返回 CodeWhale
js_authoring.rs
根目录 / crates / workflow / src / js_authoring.rs
1 use serde::Deserialize;
2 use thiserror::Error;
3
4 use crate::{
5 BranchSpec, BudgetSpec, GateSpec, LeafSpec, ModelPolicy, PermissionSpec, ReduceSpec,
6 SequenceSpec, WorkflowNode, WorkflowSpec, validate_workflow_nodes,
7 };
8
9 pub type JavascriptWorkflowResult<T> = std::result::Result<T, JavascriptWorkflowError>;
10
11 #[derive(Debug, Error)]
12 pub enum JavascriptWorkflowError {
13 #[error("workflow source contains unsupported construct `{construct}`")]
14 UnsupportedConstruct { construct: &'static str },
15 #[error("workflow source did not call workflow({{...}})")]
16 MissingWorkflowCall,
17 #[error("workflow({{...}}) object could not be extracted: {0}")]
18 InvalidWorkflowObject(String),
19 #[error("invalid workflow JSON object: {0}")]
20 InvalidJson(serde_json::Error),
21 #[error("invalid workflow node: {0}")]
22 InvalidNode(String),
23 }
24
25 pub fn compile_javascript_workflow(
26 identifier: &str,
27 source: &str,
28 ) -> JavascriptWorkflowResult<WorkflowSpec> {
29 compile_js_like_workflow(identifier, source)
30 }
31
32 pub fn compile_typescript_workflow(
33 identifier: &str,
34 source: &str,
35 ) -> JavascriptWorkflowResult<WorkflowSpec> {
36 compile_js_like_workflow(identifier, source)
37 }
38
39 fn compile_js_like_workflow(
40 _identifier: &str,
41 source: &str,
42 ) -> JavascriptWorkflowResult<WorkflowSpec> {
43 reject_unsupported_constructs(source)?;
44 let object = extract_workflow_object(source)?;
45 let authored = serde_json::from_str::<JsWorkflowSpec>(object).map_err(|error| {
46 serde_json::from_str::<serde_json::Value>(object)
47 .ok()
48 .and_then(|value| value.get("nodes").and_then(removed_node_kind))
49 .map_or(JavascriptWorkflowError::InvalidJson(error), |kind| {
50 JavascriptWorkflowError::InvalidNode(format!(
51 "`{kind}` workflow nodes were removed; use agent, branch, sequence or reduce"
52 ))
53 })
54 })?;
55 let mut workflow = authored.into_workflow();
56 normalize_leaf_profiles(&mut workflow.nodes);
57 normalize_gate_roles(&mut workflow.gates);
58 if workflow.goal.trim().is_empty() {
59 return Err(JavascriptWorkflowError::InvalidNode(
60 "workflow goal cannot be empty".to_string(),
61 ));
62 }
63 validate_workflow_nodes(&workflow.nodes)
64 .map_err(|error| JavascriptWorkflowError::InvalidNode(error.to_string()))?;
65 Ok(workflow)
66 }
67
68 const REMOVED_NODE_KINDS: [&str; 4] = ["teacher_review", "loop_until", "cond", "expand"];
69
70 fn removed_node_kind(nodes: &serde_json::Value) -> Option<&'static str> {
71 nodes.as_array()?.iter().find_map(removed_kind_in_node)
72 }
73
74 fn removed_kind_in_node(node: &serde_json::Value) -> Option<&'static str> {
75 let object = node.as_object()?;
76 let kind = object.get("kind").and_then(serde_json::Value::as_str);
77 if let Some(removed) = REMOVED_NODE_KINDS
78 .into_iter()
79 .find(|removed| object.contains_key(*removed) || kind == Some(*removed))
80 {
81 return Some(removed);
82 }
83 ["spec", "branch", "sequence"]
84 .into_iter()
85 .filter_map(|wrapper| object.get(wrapper)?.get("children"))
86 .find_map(removed_node_kind)
87 }
88
89 // Role/profile names are case-insensitive roster keys; the IR stores the
90 // canonical lowercase form. Invalid tokens are left as-is so validation
91 // reports them.
92 fn normalize_leaf_profiles(nodes: &mut [WorkflowNode]) {
93 for node in nodes {
94 match node {
95 WorkflowNode::Leaf(spec) => {
96 if let Some(role) = spec.role.as_mut() {
97 *role = role.trim().to_lowercase();
98 }
99 if let Some(profile) = spec.profile.as_mut() {
100 *profile = profile.trim().to_lowercase();
101 }
102 }
103 WorkflowNode::BranchSet(spec) => normalize_leaf_profiles(&mut spec.children),
104 WorkflowNode::Sequence(spec) => normalize_leaf_profiles(&mut spec.children),
105 WorkflowNode::Reduce(_) => {}
106 }
107 }
108 }
109
110 fn normalize_gate_roles(gates: &mut [GateSpec]) {
111 for gate in gates {
112 gate.role = gate.role.trim().to_lowercase();
113 if let Some(blocks_role) = gate.blocks_role.as_mut() {
114 *blocks_role = blocks_role.trim().to_lowercase();
115 }
116 }
117 }
118
119 fn reject_unsupported_constructs(source: &str) -> JavascriptWorkflowResult<()> {
120 let source = &blank_quoted_strings(source);
121 for (needle, construct) in [
122 ("import ", "import"),
123 ("import(", "dynamic import"),
124 ("require(", "require"),
125 ("fetch(", "fetch"),
126 ("XMLHttpRequest", "XMLHttpRequest"),
127 ("WebSocket", "WebSocket"),
128 ("process.", "process"),
129 ("Deno.", "Deno"),
130 ("Bun.", "Bun"),
131 ("child_process", "child_process"),
132 ("exec(", "exec"),
133 ("spawn(", "spawn"),
134 ("open(", "open"),
135 ("readFile", "readFile"),
136 ("writeFile", "writeFile"),
137 ("async ", "async"),
138 ("await ", "await"),
139 ("eval(", "eval"),
140 ("new Function", "Function"),
141 ] {
142 if source.contains(needle) {
143 return Err(JavascriptWorkflowError::UnsupportedConstruct { construct });
144 }
145 }
146 Ok(())
147 }
148
149 fn blank_quoted_strings(source: &str) -> String {
150 let mut out = String::with_capacity(source.len());
151 let mut chars = source.chars().peekable();
152 while let Some(ch) = chars.next() {
153 out.push(ch);
154 match ch {
155 '/' if chars.peek() == Some(&'/') => {
156 for next in chars.by_ref() {
157 out.push(next);
158 if next == '\n' {
159 break;
160 }
161 }
162 }
163 '/' if chars.peek() == Some(&'*') => {
164 out.extend(chars.next());
165 let mut previous = ' ';
166 for next in chars.by_ref() {
167 out.push(next);
168 if previous == '*' && next == '/' {
169 break;
170 }
171 previous = next;
172 }
173 }
174 '"' | '\'' | '`' => {
175 let mut escaped = false;
176 for next in chars.by_ref() {
177 if escaped {
178 escaped = false;
179 } else if next == '\\' {
180 escaped = true;
181 } else if next == ch {
182 out.push(next);
183 break;
184 }
185 out.push(if ch == '`' { next } else { ' ' });
186 }
187 }
188 _ => {}
189 }
190 }
191 out
192 }
193
194 fn is_identifier_byte(byte: u8) -> bool {
195 byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' || !byte.is_ascii()
196 }
197
198 fn skip_source_trivia(source: &str, mut index: usize) -> usize {
199 let bytes = source.as_bytes();
200 loop {
201 while index < bytes.len() && bytes[index].is_ascii_whitespace() {
202 index += 1;
203 }
204 if bytes.get(index) == Some(&b'/') && bytes.get(index + 1) == Some(&b'/') {
205 index += 2;
206 while index < bytes.len() && bytes[index] != b'\n' {
207 index += 1;
208 }
209 } else if bytes.get(index) == Some(&b'/') && bytes.get(index + 1) == Some(&b'*') {
210 index += 2;
211 while index + 1 < bytes.len() && !(bytes[index] == b'*' && bytes[index + 1] == b'/') {
212 index += 1;
213 }
214 index = index.saturating_add(2).min(bytes.len());
215 } else {
216 return index;
217 }
218 }
219 }
220
221 fn workflow_call_parenthesis(source: &str) -> Option<usize> {
222 let bytes = source.as_bytes();
223 let mut index = 0;
224 while index < bytes.len() {
225 match bytes[index] {
226 b'/' if bytes.get(index + 1) == Some(&b'/') => {
227 index += 2;
228 while index < bytes.len() && bytes[index] != b'\n' {
229 index += 1;
230 }
231 }
232 b'/' if bytes.get(index + 1) == Some(&b'*') => {
233 index = skip_source_trivia(source, index);
234 }
235 b'"' | b'\'' | b'`' => {
236 let quote = bytes[index];
237 index += 1;
238 while index < bytes.len() {
239 if bytes[index] == b'\\' {
240 index = index.saturating_add(2);
241 continue;
242 }
243 let byte = bytes[index];
244 index += 1;
245 if byte == quote {
246 break;
247 }
248 }
249 }
250 byte if is_identifier_byte(byte) => {
251 let start = index;
252 index += 1;
253 while index < bytes.len() && is_identifier_byte(bytes[index]) {
254 index += 1;
255 }
256 if &bytes[start..index] == b"workflow" {
257 let paren = skip_source_trivia(source, index);
258 if bytes.get(paren) == Some(&b'(') {
259 return Some(paren);
260 }
261 }
262 }
263 _ => index += 1,
264 }
265 }
266 None
267 }
268
269 fn extract_workflow_object(source: &str) -> JavascriptWorkflowResult<&str> {
270 let open_paren =
271 workflow_call_parenthesis(source).ok_or(JavascriptWorkflowError::MissingWorkflowCall)?;
272 let object_start = source[open_paren + 1..]
273 .char_indices()
274 .find_map(|(idx, ch)| {
275 if ch.is_whitespace() {
276 None
277 } else {
278 Some((open_paren + 1 + idx, ch))
279 }
280 })
281 .ok_or(JavascriptWorkflowError::MissingWorkflowCall)?;
282 if object_start.1 != '{' {
283 return Err(JavascriptWorkflowError::InvalidWorkflowObject(
284 "workflow(...) must receive a JSON-compatible object literal".to_string(),
285 ));
286 }
287
288 let mut depth = 0usize;
289 let mut in_string: Option<char> = None;
290 let mut escape = false;
291 for (idx, ch) in source[object_start.0..].char_indices() {
292 let absolute = object_start.0 + idx;
293 if let Some(quote) = in_string {
294 if escape {
295 escape = false;
296 } else if ch == '\\' {
297 escape = true;
298 } else if ch == quote {
299 in_string = None;
300 }
301 continue;
302 }
303
304 match ch {
305 '"' | '\'' | '`' => in_string = Some(ch),
306 '{' => depth += 1,
307 '}' => {
308 depth = depth.checked_sub(1).ok_or_else(|| {
309 JavascriptWorkflowError::InvalidWorkflowObject(
310 "unbalanced closing brace".to_string(),
311 )
312 })?;
313 if depth == 0 {
314 return Ok(&source[object_start.0..=absolute]);
315 }
316 }
317 _ => {}
318 }
319 }
320
321 Err(JavascriptWorkflowError::InvalidWorkflowObject(
322 "missing closing brace for workflow object".to_string(),
323 ))
324 }
325
326 #[derive(Debug, Deserialize)]
327 #[serde(deny_unknown_fields)]
328 struct JsWorkflowSpec {
329 #[serde(default)]
330 id: Option<String>,
331 goal: String,
332 #[serde(default)]
333 description: Option<String>,
334 #[serde(default)]
335 budget: BudgetSpec,
336 #[serde(default)]
337 permissions: PermissionSpec,
338 #[serde(default)]
339 model_policy: ModelPolicy,
340 #[serde(default)]
341 gates: Vec<GateSpec>,
342 #[serde(default)]
343 nodes: Vec<JsWorkflowNode>,
344 }
345
346 impl JsWorkflowSpec {
347 fn into_workflow(self) -> WorkflowSpec {
348 WorkflowSpec {
349 id: self.id,
350 goal: self.goal,
351 description: self.description,
352 budget: self.budget,
353 permissions: self.permissions,
354 model_policy: self.model_policy,
355 gates: self.gates,
356 nodes: self
357 .nodes
358 .into_iter()
359 .map(JsWorkflowNode::into_node)
360 .collect(),
361 }
362 }
363 }
364
365 #[derive(Debug, Deserialize)]
366 #[serde(untagged)]
367 enum JsWorkflowNode {
368 Raw(WorkflowNode),
369 Agent(JsAgentNode),
370 Branch(JsBranchNode),
371 Sequence(JsSequenceNode),
372 Reduce(JsReduceNode),
373 }
374
375 impl JsWorkflowNode {
376 fn into_node(self) -> WorkflowNode {
377 match self {
378 Self::Raw(node) => node,
379 Self::Agent(node) => WorkflowNode::Leaf(node.agent),
380 Self::Branch(node) => WorkflowNode::BranchSet(node.branch.into_branch()),
381 Self::Sequence(node) => WorkflowNode::Sequence(node.sequence.into_sequence()),
382 Self::Reduce(node) => WorkflowNode::Reduce(node.reduce),
383 }
384 }
385 }
386
387 #[derive(Debug, Deserialize)]
388 #[serde(deny_unknown_fields)]
389 struct JsAgentNode {
390 agent: LeafSpec,
391 }
392
393 #[derive(Debug, Deserialize)]
394 #[serde(deny_unknown_fields)]
395 struct JsBranchNode {
396 branch: JsBranchSpec,
397 }
398
399 #[derive(Debug, Deserialize)]
400 #[serde(deny_unknown_fields)]
401 struct JsBranchSpec {
402 id: String,
403 #[serde(default)]
404 description: Option<String>,
405 #[serde(default = "default_true")]
406 parallel: bool,
407 #[serde(default)]
408 budget: BudgetSpec,
409 #[serde(default)]
410 permissions: PermissionSpec,
411 #[serde(default)]
412 model_policy: ModelPolicy,
413 #[serde(default)]
414 children: Vec<JsWorkflowNode>,
415 }
416
417 impl JsBranchSpec {
418 fn into_branch(self) -> BranchSpec {
419 BranchSpec {
420 id: self.id,
421 description: self.description,
422 parallel: self.parallel,
423 budget: self.budget,
424 permissions: self.permissions,
425 model_policy: self.model_policy,
426 children: self
427 .children
428 .into_iter()
429 .map(JsWorkflowNode::into_node)
430 .collect(),
431 }
432 }
433 }
434
435 #[derive(Debug, Deserialize)]
436 #[serde(deny_unknown_fields)]
437 struct JsSequenceNode {
438 sequence: JsSequenceSpec,
439 }
440
441 #[derive(Debug, Deserialize)]
442 #[serde(deny_unknown_fields)]
443 struct JsSequenceSpec {
444 id: String,
445 #[serde(default)]
446 children: Vec<JsWorkflowNode>,
447 }
448
449 impl JsSequenceSpec {
450 fn into_sequence(self) -> SequenceSpec {
451 SequenceSpec {
452 id: self.id,
453 children: self
454 .children
455 .into_iter()
456 .map(JsWorkflowNode::into_node)
457 .collect(),
458 }
459 }
460 }
461
462 #[derive(Debug, Deserialize)]
463 #[serde(deny_unknown_fields)]
464 struct JsReduceNode {
465 reduce: ReduceSpec,
466 }
467
468 fn default_true() -> bool {
469 true
470 }
471
472 #[cfg(test)]
473 mod tests {
474 use super::*;
475 use crate::{
476 AgentType, GateKind, GateOn, GateOnFail, GateOutcome, GateState, LaneGateBoard, TaskMode,
477 };
478
479 #[test]
480 fn javascript_workflow_compiles_branch_reduce_to_ir() {
481 let source = r#"
482 const decoy = 'workflow({ "goal": "decoy", "nodes": [] })';
483 export default workflow({
484 "id": "js-audit",
485 "goal": "Audit a change with parallel agents",
486 "nodes": [
487 {
488 "branch": {
489 "id": "parallel-audit",
490 "children": [
491 {
492 "agent": {
493 "id": "docs-audit",
494 "prompt": "Inspect docs for missing updates",
495 "agent_type": "review",
496 "file_scope": ["docs"]
497 }
498 },
499 {
500 "agent": {
501 "id": "tests-audit",
502 "prompt": "Inspect targeted tests",
503 "agent_type": "verifier",
504 "budget": { "max_steps": 4 }
505 }
506 }
507 ]
508 }
509 },
510 {
511 "reduce": {
512 "id": "synthesize",
513 "inputs": ["docs-audit", "tests-audit"],
514 "prompt": "Merge the branch findings"
515 }
516 }
517 ]
518 });
519 "#;
520
521 let workflow =
522 compile_javascript_workflow("audit.workflow.js", source).expect("compile JS workflow");
523
524 assert_eq!(workflow.id.as_deref(), Some("js-audit"));
525 assert_eq!(workflow.nodes.len(), 2);
526 let WorkflowNode::BranchSet(branch) = &workflow.nodes[0] else {
527 panic!("first node should be a branch");
528 };
529 assert!(branch.parallel);
530 assert_eq!(branch.children.len(), 2);
531 let WorkflowNode::Leaf(leaf) = &branch.children[1] else {
532 panic!("second branch child should be a leaf");
533 };
534 assert_eq!(leaf.agent_type, AgentType::Verifier);
535 assert_eq!(leaf.budget.max_steps, Some(4));
536 assert!(matches!(workflow.nodes[1], WorkflowNode::Reduce(_)));
537 }
538
539 #[test]
540 fn typescript_workflow_allows_satisfies_suffix_without_executing_js() {
541 let source = r#"
542 export default workflow({
543 "goal": "TS authored workflow",
544 "nodes": [
545 { "agent": { "id": "scan", "prompt": "scan safely" } }
546 ]
547 } satisfies WorkflowSpec);
548 "#;
549
550 let workflow =
551 compile_typescript_workflow("scan.workflow.ts", source).expect("compile TS workflow");
552
553 assert_eq!(workflow.goal, "TS authored workflow");
554 assert_eq!(workflow.nodes.len(), 1);
555 }
556
557 #[test]
558 fn javascript_workflow_accepts_and_normalizes_agent_profile() {
559 let source = r#"
560 workflow({
561 "goal": "profile routing",
562 "nodes": [
563 { "agent": { "id": "review", "prompt": "review the diff", "profile": " Reviewer " } },
564 { "agent": { "id": "scan", "prompt": "scan safely" } }
565 ]
566 });
567 "#;
568
569 let workflow = compile_javascript_workflow("profile.workflow.js", source)
570 .expect("profile-carrying workflow should compile");
571
572 let WorkflowNode::Leaf(review) = &workflow.nodes[0] else {
573 panic!("first node should be a leaf");
574 };
575 assert_eq!(review.profile.as_deref(), Some("reviewer"));
576 let WorkflowNode::Leaf(scan) = &workflow.nodes[1] else {
577 panic!("second node should be a leaf");
578 };
579 assert_eq!(scan.profile, None);
580 }
581
582 #[test]
583 fn javascript_workflow_accepts_and_normalizes_agent_role() {
584 let source = r#"
585 workflow({
586 "goal": "role routing",
587 "nodes": [
588 { "agent": { "id": "scout-issue", "prompt": "Investigate #4090. Read-only.", "role": " Scout " } },
589 { "agent": { "id": "fix-it", "prompt": "Apply minimal fix.", "role": "implementer" } }
590 ]
591 });
592 "#;
593
594 let workflow = compile_javascript_workflow("role.workflow.js", source)
595 .expect("role-carrying workflow should compile");
596
597 let WorkflowNode::Leaf(scout) = &workflow.nodes[0] else {
598 panic!("first node should be a leaf");
599 };
600 assert_eq!(scout.role.as_deref(), Some("scout"));
601 assert_eq!(scout.profile, None);
602 // Provider/model are not required identity fields on role steps.
603 assert_eq!(scout.model_policy.provider, None);
604 assert_eq!(scout.model_policy.model, None);
605
606 let WorkflowNode::Leaf(fix) = &workflow.nodes[1] else {
607 panic!("second node should be a leaf");
608 };
609 assert_eq!(fix.role.as_deref(), Some("implementer"));
610 }
611
612 #[test]
613 fn javascript_workflow_accepts_gate_specs() {
614 let source = r#"
615 workflow({
616 "goal": "role gates",
617 "gates": [
618 {
619 "id": "scout-findings",
620 "role": " Scout ",
621 "on": "role_complete",
622 "gate": "approve",
623 "on_fail": "block",
624 "blocks_role": " Implementer ",
625 "artifact_kind": "findings"
626 }
627 ],
628 "nodes": [
629 { "agent": { "id": "scout", "prompt": "Find risk.", "role": "scout" } },
630 { "agent": { "id": "fix", "prompt": "Use findings.", "role": "implementer" } }
631 ]
632 });
633 "#;
634
635 let workflow =
636 compile_javascript_workflow("gates.workflow.js", source).expect("compile gates");
637
638 assert_eq!(workflow.gates.len(), 1);
639 let gate = &workflow.gates[0];
640 assert_eq!(gate.id, "scout-findings");
641 assert_eq!(gate.role, "scout");
642 assert_eq!(gate.on, GateOn::RoleComplete);
643 assert_eq!(gate.gate, GateKind::Approve);
644 assert_eq!(gate.on_fail, GateOnFail::Block);
645 assert_eq!(gate.blocks_role.as_deref(), Some("implementer"));
646 assert_eq!(gate.artifact_kind.as_deref(), Some("findings"));
647 }
648
649 #[test]
650 fn stopship_acceptance_fixture_is_read_only_and_gate_complete() {
651 let source = include_str!("../../../.codewhale/workflows/stopship.workflow.js");
652 let workflow = compile_javascript_workflow("stopship.workflow.js", source)
653 .expect("compile stopship acceptance fixture");
654
655 assert_eq!(workflow.id.as_deref(), Some("stopship-release-acceptance"));
656 let WorkflowNode::Sequence(sequence) = &workflow.nodes[0] else {
657 panic!("acceptance fixture should begin with one ordered role chain");
658 };
659 let expected_children = ["explore", "implement", "reviewer", "test", "release_lead"];
660 assert_eq!(sequence.children.len(), expected_children.len());
661 for (node, expected_role) in sequence.children.iter().zip(expected_children) {
662 let WorkflowNode::Leaf(leaf) = node else {
663 panic!("acceptance role chain must contain only agent leaves");
664 };
665 assert_eq!(leaf.role.as_deref(), Some(expected_role));
666 assert_eq!(leaf.mode, TaskMode::ReadOnly);
667 assert!(!leaf.permissions.allow_write);
668 // No explicit `allowed_tools` anywhere: the read-only lowering
669 // alone scopes the source-gathering explore role, and its
670 // read-only evidence surface is pinned from the engine tests.
671 assert!(leaf.permissions.allowed_tools.is_empty());
672 assert_eq!(
673 leaf.permissions.deny_all_tools,
674 expected_role != "explore",
675 "only the source-gathering explore role should receive tools"
676 );
677 assert!(
678 leaf.prompt.contains(
679 "first non-empty line of your response must be exactly APPROVE or exactly BLOCK"
680 ),
681 "{expected_role} must declare the host-readable verdict contract"
682 );
683 assert!(
684 leaf.prompt
685 .contains("Do not put any words before that verdict")
686 && leaf.prompt.contains("Here is the verdict"),
687 "{expected_role} must reject verdict preambles that the host cannot parse"
688 );
689 if expected_role == "explore" {
690 assert!(
691 !leaf.prompt.contains("tool_search")
692 && leaf.prompt.contains("Use `grep_files` with")
693 && leaf.prompt.contains(
694 "`grep_files` is available directly on your surface; call it without any activation step"
695 ),
696 "the scout must search with the content-search tool that is already on its surface"
697 );
698 assert!(
699 leaf.prompt
700 .contains("Read and search these files as needed"),
701 "discovery must be driven by missing evidence"
702 );
703 assert_eq!(
704 leaf.file_scope
705 .iter()
706 .map(String::as_str)
707 .collect::<Vec<_>>(),
708 vec![
709 ".codewhale/fleets/stopship.toml",
710 "crates/cli/src/lib.rs",
711 "crates/workflow/src/role_resolve.rs",
712 "crates/engine/src/tools/workflow/mod.rs",
713 "crates/lane/src/runtime.rs",
714 ],
715 "the scout grep must not include its own authored prompt"
716 );
717 let repository_root =
718 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
719 for path in &leaf.file_scope {
720 assert!(
721 repository_root.join(path).is_file(),
722 "scout evidence path must exist: {path}"
723 );
724 }
725 assert!(
726 leaf.prompt.contains(
727 "`include` set exactly to [`.codewhale/fleets/stopship.toml`, `crates/cli/src/lib.rs`, `crates/workflow/src/role_resolve.rs`, `crates/engine/src/tools/workflow/mod.rs`, `crates/lane/src/runtime.rs`]"
728 ) && leaf.prompt.contains("Matches outside that exact include list do not count"),
729 "the grep_files search must constrain the actual tool input, not only file scope metadata"
730 );
731 assert!(
732 leaf.prompt.contains("if you can populate all seven")
733 && leaf
734 .prompt
735 .contains("never return BLOCK after citing all seven")
736 && leaf
737 .prompt
738 .contains("identify each missing owner as MISSING"),
739 "the scout verdict must follow its own complete evidence artifact"
740 );
741 } else {
742 assert!(
743 leaf.prompt.contains("Tools are intentionally unavailable")
744 && leaf.prompt.contains("promoted handoff")
745 && leaf.prompt.contains("all seven owners")
746 && leaf.prompt.contains("one concise row per owner"),
747 "{expected_role} must consume promoted evidence without reopening discovery"
748 );
749 }
750 assert_eq!(
751 leaf.file_scope
752 .iter()
753 .map(String::as_str)
754 .collect::<Vec<_>>(),
755 vec![
756 ".codewhale/fleets/stopship.toml",
757 "crates/cli/src/lib.rs",
758 "crates/workflow/src/role_resolve.rs",
759 "crates/engine/src/tools/workflow/mod.rs",
760 "crates/lane/src/runtime.rs",
761 ],
762 "every acceptance role must carry the same promoted evidence boundary"
763 );
764 assert_eq!(leaf.budget.max_steps, None, "{expected_role}");
765 assert_eq!(leaf.budget.timeout_secs, None, "{expected_role}");
766 assert_eq!(leaf.budget.max_tokens, None, "{expected_role}");
767 assert!(!leaf.prompt.contains("at most"), "{expected_role}");
768 assert!(
769 !leaf.prompt.contains("reserve the verdict"),
770 "{expected_role}"
771 );
772 assert!(
773 leaf.profile.is_none(),
774 "Fleet must resolve the declared role"
775 );
776 }
777 let expected_gates = [
778 ("explore", Some("implement"), "source_evidence"),
779 ("implement", Some("reviewer"), "verification_plan"),
780 ("reviewer", Some("test"), "review_report"),
781 ("test", Some("release_lead"), "verification_report"),
782 ("release_lead", None, "final_receipt"),
783 ];
784 assert_eq!(workflow.gates.len(), expected_gates.len());
785 for (gate, (role, blocked_role, artifact_kind)) in workflow.gates.iter().zip(expected_gates)
786 {
787 assert_eq!(gate.role, role);
788 assert_eq!(gate.on, GateOn::RoleComplete);
789 assert_eq!(gate.on_fail, GateOnFail::Block);
790 assert_eq!(gate.blocks_role.as_deref(), blocked_role);
791 assert_eq!(gate.max_retries, 0);
792 assert_eq!(gate.artifact_kind.as_deref(), Some(artifact_kind));
793 assert!(
794 gate.require_explicit_verdict,
795 "{role} gate must fail closed when its verdict is missing or malformed"
796 );
797 }
798
799 let mut board = LaneGateBoard::new("lane-fixture-contract");
800 board.install_gates(&workflow.gates);
801 assert_eq!(
802 board
803 .evaluate(&workflow.gates[0], GateOutcome::Pass)
804 .expect("successful role promotes its gate"),
805 GateState::Passed
806 );
807 let failure = board
808 .evaluate(
809 &workflow.gates[3],
810 GateOutcome::Fail {
811 reason: "verifier receipt missing".to_string(),
812 },
813 )
814 .expect("failed verifier updates its gate");
815 assert!(matches!(failure, GateState::Blocked { .. }));
816 assert!(
817 board
818 .role_is_blocked(&workflow.gates, "release_lead")
819 .is_some()
820 );
821 }
822
823 #[test]
824 fn javascript_workflow_rejects_invalid_agent_profiles() {
825 for bad in [r#""""#, r#""has space""#, r#""quote\"y""#, r#""a=b""#] {
826 let source = format!(
827 r#"
828 workflow({{
829 "goal": "bad profile",
830 "nodes": [
831 {{ "agent": {{ "id": "scan", "prompt": "scan safely", "profile": {bad} }} }}
832 ]
833 }});
834 "#
835 );
836
837 let err = compile_javascript_workflow("bad-profile.workflow.js", &source)
838 .expect_err("invalid profile should be rejected");
839
840 assert!(
841 matches!(err, JavascriptWorkflowError::InvalidNode(_)),
842 "profile {bad} should fail as an invalid node, got {err:?}"
843 );
844 assert!(err.to_string().contains("profile"));
845 }
846 }
847
848 #[test]
849 fn javascript_workflow_names_removed_node_kinds_and_rejects_promotion_policy() {
850 for (node, kind) in [
851 (r#"{ "teacher_review": { "id": "t" } }"#, "teacher_review"),
852 (
853 r#"{ "kind": "loop_until", "spec": { "id": "l" } }"#,
854 "loop_until",
855 ),
856 (
857 r#"{ "branch": { "id": "b", "children": [{ "expand": { "id": "e" } }] } }"#,
858 "expand",
859 ),
860 ] {
861 let source = format!(r#"workflow({{ "goal": "old", "nodes": [{node}] }});"#);
862 let err = compile_javascript_workflow("old.workflow.js", &source)
863 .expect_err("removed node kinds must be rejected");
864 assert!(
865 matches!(&err, JavascriptWorkflowError::InvalidNode(message)
866 if message.contains(&format!("`{kind}` workflow nodes were removed"))),
867 "{kind}: {err}"
868 );
869 }
870
871 let err = compile_javascript_workflow(
872 "promotion.workflow.js",
873 r#"workflow({ "goal": "old", "promotion_policy": {}, "nodes": [] });"#,
874 )
875 .expect_err("promotion_policy must be rejected");
876 assert!(err.to_string().contains("unknown field `promotion_policy`"));
877 }
878
879 #[test]
880 fn javascript_workflow_rejects_runtime_effects() {
881 let source = r#"
882 import fs from "fs";
883 workflow({ "goal": "bad", "nodes": [] });
884 "#;
885
886 let err = compile_javascript_workflow("bad.workflow.js", source)
887 .expect_err("imports must be rejected");
888
889 assert!(matches!(
890 err,
891 JavascriptWorkflowError::UnsupportedConstruct {
892 construct: "import"
893 }
894 ));
895 }
896
897 #[test]
898 fn javascript_workflow_allows_construct_words_inside_strings() {
899 let source = r#"
900 // A comment's apostrophe isn't a string.
901 workflow({
902 "goal": "Make the fetch handler async and fix the import paths",
903 "nodes": [{ "agent": { "id": "fix", "prompt": "await open(path) and readFile it", "agent_type": "review" } }]
904 });
905 "#;
906
907 let workflow =
908 compile_javascript_workflow("words.workflow.js", source).expect("compile JS workflow");
909
910 assert_eq!(
911 workflow.goal,
912 "Make the fetch handler async and fix the import paths"
913 );
914 let err = compile_javascript_workflow(
915 "code.workflow.js",
916 &format!("{source}import fs from \"fs\";\n"),
917 )
918 .unwrap_err();
919 assert!(matches!(
920 err,
921 JavascriptWorkflowError::UnsupportedConstruct {
922 construct: "import"
923 }
924 ));
925 }
926
927 #[test]
928 fn javascript_workflow_rejects_unknown_result_reference() {
929 let source = r#"
930 workflow({
931 "goal": "bad dependency",
932 "nodes": [
933 {
934 "agent": {
935 "id": "scan",
936 "prompt": "scan safely",
937 "depends_on_results": ["missing"]
938 }
939 }
940 ]
941 });
942 "#;
943
944 let err = compile_javascript_workflow("bad-reference.workflow.js", source)
945 .expect_err("validation must reject unknown result references");
946
947 assert!(matches!(err, JavascriptWorkflowError::InvalidNode(_)));
948 assert!(err.to_string().contains("missing"));
949 }
950
951 #[test]
952 fn javascript_example_compiles_to_validated_ir() {
953 let source = include_str!("../../../.codewhale/workflows/issue_audit.workflow.js");
954 let workflow =
955 compile_javascript_workflow("issue_audit.workflow.js", source).expect("compile");
956
957 workflow
958 .validate_for_fleet()
959 .expect("example lowers to IR that passes Fleet validation");
960 assert_eq!(workflow.id.as_deref(), Some("issue-audit-js"));
961 assert_eq!(workflow.nodes.len(), 2, "{:#?}", workflow.nodes);
962 let WorkflowNode::BranchSet(branch) = &workflow.nodes[0] else {
963 panic!("first node should be the parallel audit branch");
964 };
965 let leaf_ids: Vec<&str> = branch
966 .children
967 .iter()
968 .map(|child| match child {
969 WorkflowNode::Leaf(leaf) => leaf.id.as_str(),
970 other => panic!("audit branch child should be an agent leaf: {other:?}"),
971 })
972 .collect();
973 assert_eq!(leaf_ids, ["code-audit", "test-audit", "docs-audit"]);
974 let WorkflowNode::Reduce(reduce) = &workflow.nodes[1] else {
975 panic!("second node should reduce the audit findings");
976 };
977 assert_eq!(reduce.id, "synthesize-release-risk");
978 assert_eq!(reduce.inputs, leaf_ids);
979 }
980 }
981
981 lines RUST