#![cfg(all(feature = "native", not(target_arch = "wasm32")))]
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use multicast::cli::Cli;
use multicast::command::{CommandContext, CommandDef, CommandHandler};
use multicast::output::CommandResult;
use multicast_workflows::Workflows;
use serde_json::{Value, json};
struct Echo;
#[async_trait::async_trait]
impl CommandHandler for Echo {
async fn run(&self, _context: CommandContext) -> CommandResult {
CommandResult::Ok {
data: Value::Null,
cta: None,
exit_code: None,
}
}
}
fn attach(workflows: Workflows) -> Result<Cli, String> {
workflows
.store_path("/nonexistent/never-opened.sqlite")
.shipped(
"twice",
"Echo twice",
json!({"type": "object", "properties": {}, "additionalProperties": false}),
"async () => { await tool.echo({}); return tool.echo({}); }",
)
.attach(Cli::create("tool").command("echo", CommandDef::build("echo", Echo).done()))
}
fn rejection(workflows: Workflows) -> String {
attach(workflows).err().expect("archetype accepted")
}
#[test]
fn accepts_an_archetype_over_commands_and_shipped_workflows() {
let attached = attach(Workflows::new().archetype(
"focus",
"Echo things",
"Call echo, or twice for two echoes.",
["echo", "twice"],
));
assert!(attached.is_ok(), "{:?}", attached.err());
}
#[test]
fn rejects_names_that_collide_with_commands_groups_or_workflows() {
for name in ["echo", "workflows", "archetypes", "twice"] {
let error = rejection(Workflows::new().archetype(name, "Summary", "Guidance", ["echo"]));
assert!(error.contains(&format!("'{name}'")), "{name}: {error}");
}
}
#[test]
fn rejects_an_archetype_shipped_twice() {
let error = rejection(
Workflows::new()
.archetype("focus", "One", "Guidance", ["echo"])
.archetype("focus", "Two", "Guidance", ["echo"]),
);
assert!(error.contains("focus"), "{error}");
}
#[test]
fn rejects_scope_outside_commands_and_shipped_workflows() {
for entry in ["missing", "workflows", "archetypes"] {
let error = rejection(Workflows::new().archetype("focus", "Summary", "Guidance", [entry]));
assert!(
error.contains("is not a command or shipped workflow"),
"{entry}: {error}"
);
}
}
#[test]
fn rejects_an_archetype_in_scope() {
let error = rejection(
Workflows::new()
.archetype("inner", "Inner", "Guidance", ["echo"])
.archetype("outer", "Outer", "Guidance", ["inner"]),
);
assert!(error.contains("scopes archetype"), "{error}");
}
#[test]
fn rejects_incomplete_definitions() {
let empty: [&str; 0] = [];
for (workflows, expected) in [
(
Workflows::new().archetype("focus", "Summary", "Guidance", empty),
"at least one",
),
(
Workflows::new().archetype("focus", "Summary", " ", ["echo"]),
"needs instructions",
),
(
Workflows::new().archetype("focus", "", "Guidance", ["echo"]),
"needs a summary",
),
(
Workflows::new().archetype("focus", "Summary", "Guidance", ["echo", "echo"]),
"twice",
),
] {
let error = rejection(workflows);
assert!(error.contains(expected), "{expected}: {error}");
}
}
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_WITHOUT_NOTE");
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 = 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) -> String {
std::fs::read_to_string(self.log_path()).unwrap_or_default()
}
fn save(&self, name: &str, instructions: &str, tools: &str) -> (i32, Value) {
self.run(&[
"archetypes",
"save",
name,
"--summary",
"Add things",
"--instructions",
instructions,
"--tools",
tools,
])
}
}
fn read_only() -> Value {
json!({"readOnlyHint": true, "destructiveHint": false, "openWorldHint": false})
}
#[test]
fn shipped_activation_returns_guidance_and_scoped_contracts() {
let fixture = Fixture::new();
let (code, value) = fixture.run(&["arithmetic", "--task", "Average 3, 5, and 10"]);
assert_eq!(code, 0, "{value}");
assert_eq!(
value,
json!({
"archetype": "arithmetic",
"origin": "shipped",
"summary": "Answer integer arithmetic questions",
"guidance": "Break the question into sums and divisions. Prefer a shipped workflow \
when one matches the whole question; otherwise call sum and divide.",
"task": "Average 3, 5, and 10",
"tools": [
{
"name": "sum",
"description": "Add two integers",
"inputSchema": {
"type": "object",
"properties": {
"left": {"type": "number", "description": "Left operand."},
"right": {"type": "number", "description": "Right operand."}
},
"required": ["left", "right"]
},
"annotations": read_only()
},
{
"name": "divide",
"description": "Divide two integers, rounding toward zero",
"inputSchema": {
"type": "object",
"properties": {
"numerator": {"type": "number", "description": "Dividend."},
"denominator": {"type": "number", "description": "Divisor."}
},
"required": ["numerator", "denominator"]
},
"annotations": read_only()
}
],
"workflows": [
{
"name": "add-three",
"description": "Add three integers",
"origin": "shipped",
"inputSchema": {
"type": "object",
"properties": {
"a": {"type": "integer"},
"b": {"type": "integer"},
"c": {"type": "integer"}
},
"required": ["a", "b", "c"],
"additionalProperties": false
}
},
{
"name": "ratio",
"description": "Divide the sum of two integers by a third",
"origin": "shipped",
"inputSchema": {
"type": "object",
"properties": {
"left": {"type": "integer"},
"right": {"type": "integer"},
"by": {"type": "integer"}
},
"required": ["left", "right", "by"],
"additionalProperties": false
}
}
],
"unavailable": []
})
);
assert_eq!(fixture.commands_run(), "");
let (code, value) = fixture.run(&["slow"]);
assert_eq!(code, 0, "{value}");
}
#[test]
fn saved_archetypes_persist_across_processes_until_deleted() {
let fixture = Fixture::new();
let (code, saved) = fixture.save("adder", "Use sum twice.", "sum,add-three");
assert_eq!(code, 0, "{saved}");
assert_eq!(
saved,
json!({
"name": "adder",
"summary": "Add things",
"origin": "saved",
"scope": ["sum", "add-three"],
"instructions": "Use sum twice."
})
);
let (code, listed) = fixture.run(&["archetypes", "list"]);
assert_eq!(code, 0, "{listed}");
assert_eq!(
listed,
json!([
{
"name": "arithmetic",
"summary": "Answer integer arithmetic questions",
"origin": "shipped",
"scope": ["sum", "divide", "add-three", "ratio"]
},
{
"name": "bookkeeping",
"summary": "Record arithmetic results as notes",
"origin": "shipped",
"scope": ["sum", "note", "sum-and-note"]
},
{
"name": "adder",
"summary": "Add things",
"origin": "saved",
"scope": ["sum", "add-three"]
}
])
);
let (code, shown) = fixture.run(&["archetypes", "show", "adder"]);
assert_eq!(code, 0, "{shown}");
assert_eq!(shown["instructions"], "Use sum twice.");
let (code, active) = fixture.run(&["archetypes", "activate", "adder"]);
assert_eq!(code, 0, "{active}");
assert_eq!(active["origin"], "saved");
assert_eq!(active["guidance"], "Use sum twice.");
assert_eq!(active["task"], Value::Null);
let names = |list: &Value| -> Vec<String> {
list.as_array()
.unwrap()
.iter()
.map(|item| item["name"].as_str().unwrap().to_string())
.collect()
};
assert_eq!(names(&active["tools"]), ["sum"]);
assert_eq!(names(&active["workflows"]), ["add-three"]);
let (code, _) = fixture.save("adder", "Use add-three.", "add-three");
assert_eq!(code, 0);
let (_, shown) = fixture.run(&["archetypes", "show", "adder"]);
assert_eq!(shown["instructions"], "Use add-three.");
assert_eq!(shown["scope"], json!(["add-three"]));
let (code, deleted) = fixture.run(&["archetypes", "delete", "adder"]);
assert_eq!(code, 0, "{deleted}");
assert_eq!(deleted, json!({"deleted": "adder"}));
let (code, missing) = fixture.run(&["archetypes", "activate", "adder"]);
assert_ne!(code, 0);
assert_eq!(missing["code"], "ARCHETYPE_NOT_FOUND");
let (code, missing) = fixture.run(&["archetypes", "delete", "adder"]);
assert_ne!(code, 0);
assert_eq!(missing["code"], "ARCHETYPE_NOT_FOUND");
assert_eq!(fixture.commands_run(), "");
}
#[test]
fn shipped_archetypes_cannot_be_replaced_or_deleted() {
let fixture = Fixture::new();
let (code, value) = fixture.save("arithmetic", "Replaced.", "sum");
assert_ne!(code, 0);
assert_eq!(value["code"], "ARCHETYPE_SHIPPED");
let (code, value) = fixture.run(&["archetypes", "delete", "arithmetic"]);
assert_ne!(code, 0);
assert_eq!(value["code"], "ARCHETYPE_SHIPPED");
let (_, shown) = fixture.run(&["archetypes", "show", "arithmetic"]);
assert_eq!(shown["origin"], "shipped");
assert_ne!(shown["instructions"], "Replaced.");
}
#[test]
fn shipped_archetypes_shadow_saved_ones_with_the_same_name() {
let fixture = Fixture::new();
let without_note = [("MATH_WITHOUT_NOTE", "1")];
let (code, saved) = fixture.run_env(
&without_note,
&[
"archetypes",
"save",
"bookkeeping",
"--summary",
"Operator bookkeeping",
"--instructions",
"Operator guidance.",
"--tools",
"sum",
],
);
assert_eq!(code, 0, "{saved}");
let (_, listed) = fixture.run(&["archetypes", "list"]);
let bookkeeping: Vec<&Value> = listed
.as_array()
.unwrap()
.iter()
.filter(|entry| entry["name"] == "bookkeeping")
.collect();
assert_eq!(bookkeeping.len(), 1, "{listed}");
assert_eq!(bookkeeping[0]["origin"], "shipped");
let (_, active) = fixture.run(&["archetypes", "activate", "bookkeeping"]);
assert_eq!(active["origin"], "shipped");
assert_eq!(active["summary"], "Record arithmetic results as notes");
let (_, report) = fixture.run(&["workflows", "doctor"]);
assert!(
report["findings"]
.as_array()
.unwrap()
.iter()
.any(|finding| {
finding["check"] == "archetype-shadowed" && finding["workflow"] == "bookkeeping"
}),
"{report}"
);
let (_, active) = fixture.run_env(&without_note, &["archetypes", "activate", "bookkeeping"]);
assert_eq!(active["origin"], "saved");
assert_eq!(active["guidance"], "Operator guidance.");
}
#[test]
fn save_rejects_invalid_names_and_scope() {
let fixture = Fixture::new();
let (code, _) = fixture.save("adder", "Use sum.", "sum");
assert_eq!(code, 0);
for (name, tools) in [
("sum", "sum"),
("add-three", "sum"),
("other", "missing"),
("other", "arithmetic"),
("other", "adder"),
("other", "workflows"),
("other", "archetypes"),
("other", "sum,sum"),
] {
let (code, value) = fixture.save(name, "Guidance.", tools);
assert_ne!(code, 0, "{name} {tools}: {value}");
assert_eq!(
value["code"], "INVALID_ARCHETYPE",
"{name} {tools}: {value}"
);
}
let (_, listed) = fixture.run(&["archetypes", "list"]);
assert_eq!(listed.as_array().unwrap().len(), 3, "{listed}");
}
#[test]
fn doctor_reports_saved_archetypes_whose_scope_disappeared() {
let fixture = Fixture::new();
let (code, _) = fixture.save("noter", "Note the sum.", "note,sum-and-note,sum");
assert_eq!(code, 0);
let (code, report) = fixture.run(&["workflows", "doctor"]);
assert_eq!(code, 0, "{report}");
assert_eq!(report["findings"], json!([]));
let without_note = [("MATH_WITHOUT_NOTE", "1")];
let (_, report) = fixture.run_env(&without_note, &["workflows", "doctor"]);
assert_eq!(report["healthy"], false, "{report}");
let findings: Vec<(&str, &str, &str)> = report["findings"]
.as_array()
.unwrap()
.iter()
.map(|finding| {
(
finding["severity"].as_str().unwrap(),
finding["check"].as_str().unwrap(),
finding["workflow"].as_str().unwrap(),
)
})
.collect();
assert!(
findings.contains(&("error", "archetype-missing-scope", "noter")),
"{report}"
);
let (code, active) = fixture.run_env(&without_note, &["archetypes", "activate", "noter"]);
assert_eq!(code, 0, "{active}");
assert_eq!(active["unavailable"], json!(["note", "sum-and-note"]));
}
struct McpSession {
child: std::process::Child,
stdin: std::process::ChildStdin,
stdout: BufReader<std::process::ChildStdout>,
next_id: u64,
}
impl McpSession {
fn start(fixture: &Fixture) -> Self {
let mut child = fixture
.command(&["--mcp"])
.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": "archetypes-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;
}
}
}
fn call(&mut self, tool: &str, arguments: Value) -> Value {
let response = self.request(json!({"method": "tools/call", "params": {
"name": tool, "arguments": arguments
}}));
assert_eq!(response["result"]["isError"], false, "{response}");
serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap()
}
}
impl Drop for McpSession {
fn drop(&mut self) {
self.child.kill().ok();
self.child.wait().ok();
}
}
#[test]
fn archetype_tool_contracts_ignore_archetype_text() {
let fixture = Fixture::new();
let details = |name: &str| {
let mut session = McpSession::start(&fixture);
session.call("get_tool_details", json!({"name": name}))
};
let shipped = details("arithmetic");
assert_eq!(
shipped["description"],
"Answer integer arithmetic questions"
);
assert_eq!(
shipped["inputSchema"]["properties"]["task"]["type"], "string",
"{shipped}"
);
assert_eq!(
shipped["outputSchema"]["required"],
json!([
"archetype",
"origin",
"summary",
"guidance",
"task",
"tools",
"workflows",
"unavailable"
])
);
assert!(
!shipped.to_string().contains("Break the question"),
"instructions leaked into the contract: {shipped}"
);
let before = details("archetypes_activate");
fixture.save("adder", "First guidance.", "sum");
let first = details("archetypes_activate");
fixture.save("adder", "Second, longer guidance.", "sum,add-three");
let second = details("archetypes_activate");
assert_eq!(before, first);
assert_eq!(first, second);
assert_eq!(before["outputSchema"], shipped["outputSchema"]);
let mut session = McpSession::start(&fixture);
let activated = session.call(
"call_read_tool",
json!({"name": "archetypes_activate", "arguments": {"name": "adder", "task": "2+2"}}),
);
assert_eq!(activated["guidance"], "Second, longer guidance.");
assert_eq!(activated["task"], "2+2");
}
#[test]
fn shipped_archetypes_publish_as_prompts_and_saved_ones_do_not() {
let fixture = Fixture::new();
assert_eq!(fixture.save("adder", "Saved guidance.", "sum").0, 0);
let mut session = McpSession::start(&fixture);
let listed = session.request(json!({"method": "prompts/list", "params": {}}));
let names = listed["result"]["prompts"]
.as_array()
.unwrap_or_else(|| panic!("{listed}"))
.iter()
.map(|prompt| prompt["name"].as_str().unwrap())
.collect::<Vec<_>>();
assert_eq!(names, ["arithmetic", "bookkeeping"]);
assert_eq!(
listed["result"]["prompts"][0],
json!({
"name": "arithmetic",
"description": "Answer integer arithmetic questions",
"arguments": [{
"name": "task",
"description": "The task to focus on.",
"required": false,
}],
})
);
let fetched = session.request(json!({"method": "prompts/get", "params": {
"name": "arithmetic", "arguments": {"task": "6/3"}
}}));
assert_eq!(
fetched["result"],
json!({
"description": "Answer integer arithmetic questions",
"messages": [{
"role": "user",
"content": {
"type": "text",
"text": "Break the question into sums and divisions. Prefer a shipped workflow when one matches the whole question; otherwise call sum and divide.\n\nTools for this task: sum, divide, add-three, ratio.\n\nTask: 6/3",
},
}],
})
);
let saved = session.request(json!({"method": "prompts/get", "params": {"name": "adder"}}));
assert_eq!(saved["error"]["code"], -32602, "{saved}");
}
#[test]
fn llms_full_includes_the_shipped_archetypes() {
let fixture = Fixture::new();
assert_eq!(fixture.save("adder", "Saved guidance.", "sum").0, 0);
let output = fixture.command(&["--llms-full"]).output().unwrap();
assert!(output.status.success());
let manual = String::from_utf8(output.stdout).unwrap();
let section = manual
.split_once("## Archetypes\n")
.unwrap_or_else(|| panic!("no archetypes section:\n{manual}"))
.1;
assert!(section.starts_with(
"\n### arithmetic\n\nAnswer integer arithmetic questions\n\nBreak the question into sums and divisions. Prefer a shipped workflow when one matches the whole question; otherwise call sum and divide.\n\nCommands: `sum`, `divide`, `add-three`, `ratio`\n\n### bookkeeping\n"
), "{section}");
assert!(!section.contains("Saved guidance."), "{section}");
}