1use std::collections::BTreeMap;
4use std::sync::{Arc, Mutex};
5
6use async_trait::async_trait;
7#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
8use multicast_codemode::{CodeMode, MemoryStore};
9use multicast_codemode::{
10 CodeModeRunOptions, CodeModeService, Connector, ConnectorDescription, ConnectorTool,
11 ExecutionState, ExecutionStatus, LogEntryState, MulticastConnector, ToolAnnotations,
12 ToolContext, ToolPolicy,
13};
14#[cfg(all(feature = "native", not(target_arch = "wasm32")))]
15use multicast_codemode_local::{LocalCodeModeService, LocalExecutor, LocalExecutorOptions};
16use serde::{Deserialize, Serialize};
17use serde_json::{Value, json};
18
19use crate::{Resolved, State, program};
20
21pub const MAX_FIXTURE_BYTES: usize = 16 * 1024 * 1024;
23
24#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26#[serde(rename_all = "camelCase", deny_unknown_fields)]
27pub struct FixtureContract {
28 pub input_schema: Value,
30 pub output_schema: Option<Value>,
32 pub annotations: ToolAnnotations,
34 pub policy: ToolPolicy,
36}
37
38impl From<&ConnectorTool> for FixtureContract {
39 fn from(tool: &ConnectorTool) -> Self {
40 Self {
41 input_schema: tool.input_schema.clone(),
42 output_schema: tool.output_schema.clone(),
43 annotations: tool.annotations.clone(),
44 policy: tool.policy,
45 }
46 }
47}
48
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase", deny_unknown_fields)]
52pub struct FixtureCall {
53 pub method: String,
55 pub arguments: Value,
57 pub result: Value,
59}
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase", deny_unknown_fields)]
69pub struct WorkflowFixture {
70 pub format_version: u32,
72 pub workflow: String,
74 pub captured_version: String,
76 pub connector: String,
78 pub input_schema: Option<Value>,
80 pub input: Value,
82 pub max_attempts: u32,
84 pub contracts: BTreeMap<String, FixtureContract>,
86 pub calls: Vec<FixtureCall>,
88 pub expected: Value,
90}
91
92impl State {
93 pub(super) async fn capture_fixture(
94 &self,
95 workflow: &Resolved,
96 input: Value,
97 execution_id: &str,
98 ) -> Result<Value, String> {
99 let (input, code) = program(workflow, input)?;
100 let service = self.service().await?;
101 let execution = service.execution(execution_id.into()).await?;
102 if execution.status != ExecutionStatus::Completed || execution.code != code {
103 return Err("Capture requires a completed execution of this workflow and input".into());
104 }
105 let description = MulticastConnector::new(self.catalog.clone())
106 .describe()
107 .await?;
108 let mut contracts = BTreeMap::new();
109 let mut calls = Vec::new();
110 for entry in &execution.log {
111 if entry.connector == "codemode" {
112 continue;
113 }
114 if entry.connector != description.name || entry.state != LogEntryState::Applied {
115 return Err(format!(
116 "Step {} has no completed command observation",
117 entry.seq
118 ));
119 }
120 let tool = description
121 .tools
122 .iter()
123 .find(|tool| tool.name == entry.method)
124 .ok_or_else(|| format!("Command '{}' no longer exists", entry.method))?;
125 if tool.policy.requires_approval != entry.requires_approval
126 || (tool.policy.replay == multicast_codemode::ReplayPolicy::Reexecute)
127 != entry.ephemeral
128 {
129 return Err(format!(
130 "Policy changed since step {} ran; capture a new run",
131 entry.seq
132 ));
133 }
134 let result = entry.result.clone().ok_or_else(|| {
135 format!(
136 "Step {} has no recorded result; capture a new run",
137 entry.seq
138 )
139 })?;
140 contracts.insert(entry.method.clone(), FixtureContract::from(tool));
141 calls.push(FixtureCall {
142 method: entry.method.clone(),
143 arguments: observed_value(service, execution_id, entry.arguments.clone()).await?,
144 result: observed_value(service, execution_id, result).await?,
145 });
146 }
147 let fixture = WorkflowFixture {
148 format_version: 1,
149 workflow: workflow.name.clone(),
150 captured_version: workflow.version(),
151 connector: description.name,
152 input_schema: workflow.input_schema.clone(),
153 input,
154 max_attempts: self
155 .retry
156 .max_attempts
157 .clamp(1, multicast_codemode::MAX_CALL_ATTEMPTS),
158 contracts,
159 calls,
160 expected: observed_value(
161 service,
162 execution_id,
163 execution
164 .result
165 .ok_or("Completed execution has no result")?,
166 )
167 .await?,
168 };
169 let bytes = serde_json::to_vec(&fixture).map_err(|error| error.to_string())?;
170 if bytes.len() > MAX_FIXTURE_BYTES {
171 return Err("Fixture exceeds the 16 MiB limit".into());
172 }
173 serde_json::to_value(fixture).map_err(|error| error.to_string())
174 }
175
176 pub(super) async fn check_fixture(
177 &self,
178 workflow: &Resolved,
179 path: &str,
180 ) -> Result<Value, String> {
181 let bytes = if let Some(host) = &self.host {
182 host.read_fixture(path)?
183 } else {
184 #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
185 {
186 use std::io::Read;
188 let file = std::fs::File::open(path)
189 .map_err(|error| format!("Cannot read fixture: {error}"))?;
190 let mut bytes = Vec::new();
191 file.take(MAX_FIXTURE_BYTES as u64 + 1)
192 .read_to_end(&mut bytes)
193 .map_err(|error| format!("Cannot read fixture: {error}"))?;
194 bytes
195 }
196 #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
197 {
198 return Err("A workflow host is required".into());
199 }
200 };
201 if bytes.len() > MAX_FIXTURE_BYTES {
202 return Err("Fixture exceeds the 16 MiB limit".into());
203 }
204 let fixture: WorkflowFixture =
205 serde_json::from_slice(&bytes).map_err(|error| format!("Invalid fixture: {error}"))?;
206 if fixture.format_version != 1 || fixture.workflow != workflow.name {
207 return Err("Fixture format or workflow name does not match".into());
208 }
209 if fixture.input_schema != workflow.input_schema {
210 return Err("Workflow input schema changed; review and recapture the fixture".into());
211 }
212 if fixture.max_attempts
213 != self
214 .retry
215 .max_attempts
216 .clamp(1, multicast_codemode::MAX_CALL_ATTEMPTS)
217 {
218 return Err("Workflow retry budget changed; review and recapture the fixture".into());
219 }
220 let (_, code) = program(workflow, fixture.input.clone())?;
221 let mut description = MulticastConnector::new(self.catalog.clone())
222 .describe()
223 .await?;
224 if description.name != fixture.connector {
225 return Err("Fixture connector namespace changed".into());
226 }
227 for (method, contract) in &fixture.contracts {
228 let current = description
229 .tools
230 .iter()
231 .find(|tool| &tool.name == method)
232 .ok_or_else(|| format!("Command '{method}' no longer exists"))?;
233 if FixtureContract::from(current) != *contract {
234 return Err(format!(
235 "Command '{method}' contract or policy changed; review and recapture the fixture"
236 ));
237 }
238 }
239 if fixture
240 .calls
241 .iter()
242 .any(|call| !fixture.contracts.contains_key(&call.method))
243 {
244 return Err("Fixture call has no pinned contract".into());
245 }
246 for tool in &mut description.tools {
249 tool.policy = ToolPolicy::default();
250 }
251 let cursor = Arc::new(Mutex::new(Cursor::default()));
252 let connector = Arc::new(FixtureConnector {
253 description,
254 calls: fixture.calls.clone(),
255 cursor: cursor.clone(),
256 });
257 let service = if let Some(host) = &self.host {
258 host.fixture_service(vec![connector])?
259 } else {
260 #[cfg(all(feature = "native", not(target_arch = "wasm32")))]
261 {
262 let local = LocalCodeModeService::spawn(move || {
263 CodeMode::new(
264 Arc::new(MemoryStore::default()),
265 LocalExecutor::new(LocalExecutorOptions::default()),
266 vec![connector],
267 )
268 })?;
269 Arc::new(local) as Arc<dyn CodeModeService>
270 }
271 #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))]
272 {
273 return Err("A workflow host is required".into());
274 }
275 };
276 let execution = service.execute(code, CodeModeRunOptions::default()).await?;
277 let mut execution = self.settle(service.as_ref(), execution).await?;
278 if let Some(result) = execution.result.take() {
279 execution.result = Some(observed_value(service.as_ref(), &execution.id, result).await?);
280 }
281 let cursor = cursor.lock().map_err(|error| error.to_string())?;
282 check_observations(&fixture, &cursor, &execution)?;
283 Ok(
284 json!({"workflow": workflow.name, "passed": true, "calls": cursor.next, "version": workflow.version()}),
285 )
286 }
287}
288
289async fn observed_value(
290 service: &dyn CodeModeService,
291 execution_id: &str,
292 value: Value,
293) -> Result<Value, String> {
294 if let Some(values) = value.as_object()
295 && values.len() == 1
296 && let Some(reference) = values.get("$artifact")
297 {
298 let reference: multicast_codemode::ArtifactRef =
299 serde_json::from_value(reference.clone()).map_err(|error| error.to_string())?;
300 if reference.bytes > MAX_FIXTURE_BYTES {
301 return Err("Fixture exceeds the 16 MiB limit".into());
302 }
303 return service.artifact(execution_id.into(), reference.id).await;
304 }
305 Ok(value)
306}
307
308#[derive(Default)]
309struct Cursor {
310 next: usize,
311 failure: Option<String>,
312}
313
314struct FixtureConnector {
315 description: ConnectorDescription,
316 calls: Vec<FixtureCall>,
317 cursor: Arc<Mutex<Cursor>>,
318}
319
320#[async_trait]
321impl Connector for FixtureConnector {
322 fn name(&self) -> &str {
323 &self.description.name
324 }
325
326 async fn describe(&self) -> Result<ConnectorDescription, String> {
327 Ok(self.description.clone())
328 }
329
330 async fn execute(
331 &self,
332 method: &str,
333 arguments: Value,
334 _: &ToolContext,
335 ) -> Result<Value, String> {
336 let mut cursor = self.cursor.lock().map_err(|error| error.to_string())?;
337 if let Some(failure) = &cursor.failure {
338 return Err(failure.clone());
339 }
340 let expected = self.calls.get(cursor.next);
341 if expected.is_none_or(|call| call.method != method || call.arguments != arguments) {
342 let message = format!(
343 "Call {} differs from the fixture: observed {method}({arguments})",
344 cursor.next
345 );
346 cursor.failure = Some(message.clone());
347 return Err(message);
348 }
349 cursor.next += 1;
350 Ok(expected.expect("checked above").result.clone())
351 }
352}
353
354fn check_observations(
355 fixture: &WorkflowFixture,
356 cursor: &Cursor,
357 execution: &ExecutionState,
358) -> Result<(), String> {
359 if let Some(failure) = &cursor.failure {
360 return Err(failure.clone());
361 }
362 if execution.status != ExecutionStatus::Completed {
363 return Err(format!(
364 "Offline workflow did not complete: {}",
365 execution.error.as_deref().unwrap_or("no result")
366 ));
367 }
368 if cursor.next != fixture.calls.len() {
369 return Err(format!(
370 "Workflow made {} calls; fixture requires {}",
371 cursor.next,
372 fixture.calls.len()
373 ));
374 }
375 if execution.result.as_ref() != Some(&fixture.expected) {
376 return Err("Workflow result differs from the reviewed fixture expectation".into());
377 }
378 Ok(())
379}