返回 CodeWhale
vm_tests.rs
根目录 / crates / workflow-js / tests / vm_tests.rs
1 //! End-to-end tests for the Workflow JS runtime against a fake driver.
2
3 use std::sync::Arc;
4 use std::time::Duration;
5
6 use codewhale_workflow_js::testing::{FakeDriver, FakeReply};
7 use codewhale_workflow_js::{ProgressEvent, WorkflowJsError, WorkflowRunCancel, WorkflowVm};
8 use serde_json::json;
9
10 async fn run(
11 driver: &Arc<FakeDriver>,
12 source: &str,
13 args: serde_json::Value,
14 ) -> Result<serde_json::Value, WorkflowJsError> {
15 WorkflowVm::new()
16 .run_script(
17 source,
18 args,
19 driver.clone() as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
20 )
21 .await
22 }
23
24 fn script_message(result: Result<serde_json::Value, WorkflowJsError>) -> String {
25 match result {
26 Err(WorkflowJsError::Script(message)) => message,
27 other => panic!("expected script error, got {other:?}"),
28 }
29 }
30
31 #[tokio::test]
32 async fn plain_return_value_round_trips() {
33 let driver = Arc::new(FakeDriver::new());
34 let value = run(&driver, "return 1 + 1;", json!(null)).await.unwrap();
35 assert_eq!(value, json!(2));
36 }
37
38 #[tokio::test]
39 async fn undefined_return_becomes_null() {
40 let driver = Arc::new(FakeDriver::new());
41 let value = run(&driver, "const x = 1;", json!(null)).await.unwrap();
42 assert_eq!(value, json!(null));
43 }
44
45 #[tokio::test]
46 async fn args_global_is_the_invocation_input() {
47 let driver = Arc::new(FakeDriver::new());
48 let value = run(
49 &driver,
50 "return { sum: args.x + 1, tag: args.tags[0] };",
51 json!({"x": 41, "tags": ["release"]}),
52 )
53 .await
54 .unwrap();
55 assert_eq!(value, json!({"sum": 42, "tag": "release"}));
56 }
57
58 #[tokio::test]
59 async fn checked_in_best_of_n_search_recipe_runs_with_structured_receipts() {
60 let driver = Arc::new(FakeDriver::new());
61 for index in 1..=2 {
62 driver.on(
63 // Rules match the driver-visible `TaskRequest.description`, which
64 // is the full instruction text (the VM's `prompt` alias wins over
65 // a short label). Match the unique per-candidate suffix line.
66 &format!("candidate_id=cand_{index:03} of 2."),
67 FakeReply::Complete(
68 json!({
69 "candidate_id": format!("cand_{index:03}"),
70 "hypothesis": "bounded fixture",
71 "modified_paths": ["src/lib.rs"],
72 "commands_run": ["cargo test --locked"],
73 "self_verdict": "pass",
74 "known_risks": [],
75 "artifact_refs": [format!("patch:cand_{index:03}")]
76 })
77 .to_string(),
78 ),
79 );
80 }
81 driver.on(
82 "read-only tournament judge",
83 FakeReply::Complete(
84 json!({
85 "winner_id": "cand_001",
86 "ranking": ["cand_001", "cand_002"],
87 "verification_required": true,
88 "reasons": ["fixture score"]
89 })
90 .to_string(),
91 ),
92 );
93
94 let value = run(
95 &driver,
96 include_str!("../../../.codewhale/workflows/operate_best_of_n.workflow.js"),
97 json!({
98 "brief": "Implement the fixture",
99 "strategy": "search",
100 "n": 2,
101 "writeRoots": ["src"],
102 "model": "deepseek-v4-flash",
103 "thinking": "max"
104 }),
105 )
106 .await
107 .expect("checked-in search recipe should execute");
108
109 assert_eq!(value["scenario"], "operate-search");
110 assert_eq!(value["review"]["winner_id"], "cand_001");
111 assert_eq!(driver.spawn_count(), 3);
112 let requests = driver.requests();
113 assert_eq!(requests[0].model.as_deref(), Some("deepseek-v4-flash"));
114 assert_eq!(requests[0].thinking.as_deref(), Some("max"));
115 assert_eq!(requests[0].write_roots, ["src"]);
116 assert_eq!(requests[2].write_authority.as_deref(), Some("read_only"));
117 // Regression: the driver-visible description is the full instruction text,
118 // so reply rules must target text that actually reaches the driver. If a
119 // future recipe reintroduces a separate short `description` next to a long
120 // `prompt`, these needles stop matching, the FakeDriver falls back to its
121 // non-JSON "done:..." reply, and the structured receipts fail loudly.
122 assert!(
123 requests[0]
124 .description
125 .starts_with("You are one independent candidate")
126 );
127 assert!(
128 requests[0]
129 .description
130 .contains("CANDIDATE-SPECIFIC INSTRUCTION: candidate_id=cand_001 of 2.")
131 );
132 assert!(
133 requests[2]
134 .description
135 .starts_with("You are the read-only tournament judge")
136 );
137 }
138
139 #[tokio::test]
140 async fn task_prompt_wins_over_description_as_driver_visible_text() {
141 let driver = Arc::new(FakeDriver::new());
142 let value = run(
143 &driver,
144 r#"
145 return await task({
146 description: "short progress label",
147 prompt: "the real instruction",
148 });
149 "#,
150 json!(null),
151 )
152 .await
153 .unwrap();
154
155 // No rules were registered, so the FakeDriver fallback echoes the
156 // driver-visible description. The reply text proves the driver received
157 // the prompt, not the short label.
158 assert_eq!(value, json!("done:the real instruction"));
159 let requests = driver.requests();
160 assert_eq!(requests.len(), 1);
161 assert_eq!(requests[0].description, "the real instruction");
162 assert_ne!(requests[0].description, "short progress label");
163 }
164
165 #[tokio::test]
166 async fn task_round_trip_carries_all_options_and_normalizes_profile() {
167 let driver = Arc::new(FakeDriver::new());
168 let value = run(
169 &driver,
170 r#"
171 return await task({
172 description: "implement the bounded change",
173 subagentType: "implementer",
174 profile: " ALpha-1 ",
175 model: "deepseek-chat",
176 modelStrength: "faster",
177 thinking: "low",
178 cwd: "repo-a",
179 worktree: true,
180 writeAuthority: "worktree_write",
181 writeRoots: ["crates/tui/src"],
182 exactFiles: ["Cargo.toml"],
183 coordinationContracts: ["public-api"],
184 dependencies: ["issue-4619"],
185 acceptance: ["locked tests pass"],
186 allowedTools: ["read", "grep"],
187 maxDepth: 2,
188 tokenBudget: 5000,
189 maxSteps: 4,
190 wallTimeSecs: 90,
191 label: "L1",
192 phase: "P1",
193 });
194 "#,
195 json!(null),
196 )
197 .await
198 .unwrap();
199 assert_eq!(value, json!("done:implement the bounded change"));
200
201 let requests = driver.requests();
202 assert_eq!(requests.len(), 1);
203 let request = &requests[0];
204 assert_eq!(request.description, "implement the bounded change");
205 assert_eq!(request.subagent_type.as_deref(), Some("implementer"));
206 assert_eq!(request.profile.as_deref(), Some("alpha-1"));
207 assert_eq!(request.model.as_deref(), Some("deepseek-chat"));
208 assert_eq!(request.model_strength.as_deref(), Some("faster"));
209 assert_eq!(request.thinking.as_deref(), Some("low"));
210 assert_eq!(request.cwd.as_deref(), Some("repo-a"));
211 assert!(request.worktree);
212 assert_eq!(request.write_authority.as_deref(), Some("worktree_write"));
213 assert_eq!(request.write_roots, ["crates/tui/src"]);
214 assert_eq!(request.exact_files, ["Cargo.toml"]);
215 assert_eq!(request.coordination_contracts, ["public-api"]);
216 assert_eq!(request.dependencies, ["issue-4619"]);
217 assert_eq!(request.acceptance, ["locked tests pass"]);
218 assert_eq!(
219 request.allowed_tools.as_deref(),
220 Some(["read".to_string(), "grep".to_string()].as_slice())
221 );
222 assert_eq!(request.max_depth, Some(2));
223 assert_eq!(request.token_budget, Some(5000));
224 assert_eq!(request.max_steps, Some(4));
225 assert_eq!(request.wall_time_secs, Some(90));
226 assert_eq!(request.response_schema, None);
227 assert_eq!(request.label.as_deref(), Some("L1"));
228 assert_eq!(request.phase.as_deref(), Some("P1"));
229 }
230
231 #[tokio::test]
232 async fn scopeless_write_tasks_dispatch_and_leave_scope_to_the_spawn_boundary() {
233 // A Workflow script starts a writing child the same way the Agent tool
234 // does: no declared scope, so the spawn boundary claims the workspace
235 // root. The VM must not refuse it before dispatch.
236 let driver = Arc::new(FakeDriver::new());
237 run(
238 &driver,
239 r#"
240 await task({ prompt: "implement it", type: "implementer" });
241 await task({ prompt: "build it", type: "builder" });
242 await task({ prompt: "do it", type: "general" });
243 await task({ prompt: "lead it", profile: "release-lead" });
244 return await task({
245 prompt: "edit without a claim",
246 writeAuthority: "workspace_write",
247 });
248 "#,
249 json!(null),
250 )
251 .await
252 .expect("scopeless write tasks dispatch");
253 let requests = driver.requests();
254 assert_eq!(requests.len(), 5);
255 for request in &requests {
256 assert!(request.write_roots.is_empty());
257 assert!(request.exact_files.is_empty());
258 assert!(request.coordination_contracts.is_empty());
259 }
260 assert_eq!(requests[0].subagent_type.as_deref(), Some("implementer"));
261 assert_eq!(
262 requests[4].write_authority.as_deref(),
263 Some("workspace_write")
264 );
265
266 // A read-only role still cannot claim write authority.
267 let driver = Arc::new(FakeDriver::new());
268 let error = run(
269 &driver,
270 r#"return await task({ prompt: "x", type: "reviewer", writeAuthority: "workspace_write" });"#,
271 json!(null),
272 )
273 .await
274 .expect_err("read-only role with write authority")
275 .to_string();
276 assert!(
277 error.contains("read-only roles cannot declare write-capable authority"),
278 "{error}"
279 );
280 assert!(driver.requests().is_empty());
281 }
282
283 #[tokio::test]
284 async fn task_coordination_lists_deduplicate_with_hard_count_bounds() {
285 let driver = Arc::new(FakeDriver::new());
286 run(
287 &driver,
288 r#"
289 return await task({
290 prompt: "bounded edit",
291 type: "implementer",
292 writeAuthority: "workspace_write",
293 exactFiles: ["src/a.rs", "src/a.rs"],
294 dependencies: ["A", "A"],
295 acceptance: ["tests pass", "tests pass"],
296 });
297 "#,
298 json!(null),
299 )
300 .await
301 .expect("bounded unique coordination values");
302 let request = driver.requests().pop().expect("request");
303 assert_eq!(request.exact_files, ["src/a.rs"]);
304 assert_eq!(request.dependencies, ["A"]);
305 assert_eq!(request.acceptance, ["tests pass"]);
306 }
307
308 #[tokio::test]
309 async fn task_write_paths_normalize_and_reject_escape_spellings() {
310 let driver = Arc::new(FakeDriver::new());
311 run(
312 &driver,
313 r#"return await task({
314 prompt: "bounded edit",
315 type: "implementer",
316 writeRoots: ["./src//", "src"],
317 exactFiles: ["src\\lib.rs"]
318 });"#,
319 json!(null),
320 )
321 .await
322 .expect("normalized repo-relative paths");
323 let request = driver.requests().pop().expect("request");
324 assert_eq!(request.write_roots, ["src"]);
325 assert_eq!(request.exact_files, ["src/lib.rs"]);
326
327 for path in [
328 "../outside",
329 "/tmp/outside",
330 "C:\\outside",
331 "src/../../outside",
332 ] {
333 let driver = Arc::new(FakeDriver::new());
334 let source = format!(
335 "return await task({{ prompt: 'escape', type: 'implementer', writeRoots: [{}] }});",
336 serde_json::to_string(path).expect("path json")
337 );
338 let message = script_message(run(&driver, &source, json!(null)).await);
339 assert!(
340 message.contains("repo-relative") || message.contains("traversal"),
341 "{path}: {message}"
342 );
343 assert!(driver.requests().is_empty());
344 }
345 }
346
347 #[tokio::test]
348 async fn task_read_only_roles_reject_write_escalation() {
349 // Scopeless write-capable tasks dispatch (see
350 // scopeless_write_tasks_dispatch_and_leave_scope_to_the_spawn_boundary);
351 // a read-only role still cannot claim write authority, and contradictory
352 // identities are still refused.
353 for source in [
354 r#"return await task({prompt: "wrong authority", type: "reviewer", writeAuthority: "workspace_write", writeRoots: ["src"]});"#,
355 r#"return await task({prompt: "wrong authority", type: "scout", writeAuthority: "workspace_write", writeRoots: ["src"]});"#,
356 r#"return await task({prompt: "role conflict", type: "implementer", role: "reviewer", writeRoots: ["src"]});"#,
357 ] {
358 let driver = Arc::new(FakeDriver::new());
359 let message = script_message(run(&driver, source, json!(null)).await);
360 assert!(
361 message.contains("require")
362 || message.contains("cannot")
363 || message.contains("contradictory"),
364 "{message}"
365 );
366 assert!(driver.requests().is_empty());
367 }
368 }
369
370 #[tokio::test]
371 async fn task_implementer_identity_can_be_narrowed_to_read_only_authority() {
372 let driver = Arc::new(FakeDriver::new());
373 let value = run(
374 &driver,
375 r#"return await task({prompt: "verification-only plan", type: "implementer", writeAuthority: "read_only"});"#,
376 json!(null),
377 )
378 .await
379 .expect("read-only authority must safely narrow an implementer identity");
380 assert_eq!(value, json!("done:verification-only plan"));
381 let request = driver.requests().pop().expect("request");
382 assert_eq!(request.subagent_type.as_deref(), Some("implementer"));
383 assert_eq!(request.write_authority.as_deref(), Some("read_only"));
384 assert!(request.write_roots.is_empty());
385 }
386
387 #[tokio::test]
388 async fn task_accepts_prompt_and_type_aliases() {
389 let driver = Arc::new(FakeDriver::new());
390 run(
391 &driver,
392 r#"return await task({ prompt: "aliased", type: "verifier" });"#,
393 json!(null),
394 )
395 .await
396 .unwrap();
397 let request = &driver.requests()[0];
398 assert_eq!(request.description, "aliased");
399 assert_eq!(request.subagent_type.as_deref(), Some("verifier"));
400 }
401
402 #[tokio::test]
403 async fn task_title_alias_routes_to_description() {
404 let driver = Arc::new(FakeDriver::new());
405 run(
406 &driver,
407 r#"return await task({ title: "inspect the release candidate", type: "verifier" });"#,
408 json!(null),
409 )
410 .await
411 .expect("title is accepted as the task description");
412
413 let request = &driver.requests()[0];
414 assert_eq!(request.description, "inspect the release candidate");
415 assert_eq!(request.subagent_type.as_deref(), Some("verifier"));
416 }
417
418 #[tokio::test]
419 async fn task_prompt_takes_precedence_over_short_description() {
420 let driver = Arc::new(FakeDriver::new());
421 run(
422 &driver,
423 r#"return await task({
424 description: "Short progress summary",
425 prompt: "Detailed child instructions",
426 label: "fixture-compatible"
427 });"#,
428 json!(null),
429 )
430 .await
431 .unwrap();
432 let request = &driver.requests()[0];
433 assert_eq!(request.description, "Detailed child instructions");
434 assert_eq!(request.label.as_deref(), Some("fixture-compatible"));
435 }
436
437 #[tokio::test]
438 async fn task_rejects_invalid_profile_tokens() {
439 for bad in ["two words", "a=b", "a\"b", "a`b", " "] {
440 let driver = Arc::new(FakeDriver::new());
441 let source = format!(
442 "return await task({{ description: \"x\", profile: {} }});",
443 serde_json::Value::String(bad.to_string())
444 );
445 let message = script_message(run(&driver, &source, json!(null)).await);
446 assert!(message.contains("profile"), "profile {bad:?}: {message}");
447 assert_eq!(driver.spawn_count(), 0, "invalid profile must not spawn");
448 }
449 }
450
451 #[tokio::test]
452 async fn task_requires_a_description() {
453 let driver = Arc::new(FakeDriver::new());
454 let message = script_message(run(&driver, "return await task({});", json!(null)).await);
455 assert!(message.contains("description"), "{message}");
456 assert_eq!(driver.spawn_count(), 0);
457 }
458
459 #[tokio::test]
460 async fn task_rejects_unknown_option_names() {
461 let driver = Arc::new(FakeDriver::new());
462 let message = script_message(
463 run(
464 &driver,
465 r#"return await task({ description: "x", responseschema: {} });"#,
466 json!(null),
467 )
468 .await,
469 );
470 assert!(message.contains("invalid options"), "{message}");
471 assert_eq!(driver.spawn_count(), 0);
472 }
473
474 #[tokio::test]
475 async fn driver_rejection_is_catchable_in_script() {
476 let driver = Arc::new(FakeDriver::new());
477 driver.on("bad", FakeReply::Reject("admission cap".to_string()));
478 let value = run(
479 &driver,
480 r#"
481 try {
482 await task({ description: "bad idea" });
483 return "no-throw";
484 } catch (err) {
485 return String(err);
486 }
487 "#,
488 json!(null),
489 )
490 .await
491 .unwrap();
492 let text = value.as_str().unwrap();
493 assert!(text.contains("admission cap"), "{text}");
494 }
495
496 #[tokio::test]
497 async fn parallel_fan_out_maps_one_failure_to_null_slot() {
498 let driver = Arc::new(FakeDriver::new());
499 driver.on("beta", FakeReply::Fail("boom".to_string()));
500 let value = run(
501 &driver,
502 r#"
503 return await parallel([
504 () => task({ description: "alpha" }),
505 () => task({ description: "beta" }),
506 () => task({ description: "gamma" }),
507 ]);
508 "#,
509 json!(null),
510 )
511 .await
512 .unwrap();
513 assert_eq!(value, json!(["done:alpha", null, "done:gamma"]));
514 assert_eq!(driver.spawn_count(), 3);
515 }
516
517 #[tokio::test]
518 async fn parallel_logs_a_breadcrumb_when_a_slot_is_dropped_to_null() {
519 // #dogfood 0.8.67: a fan-out slot that fails for a non-schema reason still
520 // resolves to null (documented resilience), but must leave a breadcrumb in
521 // the run log so an operator can see why a slot came back null / nothing
522 // spawned — instead of a silent "completed" with no explanation.
523 let driver = Arc::new(FakeDriver::new());
524 driver.on("beta", FakeReply::Fail("boom".to_string()));
525 let value = run(
526 &driver,
527 r#"
528 return await parallel([
529 () => task({ description: "alpha" }),
530 () => task({ description: "beta" }),
531 ]);
532 "#,
533 json!(null),
534 )
535 .await
536 .unwrap();
537 assert_eq!(value, json!(["done:alpha", null]));
538 assert!(
539 driver.events().iter().any(|event| matches!(
540 event,
541 ProgressEvent::Log { message } if message.contains("dropped a failed slot")
542 )),
543 "a dropped parallel slot should leave a breadcrumb in the run log"
544 );
545 }
546
547 #[tokio::test]
548 async fn parallel_surfaces_response_schema_errors_instead_of_null() {
549 let driver = Arc::new(FakeDriver::new());
550 driver.on(
551 "bad schema",
552 FakeReply::Complete(r#"{"refuted":"yes"}"#.to_string()),
553 );
554
555 let message = script_message(
556 run(
557 &driver,
558 r#"
559 return await parallel([
560 () => task({
561 description: "bad schema",
562 responseSchema: {
563 type: "object",
564 properties: { refuted: { type: "boolean" } },
565 required: ["refuted"],
566 },
567 }),
568 ]);
569 "#,
570 json!(null),
571 )
572 .await,
573 );
574
575 // The default bounded repair (#5583) re-asks once — the fake's rule
576 // matches the repair too, so it fails identically and the run still
577 // fails loud instead of degrading to a null slot.
578 assert!(message.contains("responseSchema validation"), "{message}");
579 assert_eq!(
580 driver.spawn_count(),
581 2,
582 "default repair re-asks exactly once"
583 );
584 assert!(
585 driver.events().iter().any(|event| matches!(
586 event,
587 ProgressEvent::TaskSchemaRepairAttempted { attempt: 1, raw, .. }
588 if raw.contains("yes")
589 )),
590 "the failed first attempt should be receipted before the repair"
591 );
592 assert!(
593 driver.events().iter().any(|event| matches!(
594 event,
595 ProgressEvent::TaskSchemaValidationFailed { message, attempt: 2, .. }
596 if message.contains("responseSchema validation")
597 )),
598 "schema validation error should be emitted as workflow progress"
599 );
600 }
601
602 #[tokio::test]
603 async fn parallel_partial_mode_keeps_schema_failures_as_structured_slots() {
604 let driver = Arc::new(FakeDriver::new());
605 // Repair is disabled per-task so each slot fails terminally on its own
606 // reply; the mixed fan-out then exercises partial mode directly.
607 driver.on(
608 "good slot",
609 FakeReply::Complete(r#"{"refuted": true}"#.to_string()),
610 );
611 driver.on(
612 "bad slot",
613 FakeReply::Complete("not json at all".to_string()),
614 );
615 driver.on("dead slot", FakeReply::Fail("boom".to_string()));
616
617 let value = run(
618 &driver,
619 r#"
620 const results = await parallel([
621 () => task({
622 description: "good slot",
623 responseSchema: { "type": "object" },
624 }),
625 () => task({
626 description: "bad slot",
627 schemaRepairAttempts: 0,
628 responseSchema: { "type": "object" },
629 }),
630 () => task({ description: "dead slot" }),
631 ], { mode: "partial" });
632 return results.map((slot) =>
633 slot && typeof slot === "object" && slot.__taskError !== undefined
634 ? "error:" + slot.__taskError.kind
635 : slot === null
636 ? "null"
637 : "value:" + JSON.stringify(slot)
638 );
639 "#,
640 json!(null),
641 )
642 .await
643 .expect("partial mode completes the fan-out");
644
645 assert_eq!(
646 value,
647 json!([
648 "value:{\"refuted\":true}",
649 // The JS-level kind is the fatal "schema"; the finer decode kind
650 // (json_parse) lives on the receipt events, asserted below.
651 "error:schema",
652 // R9 behavior change: partial mode used to drop a dead subagent
653 // to `null` — indistinguishable from a slot that legitimately
654 // returned nothing. It is now a typed, inspectable failure.
655 "error:agent"
656 ])
657 );
658 // Every failed slot still leaves its terminal receipt.
659 assert!(
660 driver.events().iter().any(|event| matches!(
661 event,
662 ProgressEvent::TaskSchemaValidationFailed { kind, .. } if kind == "json_parse"
663 )),
664 "partial mode must not swallow the schema-failure receipt"
665 );
666 }
667
668 /// Audit R06-10: a cancel that lands while `task()` is still waiting on
669 /// admission ends the run instead of leaving it parked on the driver.
670 #[tokio::test]
671 async fn cancel_during_task_admission_ends_the_run() {
672 let driver = Arc::new(FakeDriver::new());
673 driver.on("gate", FakeReply::HoldAdmission);
674 let cancel = WorkflowRunCancel::new();
675 let run_cancel = cancel.clone();
676 let run_driver = driver.clone();
677 let handle = tokio::spawn(async move {
678 WorkflowVm::new()
679 .run_script_with_cancel(
680 r#"await task({ description: "gate" });"#,
681 json!(null),
682 run_driver as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
683 run_cancel,
684 )
685 .await
686 });
687
688 tokio::time::timeout(Duration::from_secs(2), async {
689 while driver.spawn_count() == 0 {
690 tokio::task::yield_now().await;
691 }
692 })
693 .await
694 .expect("task should reach admission");
695 cancel.cancel();
696
697 let result = tokio::time::timeout(Duration::from_secs(5), handle)
698 .await
699 .expect("the run must end once cancelled")
700 .expect("VM task should join");
701 assert!(
702 matches!(result, Err(WorkflowJsError::Cancelled)),
703 "{result:?}"
704 );
705 }
706
707 #[tokio::test]
708 async fn parallel_partial_mode_still_fails_the_run_on_cancellation() {
709 let driver = Arc::new(FakeDriver::new());
710 driver.on("hang", FakeReply::Never);
711 let cancel = WorkflowRunCancel::new();
712 let run_cancel = cancel.clone();
713 let run_driver = driver.clone();
714 let handle = tokio::spawn(async move {
715 WorkflowVm::new()
716 .run_script_with_cancel(
717 r#"
718 await parallel([
719 () => task({ description: "hang", responseSchema: { "type": "object" } }),
720 ], { mode: "partial" });
721 "#,
722 json!(null),
723 run_driver as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
724 run_cancel,
725 )
726 .await
727 });
728
729 tokio::time::timeout(Duration::from_secs(2), async {
730 while driver.spawn_count() == 0 {
731 tokio::task::yield_now().await;
732 }
733 })
734 .await
735 .expect("task should start");
736 cancel.cancel();
737
738 let result = handle.await.expect("VM task should join");
739 assert!(
740 matches!(result, Err(WorkflowJsError::Cancelled)),
741 "partial mode must not downgrade cancellation into a slot value: {result:?}"
742 );
743 }
744
745 #[tokio::test]
746 async fn pipeline_surfaces_response_schema_errors_instead_of_null() {
747 let driver = Arc::new(FakeDriver::new());
748 driver.on(
749 "bad schema",
750 FakeReply::Complete("not json at all".to_string()),
751 );
752
753 let message = script_message(
754 run(
755 &driver,
756 r#"
757 return await pipeline(
758 ["bad schema"],
759 (description) => task({
760 description,
761 schemaRepairAttempts: 0,
762 responseSchema: {
763 type: "object",
764 properties: { refuted: { type: "boolean" } },
765 required: ["refuted"],
766 },
767 }),
768 );
769 "#,
770 json!(null),
771 )
772 .await,
773 );
774
775 // Repair disabled: the first decode failure is terminal.
776 assert!(message.contains("not valid JSON"), "{message}");
777 assert_eq!(driver.spawn_count(), 1);
778 assert!(
779 driver.events().iter().any(|event| matches!(
780 event,
781 ProgressEvent::TaskSchemaValidationFailed { kind, attempt: 1, .. }
782 if kind == "json_parse"
783 )),
784 "a disabled repair must fail terminally on attempt 1 with the parse kind"
785 );
786 }
787
788 #[tokio::test]
789 async fn prose_wrapped_json_repairs_in_one_attempt() {
790 let driver = Arc::new(FakeDriver::new());
791 // First match wins: the repair spawn's description carries the
792 // "[schema repair 2]" marker, the first attempt's does not.
793 driver.on(
794 "[schema repair",
795 FakeReply::Complete(r#"{"refuted": true}"#.to_string()),
796 );
797 driver.on(
798 "score the claim",
799 FakeReply::Complete(
800 "Sure! Happy to help. Here is my verdict:\n\
801 ```json\n{\"refuted\": true}\n```\n\
802 Let me know if you need anything else."
803 .to_string(),
804 ),
805 );
806
807 let value = run(
808 &driver,
809 r#"
810 return await task({
811 description: "score the claim",
812 responseSchema: {
813 type: "object",
814 properties: { refuted: { type: "boolean" } },
815 required: ["refuted"],
816 },
817 });
818 "#,
819 json!(null),
820 )
821 .await
822 .expect("prose-wrapped JSON should repair in one attempt");
823
824 assert_eq!(value, json!({ "refuted": true }));
825 assert_eq!(driver.spawn_count(), 2);
826 let requests = driver.requests();
827 assert_eq!(requests[0].response_schema, requests[1].response_schema);
828 assert!(
829 requests[1].description.starts_with("[schema repair 2]"),
830 "the repair spawn must identify itself: {}",
831 requests[1].description
832 );
833 assert!(
834 requests[1].description.contains("score the claim"),
835 "the repair prompt must embed the original task"
836 );
837 assert!(
838 driver.events().iter().any(|event| matches!(
839 event,
840 ProgressEvent::TaskSchemaRepairAttempted {
841 kind, attempt: 1, raw, raw_truncated: false, ..
842 } if kind == "json_parse" && raw.contains("Happy to help")
843 )),
844 "the prose failure should be receipted with the parse kind"
845 );
846 assert!(
847 !driver
848 .events()
849 .iter()
850 .any(|event| matches!(event, ProgressEvent::TaskSchemaValidationFailed { .. })),
851 "a successful repair must not leave a terminal schema-failure receipt"
852 );
853 }
854
855 #[tokio::test]
856 async fn schema_violation_receipt_names_the_validation_kind() {
857 let driver = Arc::new(FakeDriver::new());
858 driver.on(
859 "[schema repair",
860 FakeReply::Complete(r#"{"refuted": false}"#.to_string()),
861 );
862 driver.on(
863 "check the gate",
864 FakeReply::Complete(r#"{"refuted":"no"}"#.to_string()),
865 );
866
867 let value = run(
868 &driver,
869 r#"
870 return await task({
871 description: "check the gate",
872 responseSchema: {
873 type: "object",
874 properties: { refuted: { type: "boolean" } },
875 required: ["refuted"],
876 },
877 });
878 "#,
879 json!(null),
880 )
881 .await
882 .expect("valid JSON of the wrong shape should repair");
883
884 assert_eq!(value, json!({ "refuted": false }));
885 assert!(
886 driver.events().iter().any(|event| matches!(
887 event,
888 ProgressEvent::TaskSchemaRepairAttempted { kind, message, .. }
889 if kind == "schema_validation"
890 && message.contains("responseSchema validation")
891 )),
892 "a parsed-but-invalid reply must receipt as schema_validation, not json_parse"
893 );
894 }
895
896 #[tokio::test]
897 async fn schema_repair_attempts_is_bounded_at_the_parse_gate() {
898 let driver = Arc::new(FakeDriver::new());
899 let message = script_message(
900 run(
901 &driver,
902 r#"
903 return await task({
904 description: "bound me",
905 schemaRepairAttempts: 4,
906 responseSchema: { "type": "object" },
907 });
908 "#,
909 json!(null),
910 )
911 .await,
912 );
913 assert!(message.contains("bounded to 3"), "{message}");
914 assert_eq!(
915 driver.spawn_count(),
916 0,
917 "no child may spawn for a bad option"
918 );
919 }
920
921 #[tokio::test]
922 async fn legacy_task_wall_clock_does_not_prevent_schema_repair() {
923 let driver = Arc::new(FakeDriver::new());
924 driver.on("[schema repair", FakeReply::Complete("{}".to_string()));
925 driver.on_with_delay(
926 "slow prose",
927 FakeReply::Complete("eventually, still not json".to_string()),
928 Duration::from_millis(1_100),
929 );
930
931 let result = run(
932 &driver,
933 r#"
934 return await task({
935 description: "slow prose",
936 wallTimeSecs: 1,
937 responseSchema: { "type": "object" },
938 });
939 "#,
940 json!(null),
941 )
942 .await
943 .expect("legacy task wall time cannot stop repair");
944
945 assert_eq!(result, json!({}));
946 assert_eq!(
947 driver.spawn_count(),
948 2,
949 "schema repair follows the runtime's trusted limits"
950 );
951 }
952
953 #[tokio::test]
954 async fn cancellation_during_repair_terminates_cleanly() {
955 let driver = Arc::new(FakeDriver::new());
956 driver.on("[schema repair", FakeReply::Never);
957 driver.on(
958 "hang the repair",
959 FakeReply::Complete("prose, no json".to_string()),
960 );
961 let cancel = WorkflowRunCancel::new();
962 let run_cancel = cancel.clone();
963 let run_driver = driver.clone();
964 let handle = tokio::spawn(async move {
965 WorkflowVm::new()
966 .run_script_with_cancel(
967 r#"
968 return await task({
969 description: "hang the repair",
970 responseSchema: { "type": "object" },
971 });
972 "#,
973 json!(null),
974 run_driver as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
975 run_cancel,
976 )
977 .await
978 });
979
980 tokio::time::timeout(Duration::from_secs(2), async {
981 while driver.spawn_count() < 2 {
982 tokio::task::yield_now().await;
983 }
984 })
985 .await
986 .expect("repair should start");
987 cancel.cancel();
988
989 let result = handle.await.expect("VM task should join");
990 assert!(
991 matches!(result, Err(WorkflowJsError::Cancelled)),
992 "{result:?}"
993 );
994 assert!(
995 !driver
996 .events()
997 .iter()
998 .any(|event| matches!(event, ProgressEvent::TaskSchemaValidationFailed { .. })),
999 "cancellation must not be rewritten into a schema failure"
1000 );
1001 }
1002
1003 #[tokio::test]
1004 async fn parallel_fail_fast_rejects_with_the_typed_slot_error() {
1005 let driver = Arc::new(FakeDriver::new());
1006 driver.on("beta", FakeReply::Fail("boom".to_string()));
1007 let value = run(
1008 &driver,
1009 r#"
1010 try {
1011 await parallel([
1012 () => task({ description: "alpha" }),
1013 () => task({ description: "beta" }),
1014 ], { mode: "fail-fast" });
1015 return "no-error";
1016 } catch (err) {
1017 return (err && err.kind) + ":" + (err && err.message);
1018 }
1019 "#,
1020 json!(null),
1021 )
1022 .await
1023 .unwrap();
1024 let text = value.as_str().unwrap();
1025 assert!(
1026 // R9: a child that ran and failed is `agent`, distinct from the
1027 // `script` kind a plain `throw` in a thunk produces.
1028 text.starts_with("agent:") && text.contains("boom"),
1029 "fail-fast must reject with the typed slot error: {text}"
1030 );
1031 assert!(
1032 driver.events().iter().any(|event| matches!(
1033 event,
1034 ProgressEvent::Log { message } if message.contains("fail-fast slot error")
1035 )),
1036 "fail-fast must leave a breadcrumb with the slot error"
1037 );
1038 }
1039
1040 #[tokio::test]
1041 async fn parallel_fail_fast_cancels_still_running_siblings() {
1042 let driver = Arc::new(FakeDriver::new());
1043 driver.on("alpha", FakeReply::Never);
1044 driver.on_with_delay(
1045 "beta",
1046 FakeReply::Fail("boom".to_string()),
1047 Duration::from_millis(50),
1048 );
1049 let value = run(
1050 &driver,
1051 r#"
1052 try {
1053 await parallel([
1054 () => task({ description: "alpha" }),
1055 () => task({ description: "beta" }),
1056 ], { mode: "fail-fast" });
1057 return "no-error";
1058 } catch (err) {
1059 return err.kind;
1060 }
1061 "#,
1062 json!(null),
1063 )
1064 .await
1065 .unwrap();
1066 assert_eq!(value, json!("agent"));
1067 assert_eq!(driver.cancelled_tasks(), vec!["agent_0001".to_string()]);
1068 }
1069
1070 #[tokio::test]
1071 async fn task_errors_carry_typed_kinds() {
1072 let driver = Arc::new(FakeDriver::new());
1073 driver.on("budget", FakeReply::BudgetExhausted("limit 10".to_string()));
1074 driver.on("cancelled", FakeReply::Cancelled);
1075 driver.on("admission", FakeReply::Reject("admission cap".to_string()));
1076 let value = run(
1077 &driver,
1078 r#"
1079 const kinds = {};
1080 for (const description of ["budget", "cancelled", "admission"]) {
1081 try {
1082 await task({ description });
1083 kinds[description] = "none";
1084 } catch (err) {
1085 kinds[description] = err && err.kind;
1086 }
1087 }
1088 return kinds;
1089 "#,
1090 json!(null),
1091 )
1092 .await
1093 .unwrap();
1094 assert_eq!(
1095 value,
1096 json!({"budget": "budget", "cancelled": "cancelled", "admission": "admission"})
1097 );
1098 }
1099
1100 #[tokio::test]
1101 async fn pipeline_fail_fast_rejects_instead_of_nulling_the_item() {
1102 let value = run(
1103 &Arc::new(FakeDriver::new()),
1104 r#"
1105 const stage = async (value) => {
1106 if (value === 1) throw new Error("stage boom");
1107 return value * 2;
1108 };
1109 try {
1110 await pipeline([1, 2], { stages: [stage], mode: "fail-fast" });
1111 return "no-error";
1112 } catch (err) {
1113 return (err && err.kind) + ":" + (err && err.message);
1114 }
1115 "#,
1116 json!(null),
1117 )
1118 .await
1119 .unwrap();
1120 assert_eq!(value, json!("script:stage boom"));
1121 }
1122
1123 #[tokio::test]
1124 async fn parallel_enforces_the_1000_item_cap_without_spawning() {
1125 let driver = Arc::new(FakeDriver::new());
1126 let value = run(
1127 &driver,
1128 r#"
1129 const thunks = new Array(1001).fill(() => task({ description: "x" }));
1130 try {
1131 await parallel(thunks);
1132 return "no-throw";
1133 } catch (err) {
1134 return String(err);
1135 }
1136 "#,
1137 json!(null),
1138 )
1139 .await
1140 .unwrap();
1141 let text = value.as_str().unwrap();
1142 assert!(text.contains("max 1000"), "{text}");
1143 assert_eq!(driver.spawn_count(), 0, "cap must reject before any spawn");
1144 }
1145
1146 #[tokio::test]
1147 async fn parallel_accepts_exactly_1000_items() {
1148 let driver = Arc::new(FakeDriver::new());
1149 let value = run(
1150 &driver,
1151 r#"
1152 const thunks = new Array(1000).fill(() => Promise.resolve(1));
1153 const results = await parallel(thunks);
1154 return results.length;
1155 "#,
1156 json!(null),
1157 )
1158 .await
1159 .unwrap();
1160 assert_eq!(value, json!(1000));
1161 }
1162
1163 #[tokio::test]
1164 async fn pipeline_has_no_barrier_between_stages() {
1165 let driver = Arc::new(FakeDriver::new());
1166 // Item A crawls through stage 1; item B sprints through both stages.
1167 driver.on_with_delay(
1168 "s1:A",
1169 FakeReply::Complete("A1".to_string()),
1170 Duration::from_millis(300),
1171 );
1172 driver.on_with_delay(
1173 "s1:B",
1174 FakeReply::Complete("B1".to_string()),
1175 Duration::from_millis(20),
1176 );
1177 driver.on_with_delay(
1178 "s2:B1",
1179 FakeReply::Complete("B2".to_string()),
1180 Duration::from_millis(20),
1181 );
1182 driver.on("s2:A1", FakeReply::Complete("A2".to_string()));
1183
1184 let value = run(
1185 &driver,
1186 r#"
1187 return await pipeline(
1188 ["A", "B"],
1189 (v) => task({ description: "s1:" + v }),
1190 (v) => task({ description: "s2:" + v }),
1191 );
1192 "#,
1193 json!(null),
1194 )
1195 .await
1196 .unwrap();
1197 assert_eq!(value, json!(["A2", "B2"]));
1198
1199 // B's stage 2 must have been requested while A was still in stage 1 —
1200 // per-item chains, no stage barrier.
1201 let descriptions = driver.request_descriptions();
1202 assert_eq!(descriptions[..2], ["s1:A".to_string(), "s1:B".to_string()]);
1203 assert_eq!(
1204 descriptions[2], "s2:B1",
1205 "expected B to reach stage 2 while A was still in stage 1: {descriptions:?}"
1206 );
1207 assert_eq!(descriptions[3], "s2:A1");
1208 }
1209
1210 #[tokio::test]
1211 async fn pipeline_stage_error_drops_only_that_item() {
1212 let driver = Arc::new(FakeDriver::new());
1213 driver.on("s1:B", FakeReply::Fail("boom".to_string()));
1214 let value = run(
1215 &driver,
1216 r#"
1217 return await pipeline(
1218 ["A", "B"],
1219 (v) => task({ description: "s1:" + v }),
1220 (v) => v + "+2",
1221 );
1222 "#,
1223 json!(null),
1224 )
1225 .await
1226 .unwrap();
1227 assert_eq!(value, json!(["done:s1:A+2", null]));
1228 }
1229
1230 #[tokio::test]
1231 async fn budget_global_is_constant_unmetered_nulls() {
1232 let driver = Arc::new(FakeDriver::new());
1233 let value = run(
1234 &driver,
1235 r#"
1236 const before = budget.remaining();
1237 await task({ description: "one" });
1238 return {
1239 frozen: Object.isFrozen(budget),
1240 total: budget.total,
1241 metered: budget.metered,
1242 before,
1243 spent: budget.spent(),
1244 after: budget.remaining(),
1245 };
1246 "#,
1247 json!(null),
1248 )
1249 .await
1250 .unwrap();
1251 assert_eq!(
1252 value,
1253 json!({
1254 "frozen": true,
1255 "total": null,
1256 "metered": false,
1257 "before": null,
1258 "spent": null,
1259 "after": null,
1260 })
1261 );
1262 }
1263
1264 #[tokio::test]
1265 async fn sequential_work_continues_past_one_thousand_children() {
1266 let driver = Arc::new(FakeDriver::new());
1267 let value = run(
1268 &driver,
1269 r#"
1270 let completed = 0;
1271 for (let i = 0; i < 1001; i++) {
1272 await task({ description: "t" + i });
1273 completed++;
1274 }
1275 return completed;
1276 "#,
1277 json!(null),
1278 )
1279 .await
1280 .unwrap();
1281 assert_eq!(value, json!(1001));
1282 assert_eq!(driver.spawn_count(), 1001);
1283 }
1284
1285 #[tokio::test]
1286 async fn response_schema_returns_the_parsed_validated_object() {
1287 let driver = Arc::new(FakeDriver::new());
1288 driver.on(
1289 "check",
1290 FakeReply::Complete(r#"{"refuted": true, "confidence": 0.9}"#.to_string()),
1291 );
1292 let value = run(
1293 &driver,
1294 r#"
1295 const verdict = await task({
1296 description: "check the claim",
1297 responseSchema: {
1298 type: "object",
1299 properties: { refuted: { type: "boolean" } },
1300 required: ["refuted"],
1301 },
1302 });
1303 return verdict.refuted === true ? "refuted" : "upheld";
1304 "#,
1305 json!(null),
1306 )
1307 .await
1308 .unwrap();
1309 assert_eq!(value, json!("refuted"));
1310 assert!(driver.requests()[0].response_schema.is_some());
1311 }
1312
1313 #[tokio::test]
1314 async fn response_schema_rejects_non_json_replies() {
1315 let driver = Arc::new(FakeDriver::new());
1316 driver.on(
1317 "check",
1318 FakeReply::Complete("definitely not json".to_string()),
1319 );
1320 let message = script_message(
1321 run(
1322 &driver,
1323 r#"
1324 return await task({
1325 description: "check",
1326 responseSchema: { type: "object" },
1327 });
1328 "#,
1329 json!(null),
1330 )
1331 .await,
1332 );
1333 assert!(message.contains("not valid JSON"), "{message}");
1334 }
1335
1336 #[tokio::test]
1337 async fn response_schema_rejects_schema_violations() {
1338 let driver = Arc::new(FakeDriver::new());
1339 driver.on(
1340 "check",
1341 FakeReply::Complete(r#"{"refuted": "yes"}"#.to_string()),
1342 );
1343 let message = script_message(
1344 run(
1345 &driver,
1346 r#"
1347 return await task({
1348 description: "check",
1349 responseSchema: {
1350 type: "object",
1351 properties: { refuted: { type: "boolean" } },
1352 required: ["refuted"],
1353 },
1354 });
1355 "#,
1356 json!(null),
1357 )
1358 .await,
1359 );
1360 assert!(message.contains("responseSchema validation"), "{message}");
1361 }
1362
1363 #[tokio::test]
1364 async fn determinism_ban_date_now() {
1365 let driver = Arc::new(FakeDriver::new());
1366 let message = script_message(run(&driver, "return Date.now();", json!(null)).await);
1367 assert!(message.contains("Date.now()"), "{message}");
1368 }
1369
1370 #[tokio::test]
1371 async fn determinism_ban_math_random() {
1372 let driver = Arc::new(FakeDriver::new());
1373 let message = script_message(run(&driver, "return Math.random();", json!(null)).await);
1374 assert!(message.contains("Math.random()"), "{message}");
1375 }
1376
1377 #[tokio::test]
1378 async fn determinism_ban_new_date() {
1379 let driver = Arc::new(FakeDriver::new());
1380 let message = script_message(run(&driver, "return new Date();", json!(null)).await);
1381 assert!(message.contains("unavailable"), "{message}");
1382 }
1383
1384 /// Explicit product surface for the sandboxed Workflow VM (#4129).
1385 ///
1386 /// Only these Workflow-owned calls may exist on `globalThis` beyond standard
1387 /// ECMAScript intrinsics. If a new host global is intentionally added, update
1388 /// this list in the same PR — the fail-closed inventory test below will break
1389 /// until the allowlist is extended deliberately.
1390 const WORKFLOW_ALLOWED_GLOBALS: &[&str] = &[
1391 "task", "parallel", "pipeline", "phase", "log", "budget", "args",
1392 ];
1393
1394 /// Host / Node / Deno / browser surfaces that must never leak into the VM.
1395 ///
1396 /// Standard ECMAScript intrinsics (`Object`, `Function`, `eval`, `Promise`, …)
1397 /// remain available; this list is only host escape hatches.
1398 const SANDBOX_BANNED_GLOBALS: &[&str] = &[
1399 "process",
1400 "require",
1401 "module",
1402 "exports",
1403 "__dirname",
1404 "__filename",
1405 "Buffer",
1406 "fs",
1407 "child_process",
1408 "os",
1409 "path",
1410 "net",
1411 "http",
1412 "https",
1413 "fetch",
1414 "XMLHttpRequest",
1415 "WebSocket",
1416 "Deno",
1417 "Bun",
1418 "Worker",
1419 ];
1420
1421 #[tokio::test]
1422 async fn sandbox_exposes_only_the_documented_workflow_calls() {
1423 let driver = Arc::new(FakeDriver::new());
1424 let value = run(
1425 &driver,
1426 r#"
1427 return {
1428 task: typeof task,
1429 parallel: typeof parallel,
1430 pipeline: typeof pipeline,
1431 phase: typeof phase,
1432 log: typeof log,
1433 budget: typeof budget,
1434 args: typeof args,
1435 };
1436 "#,
1437 json!({"ok": true}),
1438 )
1439 .await
1440 .unwrap();
1441 assert_eq!(
1442 value,
1443 json!({
1444 "task": "function",
1445 "parallel": "function",
1446 "pipeline": "function",
1447 "phase": "function",
1448 "log": "function",
1449 "budget": "object",
1450 "args": "object",
1451 })
1452 );
1453 // Keep the constant and the live typeof probe in lockstep.
1454 assert_eq!(
1455 WORKFLOW_ALLOWED_GLOBALS,
1456 &[
1457 "task", "parallel", "pipeline", "phase", "log", "budget", "args"
1458 ]
1459 );
1460 }
1461
1462 #[tokio::test]
1463 async fn sandbox_blocks_host_filesystem_shell_network_and_env_surfaces() {
1464 // Each probe must either throw / reject or resolve to a clearly absent
1465 // binding. We never allow a successful host escape.
1466 let probes: &[(&str, &str)] = &[
1467 (
1468 "process.env",
1469 r#"
1470 if (typeof process !== "undefined") {
1471 return process.env;
1472 }
1473 throw new Error("process is unavailable");
1474 "#,
1475 ),
1476 (
1477 "require('fs')",
1478 r#"
1479 if (typeof require === "function") {
1480 return require("fs");
1481 }
1482 throw new Error("require is unavailable");
1483 "#,
1484 ),
1485 (
1486 "import",
1487 r#"
1488 // Dynamic import is a module-loader surface; the VM has no loader.
1489 return await import("fs");
1490 "#,
1491 ),
1492 (
1493 "fetch",
1494 r#"
1495 if (typeof fetch === "function") {
1496 return await fetch("https://example.invalid/");
1497 }
1498 throw new Error("fetch is unavailable");
1499 "#,
1500 ),
1501 (
1502 "child_process",
1503 r#"
1504 if (typeof require === "function") {
1505 return require("child_process");
1506 }
1507 if (typeof child_process !== "undefined") {
1508 return child_process;
1509 }
1510 throw new Error("child_process is unavailable");
1511 "#,
1512 ),
1513 (
1514 "Deno.env",
1515 r#"
1516 if (typeof Deno !== "undefined") {
1517 return Deno.env.toObject();
1518 }
1519 throw new Error("Deno is unavailable");
1520 "#,
1521 ),
1522 ];
1523
1524 for (label, source) in probes {
1525 let driver = Arc::new(FakeDriver::new());
1526 let result = run(&driver, source, json!(null)).await;
1527 assert!(
1528 result.is_err(),
1529 "sandbox probe `{label}` must fail closed, got {result:?}"
1530 );
1531 // No driver side-effect is expected from a sandbox probe.
1532 assert_eq!(
1533 driver.spawn_count(),
1534 0,
1535 "probe `{label}` must not spawn tasks"
1536 );
1537 }
1538 }
1539
1540 #[tokio::test]
1541 async fn sandbox_global_inventory_fails_closed_on_new_host_leaks() {
1542 let driver = Arc::new(FakeDriver::new());
1543 let value = run(
1544 &driver,
1545 r#"
1546 // Own enumerable + non-enumerable names on the global object.
1547 // Anything beyond standard ECMAScript + the Workflow allowlist is a
1548 // regression that must break this test so new leaks cannot land quietly.
1549 const names = Reflect.ownKeys(globalThis)
1550 .map((k) => String(k))
1551 .sort();
1552 return names;
1553 "#,
1554 json!(null),
1555 )
1556 .await
1557 .unwrap();
1558 let names: Vec<String> = serde_json::from_value(value).expect("name list is a JSON array");
1559
1560 // Fail closed: none of the banned host surfaces may appear.
1561 for banned in SANDBOX_BANNED_GLOBALS {
1562 assert!(
1563 !names.iter().any(|n| n == *banned),
1564 "banned global `{banned}` leaked into the Workflow VM: {names:?}"
1565 );
1566 }
1567
1568 // Every Workflow-owned call must still be present.
1569 for allowed in WORKFLOW_ALLOWED_GLOBALS {
1570 assert!(
1571 names.iter().any(|n| n == *allowed),
1572 "expected Workflow global `{allowed}` missing from inventory: {names:?}"
1573 );
1574 }
1575
1576 // Internal host helpers must not be script-visible.
1577 for internal in [
1578 "__workflow_task",
1579 "__workflow_cancel_tasks",
1580 "__workflow_log",
1581 "__workflow_every_slot_failed",
1582 "__workflow_slot_dropped",
1583 "__workflow_phase",
1584 ] {
1585 assert!(
1586 !names.iter().any(|n| n == internal),
1587 "internal host binding `{internal}` must stay hidden: {names:?}"
1588 );
1589 }
1590 }
1591
1592 #[tokio::test]
1593 async fn sandbox_rejects_commonjs_module_loader_and_eval_style_constructors() {
1594 let driver = Arc::new(FakeDriver::new());
1595 // `eval` / `Function` are standard ES, but if they are present they must
1596 // still be unable to reach host modules. The banned-global inventory above
1597 // already fails closed if Node-style loaders appear; this probe documents
1598 // the intended product message for module load attempts.
1599 let message = script_message(
1600 run(
1601 &driver,
1602 r#"
1603 if (typeof require === "function") {
1604 return require("node:fs");
1605 }
1606 throw new Error("require is unavailable");
1607 "#,
1608 json!(null),
1609 )
1610 .await,
1611 );
1612 assert!(
1613 message.contains("unavailable") || message.contains("require"),
1614 "{message}"
1615 );
1616 }
1617
1618 #[tokio::test]
1619 async fn dropping_the_run_future_cancels_outstanding_tasks() {
1620 let driver = Arc::new(FakeDriver::new());
1621 driver.on("hang", FakeReply::Never);
1622 let vm = WorkflowVm::new();
1623 {
1624 let fut = vm.run_script(
1625 "await task({ description: 'hang forever' }); return 'unreachable';",
1626 json!(null),
1627 driver.clone() as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
1628 );
1629 let outcome = tokio::time::timeout(Duration::from_millis(400), fut).await;
1630 assert!(outcome.is_err(), "run should still be pending at timeout");
1631 // The timed-out future is dropped here.
1632 }
1633 assert!(
1634 driver.cancel_all_calls() >= 1,
1635 "dropping the run future must cancel outstanding driver tasks"
1636 );
1637 assert_eq!(driver.spawn_count(), 1);
1638 }
1639
1640 #[tokio::test]
1641 async fn parallel_does_not_continue_after_external_run_cancellation() {
1642 let driver = Arc::new(FakeDriver::new());
1643 driver.on("hang", FakeReply::Never);
1644 let cancel = WorkflowRunCancel::new();
1645 let run_cancel = cancel.clone();
1646 let run_driver = driver.clone();
1647 let handle = tokio::spawn(async move {
1648 WorkflowVm::new()
1649 .run_script_with_cancel(
1650 r#"
1651 await parallel([() => task({ description: "hang" })]);
1652 phase("unreachable after cancellation");
1653 return "wrong";
1654 "#,
1655 json!(null),
1656 run_driver as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
1657 run_cancel,
1658 )
1659 .await
1660 });
1661
1662 tokio::time::timeout(Duration::from_secs(2), async {
1663 while driver.spawn_count() == 0 {
1664 tokio::task::yield_now().await;
1665 }
1666 })
1667 .await
1668 .expect("task should start");
1669 cancel.cancel();
1670
1671 let result = handle.await.expect("VM task should join");
1672 assert!(
1673 matches!(result, Err(WorkflowJsError::Cancelled)),
1674 "{result:?}"
1675 );
1676 assert!(
1677 !driver.events().iter().any(|event| matches!(
1678 event,
1679 ProgressEvent::Phase { title } if title == "unreachable after cancellation"
1680 )),
1681 "parallel() must not downgrade run cancellation into a null slot"
1682 );
1683 }
1684
1685 #[tokio::test]
1686 async fn script_error_rejects_cleanly_and_cancels_children() {
1687 let driver = Arc::new(FakeDriver::new());
1688 let result = run(
1689 &driver,
1690 r#"await task({ description: "quick" }); throw new Error("boom");"#,
1691 json!(null),
1692 )
1693 .await;
1694 let message = script_message(result);
1695 assert!(message.contains("boom"), "{message}");
1696 assert!(
1697 driver.cancel_all_calls() >= 1,
1698 "a failed run must cancel its cascade"
1699 );
1700 }
1701
1702 #[tokio::test]
1703 async fn log_and_phase_events_reach_the_driver_in_order() {
1704 let driver = Arc::new(FakeDriver::new());
1705 run(
1706 &driver,
1707 r#"
1708 phase("scan");
1709 log("a");
1710 log({ found: 2 });
1711 phase("verify");
1712 log("b");
1713 return null;
1714 "#,
1715 json!(null),
1716 )
1717 .await
1718 .unwrap();
1719 assert_eq!(
1720 driver.events(),
1721 vec![
1722 ProgressEvent::Phase {
1723 title: "scan".to_string()
1724 },
1725 ProgressEvent::Log {
1726 message: "a".to_string()
1727 },
1728 ProgressEvent::Log {
1729 message: r#"{"found":2}"#.to_string()
1730 },
1731 ProgressEvent::Phase {
1732 title: "verify".to_string()
1733 },
1734 ProgressEvent::Log {
1735 message: "b".to_string()
1736 },
1737 ]
1738 );
1739 }
1740
1741 #[tokio::test]
1742 async fn promise_all_of_tasks_resolves_concurrently() {
1743 let driver = Arc::new(FakeDriver::new());
1744 driver.on_with_delay(
1745 "left",
1746 FakeReply::Complete("L".to_string()),
1747 Duration::from_millis(50),
1748 );
1749 driver.on_with_delay(
1750 "right",
1751 FakeReply::Complete("R".to_string()),
1752 Duration::from_millis(50),
1753 );
1754 let started = std::time::Instant::now();
1755 let value = run(
1756 &driver,
1757 r#"
1758 const [a, b] = await Promise.all([
1759 task({ description: "left" }),
1760 task({ description: "right" }),
1761 ]);
1762 return a + "/" + b;
1763 "#,
1764 json!(null),
1765 )
1766 .await
1767 .unwrap();
1768 assert_eq!(value, json!("L/R"));
1769 // Two 50ms tasks awaited concurrently should not take ~100ms serially.
1770 // Generous bound to stay green on slow CI.
1771 assert!(
1772 started.elapsed() < Duration::from_millis(3000),
1773 "took {:?}",
1774 started.elapsed()
1775 );
1776 assert_eq!(driver.spawn_count(), 2);
1777 }
1778
1779 #[tokio::test]
1780 async fn export_default_async_function_runs_with_args() {
1781 let driver = Arc::new(FakeDriver::new());
1782 let source = r#"
1783 export default async function (args) {
1784 return { doubled: args.n * 2 };
1785 }
1786 "#;
1787 let value = run(&driver, source, json!({ "n": 21 })).await.unwrap();
1788 assert_eq!(value, json!({ "doubled": 42 }));
1789 }
1790
1791 #[tokio::test]
1792 async fn export_default_function_result_becomes_run_result() {
1793 let driver = Arc::new(FakeDriver::new());
1794 let source = r#"
1795 function helper() {
1796 return "from-helper";
1797 }
1798 export default function () {
1799 return helper();
1800 }
1801 "#;
1802 let value = run(&driver, source, json!(null)).await.unwrap();
1803 assert_eq!(value, json!("from-helper"));
1804 }
1805
1806 #[tokio::test]
1807 async fn export_default_non_function_value_is_returned() {
1808 let driver = Arc::new(FakeDriver::new());
1809 let value = run(&driver, "export default 7;", json!(null))
1810 .await
1811 .unwrap();
1812 assert_eq!(value, json!(7));
1813 }
1814
1815 #[tokio::test]
1816 async fn plain_scripts_are_untouched_by_export_desugaring() {
1817 let driver = Arc::new(FakeDriver::new());
1818 // A string literal mentioning `export default` must not trigger the
1819 // module desugaring path.
1820 let value = run(
1821 &driver,
1822 "const note = \"export default docs\";\nreturn note.length;",
1823 json!(null),
1824 )
1825 .await
1826 .unwrap();
1827 assert_eq!(value, json!(19));
1828 }
1829
1830 #[tokio::test]
1831 async fn export_default_examples_inside_multiline_text_are_not_desugared() {
1832 let driver = Arc::new(FakeDriver::new());
1833 let value = run(
1834 &driver,
1835 r#"
1836 const template = `
1837 export default async function (args) {
1838 return args;
1839 }
1840 `;
1841 /*
1842 export default function () {
1843 return "comment example";
1844 }
1845 */
1846 return template.includes("export default async function");
1847 "#,
1848 json!(null),
1849 )
1850 .await
1851 .unwrap();
1852 assert_eq!(value, json!(true));
1853 }
1854
1855 #[tokio::test]
1856 async fn task_accepts_agent_tool_spellings() {
1857 // The `agent` tool and `task()` are written by the same authors; a schema
1858 // that runs on one surface must not be an unknown-field error on the
1859 // other. snake_case spellings and `workspace_policy` are aliases.
1860 let driver = Arc::new(FakeDriver::new());
1861 let value = run(
1862 &driver,
1863 r#"
1864 return await task({
1865 prompt: "cross-surface schema",
1866 subagent_type: "implementer",
1867 workspace_policy: "worktree",
1868 write_authority: "worktree_write",
1869 write_roots: ["crates/tui/src"],
1870 token_budget: 5000,
1871 max_steps: 4,
1872 });
1873 "#,
1874 json!(null),
1875 )
1876 .await
1877 .unwrap();
1878 assert_eq!(value, json!("done:cross-surface schema"));
1879 let requests = driver.requests();
1880 assert_eq!(requests.len(), 1);
1881 assert!(
1882 requests[0].worktree,
1883 "workspace_policy worktree maps to worktree isolation"
1884 );
1885 assert_eq!(
1886 requests[0].write_authority.as_deref(),
1887 Some("worktree_write")
1888 );
1889 assert_eq!(requests[0].token_budget, Some(5000));
1890
1891 // "shared" is accepted and stays non-worktree; contradictions and unknown
1892 // values still fail loudly.
1893 let error = run(
1894 &driver,
1895 r#"return await task({ prompt: "x", workspacePolicy: "shared", worktree: true });"#,
1896 json!(null),
1897 )
1898 .await
1899 .unwrap_err();
1900 assert!(script_message(Err(error)).contains("conflicts with worktree"));
1901 let error = run(
1902 &driver,
1903 r#"return await task({ prompt: "x", workspacePolicy: "solo" });"#,
1904 json!(null),
1905 )
1906 .await
1907 .unwrap_err();
1908 assert!(script_message(Err(error)).contains("must be shared or worktree"));
1909 }
1910
1911 #[tokio::test]
1912 async fn vm_rejected_task_options_notify_the_driver() {
1913 // A task() whose options fail VM validation throws before spawn_task, and
1914 // inside parallel() that throw collapses to a null slot. The driver must
1915 // still receive a TaskRejected event so the run record can refuse to call
1916 // the run a plain success (morning-report issue #2).
1917 let driver = Arc::new(FakeDriver::new());
1918 let value = run(
1919 &driver,
1920 r#"
1921 return await parallel([
1922 () => task({ prompt: "bad slot", label: "L-bad", phase: "P1", cwd: "/absolute/path" }),
1923 ]);
1924 "#,
1925 json!(null),
1926 )
1927 .await
1928 .unwrap();
1929 assert_eq!(value, json!([null]));
1930 assert!(
1931 driver.requests().is_empty(),
1932 "no dispatch reached the driver"
1933 );
1934 let rejected: Vec<_> = driver
1935 .events()
1936 .into_iter()
1937 .filter_map(|event| match event {
1938 ProgressEvent::TaskRejected {
1939 label,
1940 phase,
1941 message,
1942 } => Some((label, phase, message)),
1943 _ => None,
1944 })
1945 .collect();
1946 assert_eq!(rejected.len(), 1, "one rejection event per refused slot");
1947 let (label, phase, message) = &rejected[0];
1948 assert_eq!(label.as_deref(), Some("L-bad"));
1949 assert_eq!(phase.as_deref(), Some("P1"));
1950 assert!(message.contains("bounded repo-relative paths"), "{message}");
1951 }
1952
1953 // ---------------------------------------------------------------------------
1954 // R9: typed slot errors, inspectable settled failures, explicit modes.
1955 // ---------------------------------------------------------------------------
1956
1957 /// Every way a `task()` can die gets its own kind, assigned by the host where
1958 /// the failure happened. Before R9 all six collapsed into two buckets
1959 /// ("budget"/"cancelled" if the message happened to say so, "task" otherwise),
1960 /// so a dead subagent and a typo'd script throw were the same thing.
1961 #[tokio::test]
1962 async fn every_task_failure_mode_carries_its_own_kind() {
1963 let driver = Arc::new(FakeDriver::new());
1964 driver.on("agent case", FakeReply::Fail("boom".to_string()));
1965 driver.on(
1966 "budget case",
1967 FakeReply::BudgetExhausted("limit 10".to_string()),
1968 );
1969 driver.on("cancelled case", FakeReply::Cancelled);
1970 driver.on(
1971 "admission case",
1972 FakeReply::Reject("admission cap".to_string()),
1973 );
1974 driver.on(
1975 "driver case",
1976 FakeReply::Unavailable("driver gone".to_string()),
1977 );
1978 driver.on("dropped case", FakeReply::DropCompletion);
1979 driver.on(
1980 "schema case",
1981 FakeReply::Complete("not json at all".to_string()),
1982 );
1983
1984 let value = run(
1985 &driver,
1986 r#"
1987 const kinds = {};
1988 const probe = async (name, opts) => {
1989 try {
1990 await task(opts);
1991 kinds[name] = "none";
1992 } catch (err) {
1993 kinds[name] = err && err.kind;
1994 }
1995 };
1996 await probe("agent", { description: "agent case" });
1997 await probe("budget", { description: "budget case" });
1998 await probe("cancelled", { description: "cancelled case" });
1999 await probe("admission", { description: "admission case" });
2000 await probe("driver", { description: "driver case" });
2001 await probe("dropped", { description: "dropped case" });
2002 await probe("schema", {
2003 description: "schema case",
2004 schemaRepairAttempts: 0,
2005 responseSchema: { type: "object" },
2006 });
2007 // A malformed options object never reaches a child either.
2008 await probe("bad-options", { description: "x", nosuchoption: 1 });
2009 try {
2010 await task("not an object");
2011 kinds["not-an-object"] = "none";
2012 } catch (err) {
2013 kinds["not-an-object"] = String(err && err.kind);
2014 }
2015 return kinds;
2016 "#,
2017 json!(null),
2018 )
2019 .await
2020 .unwrap();
2021
2022 assert_eq!(
2023 value,
2024 json!({
2025 "agent": "agent",
2026 "budget": "budget",
2027 "cancelled": "cancelled",
2028 "admission": "admission",
2029 "driver": "driver",
2030 "dropped": "driver",
2031 "schema": "schema",
2032 "bad-options": "admission",
2033 // A TypeError raised by the prelude's own argument check never
2034 // came from the host, so it is a script error, not a task kind.
2035 "not-an-object": "undefined",
2036 })
2037 );
2038 }
2039
2040 /// The classifier reads `Error.kind`, never the message text. A child is free
2041 /// to say "budget exhausted" or "responseSchema" in its own failure prose;
2042 /// under the old substring classifier that forged a fatal kind and aborted an
2043 /// otherwise healthy fan-out.
2044 #[tokio::test]
2045 async fn slot_kinds_cannot_be_forged_from_child_failure_text() {
2046 let driver = Arc::new(FakeDriver::new());
2047 driver.on(
2048 "liar",
2049 FakeReply::Fail(
2050 "the reviewer said the run cancelled because budget exhausted and responseSchema \
2051 validation failed"
2052 .to_string(),
2053 ),
2054 );
2055
2056 let value = run(
2057 &driver,
2058 r#"
2059 const results = await parallel([
2060 () => task({ description: "liar" }),
2061 () => task({ description: "honest" }),
2062 ]);
2063 return {
2064 slots: results,
2065 kinds: results.errors.map((entry) => entry.kind),
2066 };
2067 "#,
2068 json!(null),
2069 )
2070 .await
2071 .expect("a child's prose must not cancel the run");
2072
2073 assert_eq!(
2074 value,
2075 json!({
2076 "slots": [null, "done:honest"],
2077 "kinds": ["agent"],
2078 })
2079 );
2080 }
2081
2082 /// The settled default is unchanged on the wire — same slots, same length,
2083 /// same JSON — but the run can now ask why a slot is null instead of guessing.
2084 #[tokio::test]
2085 async fn settled_parallel_keeps_null_slots_and_attaches_an_inspectable_ledger() {
2086 let driver = Arc::new(FakeDriver::new());
2087 driver.on("beta", FakeReply::Fail("boom".to_string()));
2088 driver.on(
2089 "delta",
2090 FakeReply::BudgetExhausted("pool drained".to_string()),
2091 );
2092
2093 let value = run(
2094 &driver,
2095 r#"
2096 const results = await parallel([
2097 () => task({ description: "alpha" }),
2098 () => task({ description: "beta" }),
2099 () => task({ description: "gamma" }),
2100 () => task({ description: "delta" }),
2101 ]);
2102 return {
2103 slots: results,
2104 length: results.length,
2105 // Non-enumerable: the array still serializes as a plain array.
2106 encoded: JSON.stringify(results),
2107 errors: results.errors.map((entry) => ({
2108 index: entry.index,
2109 kind: entry.kind,
2110 says: entry.message.indexOf("boom") !== -1
2111 || entry.message.indexOf("pool drained") !== -1,
2112 })),
2113 };
2114 "#,
2115 json!(null),
2116 )
2117 .await
2118 .unwrap();
2119
2120 assert_eq!(
2121 value,
2122 json!({
2123 "slots": ["done:alpha", null, "done:gamma", null],
2124 "length": 4,
2125 "encoded": "[\"done:alpha\",null,\"done:gamma\",null]",
2126 "errors": [
2127 {"index": 1, "kind": "agent", "says": true},
2128 {"index": 3, "kind": "budget", "says": true},
2129 ],
2130 })
2131 );
2132 }
2133
2134 /// A clean fan-out still gets the ledger, empty and frozen — a script can read
2135 /// `results.errors.length` unconditionally.
2136 #[tokio::test]
2137 async fn a_clean_fan_out_still_reports_an_empty_frozen_error_ledger() {
2138 let value = run(
2139 &Arc::new(FakeDriver::new()),
2140 r#"
2141 const results = await parallel([() => task({ description: "alpha" })]);
2142 let mutated = false;
2143 try {
2144 results.errors = ["forged"];
2145 mutated = true;
2146 } catch (_) {
2147 mutated = false;
2148 }
2149 return {
2150 count: results.errors.length,
2151 frozen: Object.isFrozen(results.errors),
2152 mutated: mutated,
2153 stillEmpty: results.errors.length,
2154 };
2155 "#,
2156 json!(null),
2157 )
2158 .await
2159 .unwrap();
2160 assert_eq!(
2161 value,
2162 json!({"count": 0, "frozen": true, "mutated": false, "stillEmpty": 0})
2163 );
2164 }
2165
2166 /// `settled` is the spelling of today's default; naming it explicitly changes
2167 /// nothing.
2168 #[tokio::test]
2169 async fn explicit_settled_mode_matches_the_default() {
2170 let driver = Arc::new(FakeDriver::new());
2171 driver.on("beta", FakeReply::Fail("boom".to_string()));
2172 let value = run(
2173 &driver,
2174 r#"
2175 const thunks = () => [
2176 () => task({ description: "alpha" }),
2177 () => task({ description: "beta" }),
2178 ];
2179 const implicit = await parallel(thunks());
2180 const explicit = await parallel(thunks(), { mode: "settled" });
2181 return {
2182 implicit: implicit,
2183 explicit: explicit,
2184 sameKinds: JSON.stringify(implicit.errors.map((e) => e.kind))
2185 === JSON.stringify(explicit.errors.map((e) => e.kind)),
2186 };
2187 "#,
2188 json!(null),
2189 )
2190 .await
2191 .unwrap();
2192 assert_eq!(
2193 value,
2194 json!({
2195 "implicit": ["done:alpha", null],
2196 "explicit": ["done:alpha", null],
2197 "sameKinds": true,
2198 })
2199 );
2200 }
2201
2202 /// A typo'd mode used to read as `settled`: the author believed slots were
2203 /// now fatal while they kept silently dropping. It throws instead.
2204 #[tokio::test]
2205 async fn an_unknown_mode_is_refused_rather_than_silently_settled() {
2206 let driver = Arc::new(FakeDriver::new());
2207 let value = run(
2208 &driver,
2209 r#"
2210 const errs = [];
2211 for (const mode of ["failfast", "all-settled", 7]) {
2212 try {
2213 await parallel([() => task({ description: "alpha" })], { mode });
2214 errs.push("no-error");
2215 } catch (err) {
2216 errs.push(err.message);
2217 }
2218 }
2219 try {
2220 await pipeline([1], { stages: [(v) => v], mode: "failfast" });
2221 errs.push("no-error");
2222 } catch (err) {
2223 errs.push(err.message);
2224 }
2225 return errs;
2226 "#,
2227 json!(null),
2228 )
2229 .await
2230 .unwrap();
2231 let messages = value.as_array().unwrap();
2232 assert_eq!(messages.len(), 4, "{value}");
2233 for message in messages {
2234 let text = message.as_str().unwrap();
2235 assert!(
2236 text.contains("unknown mode") && text.contains("settled, fail-fast, partial"),
2237 "{text}"
2238 );
2239 }
2240 assert_eq!(
2241 driver.spawn_count(),
2242 0,
2243 "a refused mode must not spawn anything"
2244 );
2245 }
2246
2247 /// Partial mode is the "inspect every outcome" contract: no failure is erased,
2248 /// and none of them can be mistaken for a value.
2249 #[tokio::test]
2250 async fn partial_mode_types_every_non_cancellation_failure() {
2251 let driver = Arc::new(FakeDriver::new());
2252 driver.on("dead", FakeReply::Fail("boom".to_string()));
2253 driver.on("broke", FakeReply::BudgetExhausted("drained".to_string()));
2254 driver.on("refused", FakeReply::Reject("admission cap".to_string()));
2255
2256 let value = run(
2257 &driver,
2258 r#"
2259 const results = await parallel([
2260 () => task({ description: "alive" }),
2261 () => task({ description: "dead" }),
2262 () => task({ description: "broke" }),
2263 () => task({ description: "refused" }),
2264 ], { mode: "partial" });
2265 return {
2266 shapes: results.map((slot) =>
2267 slot && typeof slot === "object" && slot.__taskError
2268 ? slot.__taskError.kind + "@" + slot.__taskError.index
2269 : String(slot)
2270 ),
2271 ledger: results.errors.map((entry) => entry.kind),
2272 noNulls: results.every((slot) => slot !== null),
2273 };
2274 "#,
2275 json!(null),
2276 )
2277 .await
2278 .expect("partial mode completes the fan-out");
2279
2280 assert_eq!(
2281 value,
2282 json!({
2283 "shapes": ["done:alive", "agent@1", "budget@2", "admission@3"],
2284 "ledger": ["agent", "budget", "admission"],
2285 "noNulls": true,
2286 })
2287 );
2288 }
2289
2290 /// `pipeline` speaks the same three modes and keeps the same ledger.
2291 #[tokio::test]
2292 async fn pipeline_supports_settled_fail_fast_and_partial_with_a_ledger() {
2293 let driver = Arc::new(FakeDriver::new());
2294 driver.on("bad-1", FakeReply::Fail("boom".to_string()));
2295
2296 let value = run(
2297 &driver,
2298 r#"
2299 const stage = (item) => task({ description: item });
2300 const settled = await pipeline(["ok-0", "bad-1", "ok-2"], stage);
2301 const partial = await pipeline(["ok-0", "bad-1"], {
2302 stages: [stage],
2303 mode: "partial",
2304 });
2305 let failFast = "no-error";
2306 try {
2307 await pipeline(["ok-0", "bad-1"], { stages: [stage], mode: "fail-fast" });
2308 } catch (err) {
2309 failFast = err.kind + ":" + (err.message.indexOf("boom") !== -1);
2310 }
2311 return {
2312 settled: settled,
2313 settledLedger: settled.errors.map((e) => e.index + ":" + e.kind),
2314 partial: partial.map((slot) =>
2315 slot && typeof slot === "object" && slot.__taskError
2316 ? slot.__taskError.kind
2317 : slot
2318 ),
2319 failFast: failFast,
2320 };
2321 "#,
2322 json!(null),
2323 )
2324 .await
2325 .unwrap();
2326
2327 assert_eq!(
2328 value,
2329 json!({
2330 "settled": ["done:ok-0", null, "done:ok-2"],
2331 "settledLedger": ["1:agent"],
2332 "partial": ["done:ok-0", "agent"],
2333 "failFast": "agent:true",
2334 })
2335 );
2336 }
2337
2338 /// A fan-out where nothing survived is a dead fan-out. The default still
2339 /// resolves (existing scripts keep working) but the run log says so in a line
2340 /// the host status classifier and an operator can both find.
2341 #[tokio::test]
2342 async fn a_fan_out_where_every_slot_failed_says_so_in_the_run_log() {
2343 let driver = Arc::new(FakeDriver::new());
2344 driver.on("doomed", FakeReply::Fail("boom".to_string()));
2345 let value = run(
2346 &driver,
2347 r#"
2348 const results = await parallel([
2349 () => task({ description: "doomed a" }),
2350 () => task({ description: "doomed b" }),
2351 ]);
2352 return { slots: results, failed: results.errors.length };
2353 "#,
2354 json!(null),
2355 )
2356 .await
2357 .unwrap();
2358 assert_eq!(value, json!({"slots": [null, null], "failed": 2}));
2359 assert!(
2360 driver.events().iter().any(|event| matches!(
2361 event,
2362 ProgressEvent::Log { message }
2363 if message.contains("every slot failed (2 of 2)")
2364 && message.contains("no work survived")
2365 )),
2366 "a fully-failed fan-out must be named in the run log: {:?}",
2367 driver.events()
2368 );
2369 }
2370
2371 /// Cancellation stays fatal in every mode — it is the run's deadline, not a
2372 /// per-slot outcome — and partial mode does not get to keep it as a value.
2373 #[tokio::test]
2374 async fn cancellation_is_fatal_in_partial_pipeline_mode() {
2375 let driver = Arc::new(FakeDriver::new());
2376 driver.on("hang", FakeReply::Never);
2377 let cancel = WorkflowRunCancel::new();
2378 let run_cancel = cancel.clone();
2379 let run_driver = driver.clone();
2380 let handle = tokio::spawn(async move {
2381 WorkflowVm::new()
2382 .run_script_with_cancel(
2383 r#"
2384 await pipeline(["hang"], {
2385 stages: [(item) => task({ description: item })],
2386 mode: "partial",
2387 });
2388 "#,
2389 json!(null),
2390 run_driver as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
2391 run_cancel,
2392 )
2393 .await
2394 });
2395
2396 tokio::time::timeout(Duration::from_secs(2), async {
2397 while driver.spawn_count() == 0 {
2398 tokio::task::yield_now().await;
2399 }
2400 })
2401 .await
2402 .expect("task should start");
2403 cancel.cancel();
2404
2405 let result = handle.await.expect("VM task should join");
2406 assert!(
2407 matches!(result, Err(WorkflowJsError::Cancelled)),
2408 "pipeline partial mode must not downgrade cancellation into a slot value: {result:?}"
2409 );
2410 }
2411
2412 /// The dropped-slot breadcrumb now names the kind, so the run log alone
2413 /// distinguishes "the agent failed" from "we never got to spawn it".
2414 #[tokio::test]
2415 async fn the_dropped_slot_breadcrumb_names_the_kind_and_the_slot() {
2416 let driver = Arc::new(FakeDriver::new());
2417 driver.on("beta", FakeReply::Fail("boom".to_string()));
2418 run(
2419 &driver,
2420 r#"
2421 return await parallel([
2422 () => task({ description: "alpha" }),
2423 () => task({ description: "beta" }),
2424 ]);
2425 "#,
2426 json!(null),
2427 )
2428 .await
2429 .unwrap();
2430 assert!(
2431 driver.events().iter().any(|event| matches!(
2432 event,
2433 ProgressEvent::Log { message }
2434 if message.contains("dropped a failed slot as null")
2435 && message.contains("kind=agent")
2436 && message.contains("slot 1")
2437 )),
2438 "the breadcrumb must name the kind and the slot: {:?}",
2439 driver.events()
2440 );
2441 }
2442
2443 struct EchoInvoker;
2444
2445 #[async_trait::async_trait]
2446 impl codewhale_workflow_js::ToolInvoker for EchoInvoker {
2447 async fn invoke(
2448 &self,
2449 request: codewhale_workflow_js::ToolCallRequest,
2450 ) -> Result<codewhale_workflow_js::ToolCallResponse, codewhale_workflow_js::DriverError> {
2451 use codewhale_workflow_js::{DriverError, ToolCallResponse};
2452 if request.tool == "boom" {
2453 return Ok(ToolCallResponse {
2454 ok: false,
2455 result: json!("kaput"),
2456 });
2457 }
2458 if request.tool == "deny" {
2459 return Err(DriverError::Rejected("nope".to_string()));
2460 }
2461 Ok(ToolCallResponse {
2462 ok: true,
2463 result: json!({ "echo": request.input }),
2464 })
2465 }
2466 }
2467
2468 async fn run_tools(source: &str) -> Result<serde_json::Value, WorkflowJsError> {
2469 let driver = Arc::new(FakeDriver::new());
2470 WorkflowVm::new()
2471 .run_tools_script(
2472 source,
2473 json!(null),
2474 driver.clone() as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
2475 Arc::new(EchoInvoker) as Arc<dyn codewhale_workflow_js::ToolInvoker>,
2476 WorkflowRunCancel::new(),
2477 )
2478 .await
2479 }
2480
2481 #[tokio::test]
2482 async fn tools_surface_is_absent_without_invoker() {
2483 let driver = Arc::new(FakeDriver::new());
2484 let value = run(&driver, "return typeof tools;", json!(null))
2485 .await
2486 .unwrap();
2487 assert_eq!(value, json!("undefined"));
2488 }
2489
2490 #[tokio::test]
2491 async fn tools_call_round_trips() {
2492 let value =
2493 run_tools(r#"const r = await tools.call("read", { path: "x" }); return r.echo.path;"#)
2494 .await
2495 .unwrap();
2496 assert_eq!(value, json!("x"));
2497 }
2498
2499 #[tokio::test]
2500 async fn native_callbacks_stay_on_the_originating_host_runtime() {
2501 use codewhale_workflow_js::{
2502 DriverError, SpawnedTask, TaskRequest, ToolCallRequest, ToolCallResponse, ToolInvoker,
2503 WorkflowDriver,
2504 };
2505 use std::sync::atomic::{AtomicUsize, Ordering};
2506
2507 struct OriginCallbacks {
2508 origin: std::thread::ThreadId,
2509 calls: AtomicUsize,
2510 driver: FakeDriver,
2511 }
2512
2513 #[async_trait::async_trait]
2514 impl WorkflowDriver for OriginCallbacks {
2515 async fn spawn_task(&self, request: TaskRequest) -> Result<SpawnedTask, DriverError> {
2516 assert_eq!(std::thread::current().id(), self.origin);
2517 self.calls.fetch_add(1, Ordering::SeqCst);
2518 self.driver.spawn_task(request).await
2519 }
2520
2521 fn cancel_all(&self) {
2522 self.driver.cancel_all();
2523 }
2524
2525 fn progress(&self, event: ProgressEvent) {
2526 self.driver.progress(event);
2527 }
2528 }
2529
2530 #[async_trait::async_trait]
2531 impl ToolInvoker for OriginCallbacks {
2532 async fn invoke(&self, request: ToolCallRequest) -> Result<ToolCallResponse, DriverError> {
2533 assert_eq!(std::thread::current().id(), self.origin);
2534 self.calls.fetch_add(1, Ordering::SeqCst);
2535 EchoInvoker.invoke(request).await
2536 }
2537 }
2538
2539 let callbacks = Arc::new(OriginCallbacks {
2540 origin: std::thread::current().id(),
2541 calls: AtomicUsize::new(0),
2542 driver: FakeDriver::new(),
2543 });
2544 let value = WorkflowVm::new()
2545 .run_tools_script(
2546 r#"const child = await task({ description: "origin-thread" });
2547 const tool = await tools.call("read", { path: "original" });
2548 return { child, path: tool.echo.path };"#,
2549 json!(null),
2550 callbacks.clone(),
2551 callbacks.clone(),
2552 WorkflowRunCancel::new(),
2553 )
2554 .await
2555 .unwrap();
2556 assert_eq!(
2557 value,
2558 json!({"child": "done:origin-thread", "path": "original"})
2559 );
2560 assert_eq!(callbacks.calls.load(Ordering::SeqCst), 2);
2561 assert_eq!(callbacks.driver.spawn_count(), 1);
2562 }
2563
2564 #[tokio::test]
2565 async fn tools_call_refusal_throws_admission_kind() {
2566 let value = run_tools(
2567 r#"try { await tools.call("deny", {}); return "no-throw"; } catch (e) { return e.kind; }"#,
2568 )
2569 .await
2570 .unwrap();
2571 assert_eq!(value, json!("admission"));
2572 }
2573
2574 #[tokio::test]
2575 async fn tools_call_failure_throws_agent_kind() {
2576 let value = run_tools(
2577 r#"try { await tools.call("boom", {}); return "no-throw"; } catch (e) { return e.kind; }"#,
2578 )
2579 .await
2580 .unwrap();
2581 assert_eq!(value, json!("agent"));
2582 }
2583
2584 #[tokio::test]
2585 async fn tools_calls_continue_past_fifty_while_the_host_admits_them() {
2586 let result = run_tools(
2587 r#"let completed = 0; for (let i = 0; i < 55; i++) { await tools.call("read", {}); completed++; } return completed;"#,
2588 )
2589 .await
2590 .expect("admitted calls continue until the script completes");
2591 assert_eq!(result, json!(55));
2592 }
2593
2594 #[tokio::test]
2595 async fn console_methods_route_to_driver_log_sink() {
2596 let driver = Arc::new(FakeDriver::new());
2597 let value = WorkflowVm::new()
2598 .run_tools_script(
2599 r#"
2600 const cyclic = {};
2601 cyclic.self = cyclic;
2602 const nullProto = Object.create(null);
2603 nullProto.self = nullProto;
2604 console.log("hello", 42, { ok: true });
2605 console.info("starting", new URL("https://example.com/a?b=1"));
2606 console.warn("careful");
2607 console.error(new Error("boom"));
2608 console.debug("trace", cyclic, nullProto);
2609 console.warn();
2610 return Object.isFrozen(console);
2611 "#,
2612 json!(null),
2613 driver.clone() as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
2614 Arc::new(EchoInvoker) as Arc<dyn codewhale_workflow_js::ToolInvoker>,
2615 WorkflowRunCancel::new(),
2616 )
2617 .await
2618 .unwrap();
2619 assert_eq!(value, json!(true));
2620 assert_eq!(
2621 driver.events(),
2622 vec![
2623 ProgressEvent::Log {
2624 message: r#"hello 42 {"ok":true}"#.to_string(),
2625 },
2626 ProgressEvent::Log {
2627 message: "[info] starting https://example.com/a?b=1".to_string(),
2628 },
2629 ProgressEvent::Log {
2630 message: "[warn] careful".to_string(),
2631 },
2632 ProgressEvent::Log {
2633 message: "[error] Error: boom".to_string(),
2634 },
2635 ProgressEvent::Log {
2636 message: "[debug] trace [object Object] [object Object]".to_string(),
2637 },
2638 ProgressEvent::Log {
2639 message: "[warn]".to_string(),
2640 },
2641 ]
2642 );
2643 }
2644
2645 #[tokio::test]
2646 async fn url_host_setter_keeps_an_existing_port_unless_one_is_given() {
2647 let value = run_tools(
2648 r#"
2649 const u = new URL("https://a.example:8443/p");
2650 u.host = "new.example";
2651 const kept = u.href;
2652 u.host = "other.example:9000";
2653 return { kept, replaced: u.href };
2654 "#,
2655 )
2656 .await
2657 .unwrap();
2658 assert_eq!(
2659 value,
2660 json!({
2661 "kept": "https://new.example:8443/p",
2662 "replaced": "https://other.example:9000/p",
2663 })
2664 );
2665 }
2666
2667 #[tokio::test]
2668 async fn url_and_url_search_params_parse_resolve_and_sync() {
2669 let value = run_tools(
2670 r#"
2671 const u = new URL("HTTPS://EXAMPLE.COM:443/a/b/../c?b=1&tag=rust+lang&tag=%E2%9C%93#top");
2672 const parsed = {
2673 protocol: u.protocol,
2674 hostname: u.hostname,
2675 host: u.host,
2676 port: u.port,
2677 pathname: u.pathname,
2678 search: u.search,
2679 hash: u.hash,
2680 origin: u.origin,
2681 href: u.href,
2682 str: u.toString(),
2683 json: JSON.stringify(u),
2684 b: u.searchParams.get("b"),
2685 tags: u.searchParams.getAll("tag"),
2686 hasB: u.searchParams.has("b"),
2687 hasMissing: u.searchParams.has("missing"),
2688 sameParamsRef: u.searchParams === u.searchParams,
2689 };
2690
2691 u.searchParams.set("b", "2");
2692 u.searchParams.append("extra", "a b");
2693 u.searchParams.delete("tag", "rust lang");
2694 const afterParamsMutation = {
2695 search: u.search,
2696 href: u.href,
2697 entries: Array.from(u.searchParams.entries()),
2698 keys: Array.from(u.searchParams.keys()),
2699 values: Array.from(u.searchParams.values()),
2700 fromEntries: Object.fromEntries(u.searchParams),
2701 };
2702
2703 const spRef = u.searchParams;
2704 u.search = "?x=10&x=20";
2705 const afterSearchSetter = {
2706 sameRef: u.searchParams === spRef,
2707 xAll: spRef.getAll("x"),
2708 size: spRef.size,
2709 };
2710
2711 const rel = new URL("../v2/items?p=1", "https://api.example.com:8443/v1/old/list");
2712 const ipv6 = new URL("http://[2001:DB8::1]:8080/status");
2713 const customPort = new URL("http://example.com:80/default-port");
2714
2715 const standalone = new URLSearchParams({ z: "last", a: "first" });
2716 standalone.append("a", "second");
2717 standalone.sort();
2718 const standaloneOut = {
2719 str: standalone.toString(),
2720 getA: standalone.get("a"),
2721 allA: standalone.getAll("a"),
2722 hasA2: standalone.has("a", "second"),
2723 };
2724
2725 let badThrew = false;
2726 try {
2727 new URL("not a valid url");
2728 } catch (err) {
2729 badThrew = err instanceof TypeError;
2730 }
2731 let badPortThrew = false;
2732 try {
2733 new URL("https://example.com:99999/");
2734 } catch (err) {
2735 badPortThrew = err instanceof TypeError;
2736 }
2737
2738 return {
2739 parsed,
2740 afterParamsMutation,
2741 afterSearchSetter,
2742 relHref: rel.href,
2743 relOrigin: rel.origin,
2744 ipv6Host: ipv6.host,
2745 ipv6Hostname: ipv6.hostname,
2746 ipv6Port: ipv6.port,
2747 customPortHref: customPort.href,
2748 standaloneOut,
2749 canParseGood: URL.canParse("https://example.com/ok"),
2750 canParseBad: URL.canParse("relative/no-base"),
2751 parseNull: URL.parse(":::"),
2752 badThrew,
2753 badPortThrew,
2754 };
2755 "#,
2756 )
2757 .await
2758 .unwrap();
2759
2760 assert_eq!(
2761 value["parsed"],
2762 json!({
2763 "protocol": "https:",
2764 "hostname": "example.com",
2765 "host": "example.com",
2766 "port": "",
2767 "pathname": "/a/c",
2768 "search": "?b=1&tag=rust+lang&tag=%E2%9C%93",
2769 "hash": "#top",
2770 "origin": "https://example.com",
2771 "href": "https://example.com/a/c?b=1&tag=rust+lang&tag=%E2%9C%93#top",
2772 "str": "https://example.com/a/c?b=1&tag=rust+lang&tag=%E2%9C%93#top",
2773 "json": "\"https://example.com/a/c?b=1&tag=rust+lang&tag=%E2%9C%93#top\"",
2774 "b": "1",
2775 "tags": ["rust lang", "✓"],
2776 "hasB": true,
2777 "hasMissing": false,
2778 "sameParamsRef": true,
2779 })
2780 );
2781 assert_eq!(
2782 value["afterParamsMutation"],
2783 json!({
2784 "search": "?b=2&tag=%E2%9C%93&extra=a+b",
2785 "href": "https://example.com/a/c?b=2&tag=%E2%9C%93&extra=a+b#top",
2786 "entries": [["b", "2"], ["tag", "✓"], ["extra", "a b"]],
2787 "keys": ["b", "tag", "extra"],
2788 "values": ["2", "✓", "a b"],
2789 "fromEntries": {"b": "2", "tag": "✓", "extra": "a b"},
2790 })
2791 );
2792 assert_eq!(
2793 value["afterSearchSetter"],
2794 json!({
2795 "sameRef": true,
2796 "xAll": ["10", "20"],
2797 "size": 2,
2798 })
2799 );
2800 assert_eq!(
2801 value["relHref"],
2802 json!("https://api.example.com:8443/v1/v2/items?p=1")
2803 );
2804 assert_eq!(value["relOrigin"], json!("https://api.example.com:8443"));
2805 assert_eq!(value["ipv6Host"], json!("[2001:db8::1]:8080"));
2806 assert_eq!(value["ipv6Hostname"], json!("[2001:db8::1]"));
2807 assert_eq!(value["ipv6Port"], json!("8080"));
2808 assert_eq!(
2809 value["customPortHref"],
2810 json!("http://example.com/default-port")
2811 );
2812 assert_eq!(
2813 value["standaloneOut"],
2814 json!({
2815 "str": "a=first&a=second&z=last",
2816 "getA": "first",
2817 "allA": ["first", "second"],
2818 "hasA2": true,
2819 })
2820 );
2821 assert_eq!(value["canParseGood"], json!(true));
2822 assert_eq!(value["canParseBad"], json!(false));
2823 assert_eq!(value["parseNull"], json!(null));
2824 assert_eq!(value["badThrew"], json!(true));
2825 assert_eq!(value["badPortThrew"], json!(true));
2826 }
2827
2828 #[tokio::test]
2829 async fn codemode_determinism_errors_name_execute_tools_instead_of_workflow() {
2830 for (expr, expected_name) in [
2831 ("return Date.now();", "Date.now()"),
2832 ("return new Date();", "new Date()/Date()"),
2833 ("return Math.random();", "Math.random()"),
2834 ] {
2835 let codemode_msg = script_message(run_tools(expr).await);
2836 assert!(codemode_msg.contains(expected_name), "{codemode_msg}");
2837 assert!(codemode_msg.contains("execute_tools"), "{codemode_msg}");
2838 assert!(codemode_msg.contains("deterministic"), "{codemode_msg}");
2839 assert!(
2840 !codemode_msg.contains("Workflow") && !codemode_msg.contains("record/replay"),
2841 "{codemode_msg}"
2842 );
2843
2844 let driver = Arc::new(FakeDriver::new());
2845 let workflow_msg = script_message(run(&driver, expr, json!(null)).await);
2846 assert!(workflow_msg.contains(expected_name), "{workflow_msg}");
2847 assert!(workflow_msg.contains("Workflow scripts"), "{workflow_msg}");
2848 }
2849 }
2850
2851 /// A platform-native absolute path for `unix_path` (`/a/b`): unchanged on
2852 /// Unix, `C:\a\b` on Windows, where `/a/b` has no drive and is not absolute.
2853 fn native_abs(unix_path: &str) -> String {
2854 if cfg!(windows) {
2855 format!("C:{}", unix_path.replace('/', "\\"))
2856 } else {
2857 unix_path.to_string()
2858 }
2859 }
2860
2861 /// An absolute `cwd` inside the run's workspace normalizes to the
2862 /// repo-relative form; outside it, through `..`, or with no known workspace
2863 /// it is still refused (the trust boundary is unchanged).
2864 #[test]
2865 fn absolute_cwd_inside_the_workspace_normalizes_and_outside_is_refused() {
2866 use codewhale_workflow_js::{normalize_task_cwd, normalize_task_cwd_in};
2867 use std::path::PathBuf;
2868 let workspace = PathBuf::from(native_abs("/Volumes/WorkSSD/project"));
2869 let workspace = Some(workspace.as_path());
2870 assert_eq!(
2871 normalize_task_cwd_in(&native_abs("/Volumes/WorkSSD/project/codewhale"), workspace)
2872 .unwrap(),
2873 "codewhale"
2874 );
2875 assert_eq!(
2876 normalize_task_cwd_in(
2877 &native_abs("/Volumes/WorkSSD/project/./crates/tui"),
2878 workspace
2879 )
2880 .unwrap(),
2881 "crates/tui"
2882 );
2883 assert_eq!(
2884 normalize_task_cwd_in(&native_abs("/Volumes/WorkSSD/project/"), workspace).unwrap(),
2885 "."
2886 );
2887 assert_eq!(
2888 normalize_task_cwd_in("crates/tui", workspace).unwrap(),
2889 normalize_task_cwd("crates/tui").unwrap()
2890 );
2891 for outside in [
2892 native_abs("/Volumes/WorkSSD/project-other/codewhale"),
2893 native_abs("/Volumes/WorkSSD"),
2894 native_abs("/etc"),
2895 native_abs("/Volumes/WorkSSD/project/../secrets"),
2896 native_abs("/Volumes/WorkSSD/project/codewhale/../../secrets"),
2897 native_abs("/Volumes/WorkSSD/X/../project/codewhale"),
2898 ] {
2899 let error = normalize_task_cwd_in(&outside, workspace).unwrap_err();
2900 assert!(
2901 error.contains("outside the workspace") || error.contains("parent traversal"),
2902 "{outside}: {error}"
2903 );
2904 }
2905 let error =
2906 normalize_task_cwd_in(&native_abs("/Volumes/WorkSSD/project/codewhale"), None).unwrap_err();
2907 assert!(error.contains("bounded repo-relative paths"), "{error}");
2908 }
2909
2910 /// Windows spellings of the same workspace path: a verbatim `\\?\` prefix on
2911 /// either side, forward slashes, and a different case all match; another
2912 /// drive or a sibling directory does not.
2913 #[cfg(windows)]
2914 #[test]
2915 fn absolute_cwd_matches_windows_spellings_of_the_workspace() {
2916 use codewhale_workflow_js::normalize_task_cwd_in;
2917 use std::path::Path;
2918 let plain = Path::new(r"C:\Users\dev\CW");
2919 let verbatim = Path::new(r"\\?\C:\Users\dev\CW");
2920 for workspace in [plain, verbatim] {
2921 for inside in [
2922 r"C:\Users\dev\CW\codewhale",
2923 "C:/Users/dev/CW/codewhale",
2924 r"c:\users\DEV\cw\codewhale",
2925 r"\\?\C:\Users\dev\CW\codewhale",
2926 ] {
2927 assert_eq!(
2928 normalize_task_cwd_in(inside, Some(workspace)).unwrap(),
2929 "codewhale",
2930 "{inside} in {}",
2931 workspace.display()
2932 );
2933 }
2934 for outside in [
2935 r"D:\Users\dev\CW\codewhale",
2936 r"C:\Users\dev\CW-other",
2937 r"C:\Users\dev\CW\..\secrets",
2938 r"\\server\share\Users\dev\CW",
2939 ] {
2940 let error = normalize_task_cwd_in(outside, Some(workspace)).unwrap_err();
2941 assert!(
2942 error.contains("outside the workspace") || error.contains("parent traversal"),
2943 "{outside}: {error}"
2944 );
2945 }
2946 }
2947 // A UNC workspace matches its own share, case-insensitively.
2948 let unc = Path::new(r"\\Server\Share\CW");
2949 assert_eq!(
2950 normalize_task_cwd_in(r"\\server\share\cw\codewhale", Some(unc)).unwrap(),
2951 "codewhale"
2952 );
2953 }
2954
2955 #[derive(Default)]
2956 struct DiscoveryInvoker {
2957 calls: std::sync::Mutex<Vec<String>>,
2958 }
2959
2960 #[async_trait::async_trait]
2961 impl codewhale_workflow_js::ToolInvoker for DiscoveryInvoker {
2962 async fn invoke(
2963 &self,
2964 request: codewhale_workflow_js::ToolCallRequest,
2965 ) -> Result<codewhale_workflow_js::ToolCallResponse, codewhale_workflow_js::DriverError> {
2966 use codewhale_workflow_js::{DriverError, ToolCallResponse};
2967 let mode = request.input["mode"].as_str().unwrap_or_default();
2968 self.calls
2969 .lock()
2970 .unwrap()
2971 .push(format!("{} {mode}", request.tool).trim_end().to_string());
2972 let content = match (request.tool.as_str(), mode) {
2973 ("tool_search", "resolve") if request.input["query"] != "github" => {
2974 return Err(DriverError::Rejected(format!(
2975 "boot query {} is not the bare server name",
2976 request.input["query"]
2977 )));
2978 }
2979 ("tool_search", "resolve") if request.input["op"] == "missing" => {
2980 return Err(DriverError::Rejected("unknown tool".to_string()));
2981 }
2982 ("tool_search", "resolve") => json!({ "name": "mcp_GitHub_list_issues" }),
2983 ("tool_search", "list") => json!({
2984 "total": 2, "truncated": true, "tools": [{ "name": "read" }]
2985 }),
2986 ("tool_search", _) => json!({
2987 "total": 2, "truncated": false, "tools": [{ "name": "read" }]
2988 }),
2989 _ => json!({ "tool": request.tool }),
2990 };
2991 let cut = matches!((request.tool.as_str(), mode), ("tool_search", "describe"));
2992 Ok(ToolCallResponse {
2993 ok: true,
2994 result: json!({
2995 "content": content,
2996 "metadata": null,
2997 "truncated": cut.then(|| json!({ "original_bytes": 2 })),
2998 }),
2999 })
3000 }
3001 }
3002
3003 async fn run_discovery(source: &str) -> (serde_json::Value, Vec<String>, Vec<ProgressEvent>) {
3004 let driver = Arc::new(FakeDriver::new());
3005 let invoker = Arc::new(DiscoveryInvoker::default());
3006 let value = WorkflowVm::new()
3007 .run_tools_script(
3008 source,
3009 json!(null),
3010 driver.clone() as Arc<dyn codewhale_workflow_js::WorkflowDriver>,
3011 invoker.clone() as Arc<dyn codewhale_workflow_js::ToolInvoker>,
3012 WorkflowRunCancel::new(),
3013 )
3014 .await
3015 .unwrap();
3016 let calls = invoker.calls.lock().unwrap().clone();
3017 (value, calls, driver.events())
3018 }
3019
3020 #[tokio::test]
3021 async fn namespace_calls_resolve_once_on_the_host_and_dispatch_one_name() {
3022 let (value, calls, _) = run_discovery(
3023 r#"
3024 const first = await tools.github.listIssues({ state: "open" });
3025 const second = await tools.github.listIssues({});
3026 let error = "";
3027 try { await tools.github.missing({}); } catch (err) { error = `${err.kind}: ${err.message}`; }
3028 return { first: first.content.tool, second: second.content.tool, error };
3029 "#,
3030 )
3031 .await;
3032 assert_eq!(value["first"], "mcp_GitHub_list_issues");
3033 assert_eq!(value["second"], "mcp_GitHub_list_issues");
3034 assert!(
3035 value["error"]
3036 .as_str()
3037 .is_some_and(|error| error.starts_with("admission: tools.github.missing: ")),
3038 "{value}"
3039 );
3040 assert_eq!(
3041 calls,
3042 [
3043 "tool_search resolve",
3044 "mcp_GitHub_list_issues",
3045 "mcp_GitHub_list_issues",
3046 "tool_search resolve",
3047 ]
3048 );
3049 }
3050
3051 #[tokio::test]
3052 async fn cut_discovery_results_carry_the_total_and_log_it() {
3053 let (value, _, events) = run_discovery(
3054 r#"
3055 const listed = await tools.list();
3056 const described = await tools.describe(["read", "write"]);
3057 return [listed, described].map((found) => [found.length, found.total, found.truncated, Object.keys(found).length]);
3058 "#,
3059 )
3060 .await;
3061 assert_eq!(value, json!([[1, 2, true, 1], [1, 2, true, 1]]));
3062 let logs = events
3063 .iter()
3064 .filter_map(|event| match event {
3065 ProgressEvent::Log { message } => Some(message.as_str()),
3066 _ => None,
3067 })
3068 .collect::<Vec<_>>();
3069 assert_eq!(logs.len(), 2, "{logs:?}");
3070 assert!(logs[0].starts_with("tools.list: showing 1 of 2 tools"));
3071 assert!(logs[1].starts_with("tools.describe: showing 1 of 2 tools (cut"));
3072 }
3073
3074 #[tokio::test]
3075 async fn coercing_tools_or_a_namespace_makes_no_call() {
3076 let (value, calls, _) = run_discovery(
3077 r#"
3078 return [
3079 String(tools), `${tools.github}`, typeof tools.github.valueOf(),
3080 tools.hasOwnProperty("call"), tools.github.hasOwnProperty("op"),
3081 typeof tools.github.name, typeof tools.github.length,
3082 tools.github.then === undefined, JSON.stringify(tools),
3083 ];
3084 "#,
3085 )
3086 .await;
3087 assert_eq!(
3088 value,
3089 json!([
3090 "[object Object]",
3091 "[object Function]",
3092 "function",
3093 true,
3094 false,
3095 "function",
3096 "function",
3097 true,
3098 "{}"
3099 ])
3100 );
3101 assert!(calls.is_empty(), "{calls:?}");
3102 }
3103
3103 lines RUST