deepstrike_core/orchestration/workflow/mod.rs
1//! Declarative workflow shapes — the six patterns as composable templates.
2//!
3//! A [`WorkflowSpec`] is a pure, declarative DAG of [`WorkflowNode`]s, each carrying the
4//! per-node execution contract (role / isolation / context inheritance / model hint) that
5//! the SDK turns into an `AgentRunSpec` at spawn time. This is the data the template
6//! constructors below emit, and the shape a future "orchestration-as-syscall" round will
7//! lower into per-step [`crate::syscall::Syscall`]s.
8//!
9//! Three patterns are template constructors here. The dynamic control-flow patterns —
10//! loop-until-done, classify-and-act, and tournament — are now first-class [`NodeKind`] variants
11//! ([`NodeKind::Loop`] / [`NodeKind::Classify`] / [`NodeKind::Tournament`]) driven by the unified
12//! workflow executor; the former standalone `loop_until_done` / `tournament` SDK primitives were
13//! removed in their favor (A#1). The generate→evaluate→retry quality gate is the [`gen_eval`]
14//! template (a `Loop` worker + a `Verify` eval node carrying [`crate::harness::verdict_output_schema`]);
15//! its eval/verdict compute lives in [`crate::harness`].
16//!
17//! Pure: no I/O, no clock, no spawning. Validation reuses [`TaskGraph::topological_sort`].
18
19use serde::{Deserialize, Serialize};
20
21use super::task_graph::TaskGraph;
22use crate::types::agent::{AgentIsolation, AgentRole, ContextInheritance};
23use crate::types::error::{DeepStrikeError, Result};
24use crate::types::task::RuntimeTask;
25
26/// The kernel-resident execution state for an in-flight [`WorkflowSpec`] — the DAG run-queue,
27/// tournament bracket advancement, and per-node spawn descriptors. Was `scheduler/workflow_run.rs`;
28/// folded under `workflow` so the declarative spec and its runtime live in one module.
29pub mod run;
30pub use run::*;
31
32/// W3: a node's trust level. `Quarantined` nodes read untrusted content and must run with no
33/// privileges; their output crosses into the trusted plane only as a structured summary (the SDK
34/// enforces this — the kernel carries the flag to every spawn descriptor).
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
36#[serde(rename_all = "snake_case")]
37pub enum NodeTrust {
38 #[default]
39 Trusted,
40 Quarantined,
41}
42
43/// How a node interprets the terminal states of its declared dependencies.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
45#[serde(rename_all = "snake_case")]
46pub enum DependencyPolicy {
47 /// Every dependency must finish with a complete (non-partial) result.
48 #[default]
49 AllSuccess,
50 /// Complete and partial results satisfy the dependency; failures do not.
51 AcceptPartial,
52 /// Wait for every dependency to terminate, regardless of its outcome.
53 AllTerminal,
54 /// Dependencies are inputs when available, but never gate execution.
55 Optional,
56}
57
58/// One branch of a [`NodeKind::Classify`] node: a label and the node indices to enable when the
59/// classifier's result selects that label. The other branches' nodes are pruned (failed) so they
60/// never run — this is how a classify node yields *conditional edges* in an otherwise static DAG.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct ClassifyBranch {
63 pub label: String,
64 pub nodes: Vec<usize>,
65}
66
67/// Control-flow kind of a workflow node. `Spawn` (the default) runs the node's agent once.
68/// `Loop` re-runs it until a stop condition; `Classify` routes to one branch by its result;
69/// `Tournament` generates entrants and pairwise-judges them — all dynamic control-flow types.
70/// Additive: existing specs omit `kind` → `Spawn`. (No `Eq`: a `Tournament`'s entrant tasks carry
71/// arbitrary JSON metadata, which is `PartialEq` but not `Eq`.)
72#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
73#[serde(rename_all = "snake_case", tag = "type")]
74pub enum NodeKind {
75 /// Run the node's agent once (classic spawn node).
76 #[default]
77 Spawn,
78 /// Re-run the node's agent up to `max_iters` times; an iteration reporting
79 /// `loop_continue=Some(false)` stops early (v2 "until done").
80 Loop { max_iters: usize },
81 /// Run the node's agent once as a classifier; its `classify_branch` result selects one branch
82 /// to run and prunes the others. Branch nodes must `depends_on` this classify node.
83 ///
84 /// NOTE (W-11): prefer expressing classify-and-act via *runtime submission* — run the
85 /// classifier as a plain node and have it `submit_workflow_nodes` only the chosen branch. That
86 /// form needs no branch pre-declaration, prune bookkeeping, or resume branch-replay, and is the
87 /// CC-parity model-driven shape. `Classify` stays for declaratively auditable topologies (the
88 /// full branch set is visible up front) but should not grow new capabilities.
89 Classify { branches: Vec<ClassifyBranch> },
90 /// A *controller* node (spawns no agent of its own): it generates `entrants` candidates in
91 /// parallel, then runs a single-elimination bracket of pairwise judges (reusing
92 /// [`super::tournament::Tournament`]) until one survivor remains. The winner's id lands in the
93 /// node's `tournament_winner` result; dependents start only after the bracket resolves.
94 Tournament { entrants: Vec<RuntimeTask> },
95 /// G2 deterministic compute: a *host-compute* node that runs no LLM agent. The kernel schedules
96 /// it like a `Spawn` (deps / ready / completion) but stamps its spawn descriptor with `reducer`
97 /// + the dependency agent ids, and the SDK routes it to a registered pure function over those
98 /// dependencies' outputs (dedupe / filter / merge / early-exit) instead of the model. This is the
99 /// "ordinary code between stages" of the code-orchestration model, expressed as a DAG node — no
100 /// agent burned, fully deterministic. `reducer` names the SDK-side function.
101 Reduce { reducer: String },
102}
103
104/// One node in a workflow DAG: a task plus the contract its agent runs under.
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct WorkflowNode {
107 pub task: RuntimeTask,
108 pub role: AgentRole,
109 pub isolation: AgentIsolation,
110 pub context_inheritance: ContextInheritance,
111 /// Optional model preference (e.g. "opus" / "sonnet"); the SDK resolves it. See W4.
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub model_hint: Option<String>,
114 /// W3 trust level. Default `Trusted`.
115 #[serde(default, skip_serializing_if = "is_trusted")]
116 pub trust: NodeTrust,
117 /// G3 structured output: an optional JSON Schema the node's agent output must conform to. The
118 /// kernel is zero-I/O and never validates it — it carries the schema verbatim to the spawn
119 /// descriptor so the SDK can instruct the agent and validate/retry on its result (the structured
120 /// "summary only" contract from image 8 is enforced SDK-side; the kernel owns the contract).
121 /// Additive: omitted on the wire when absent.
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub output_schema: Option<serde_json::Value>,
124 /// Control-flow kind. Default `Spawn` (run once).
125 #[serde(default, skip_serializing_if = "is_spawn")]
126 pub kind: NodeKind,
127 /// M4/G5: optional per-node cumulative token cap. The kernel carries it to the spawn descriptor;
128 /// the SDK sets the node's child-run `max_total_tokens` to it, so an expensive node self-terminates
129 /// at the cap (the "use N tokens" budget, applied per node). Additive: omitted on the wire when
130 /// `None`.
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub token_budget: Option<u64>,
133 /// O3 per-node turn cap: the SDK sets the child run's `max_turns` (falls back to the parent's).
134 /// Mirrors `token_budget` — same hop chain, additive ABI.
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub max_turns: Option<u32>,
137 /// O3 per-node wall-clock cap (ms): the SDK sets the child run's timeout. Additive ABI.
138 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub max_wall_ms: Option<u64>,
140 /// Policy for interpreting this node's dependency terminal states.
141 #[serde(default)]
142 pub dep_policy: DependencyPolicy,
143 /// Indices into [`WorkflowSpec::nodes`] this node depends on.
144 #[serde(default, skip_serializing_if = "Vec::is_empty")]
145 pub depends_on: Vec<usize>,
146}
147
148fn is_trusted(t: &NodeTrust) -> bool {
149 matches!(t, NodeTrust::Trusted)
150}
151
152fn is_spawn(k: &NodeKind) -> bool {
153 matches!(k, NodeKind::Spawn)
154}
155
156impl WorkflowNode {
157 /// A node with role-default isolation/inheritance and no dependencies.
158 pub fn new(task: RuntimeTask, role: AgentRole) -> Self {
159 let (isolation, context_inheritance) = role_defaults(role);
160 Self {
161 task,
162 role,
163 isolation,
164 context_inheritance,
165 model_hint: None,
166 trust: NodeTrust::Trusted,
167 output_schema: None,
168 kind: NodeKind::Spawn,
169 token_budget: None,
170 max_turns: None,
171 max_wall_ms: None,
172 dep_policy: DependencyPolicy::AllSuccess,
173 depends_on: Vec::new(),
174 }
175 }
176
177 /// M4/G5: cap this node's child run at `tokens` cumulative tokens.
178 pub fn with_token_budget(mut self, tokens: u64) -> Self {
179 self.token_budget = Some(tokens);
180 self
181 }
182
183 /// O3: cap this node's child run at `turns` provider turns.
184 pub fn with_max_turns(mut self, turns: u32) -> Self {
185 self.max_turns = Some(turns);
186 self
187 }
188
189 /// O3: cap this node's child run at `ms` wall-clock milliseconds.
190 pub fn with_max_wall_ms(mut self, ms: u64) -> Self {
191 self.max_wall_ms = Some(ms);
192 self
193 }
194
195 /// Make this a loop node: re-run the agent up to `max_iters` times before completing.
196 /// Dependents wait for the whole loop to finish.
197 pub fn with_loop(mut self, max_iters: usize) -> Self {
198 self.kind = NodeKind::Loop { max_iters };
199 self
200 }
201
202 /// Make this a classify node: its result selects one of `branches` to run; the rest are pruned.
203 pub fn with_classify(mut self, branches: Vec<ClassifyBranch>) -> Self {
204 self.kind = NodeKind::Classify { branches };
205 self
206 }
207
208 /// Make this a tournament *controller* node: it spawns no agent of its own but generates each
209 /// of `entrants` (in parallel), then pairwise-judges them to a single winner. The node's own
210 /// `task.goal` is the judging criterion handed to every judge. Requires ≥2 entrants.
211 pub fn with_tournament(mut self, entrants: Vec<RuntimeTask>) -> Self {
212 self.kind = NodeKind::Tournament { entrants };
213 self
214 }
215
216 /// G2: make this a deterministic *reduce* node — it runs no LLM agent; the SDK routes it to the
217 /// registered `reducer` function over its dependencies' outputs (dedupe / filter / merge). Give
218 /// it `depends_on` the nodes whose outputs it consumes.
219 pub fn with_reduce(mut self, reducer: impl Into<String>) -> Self {
220 self.kind = NodeKind::Reduce {
221 reducer: reducer.into(),
222 };
223 self
224 }
225
226 pub fn with_depends_on(mut self, depends_on: Vec<usize>) -> Self {
227 self.depends_on = depends_on;
228 self
229 }
230
231 pub fn with_dependency_policy(mut self, policy: DependencyPolicy) -> Self {
232 self.dep_policy = policy;
233 self
234 }
235
236 pub fn with_isolation(mut self, isolation: AgentIsolation) -> Self {
237 self.isolation = isolation;
238 self
239 }
240
241 pub fn with_model_hint(mut self, hint: impl Into<String>) -> Self {
242 self.model_hint = Some(hint.into());
243 self
244 }
245
246 /// W3: mark this node's trust level. `Quarantined` nodes read untrusted content and are
247 /// kernel-enforced to read-only (a quarantined node declaring write isolation is denied).
248 pub fn with_trust(mut self, trust: NodeTrust) -> Self {
249 self.trust = trust;
250 self
251 }
252
253 /// Mark this node as quarantined (reads untrusted content, runs without privileges).
254 pub fn quarantined(mut self) -> Self {
255 self.trust = NodeTrust::Quarantined;
256 self
257 }
258
259 /// G3: require this node's output to conform to a JSON Schema. The kernel carries it verbatim to
260 /// the spawn descriptor; the SDK instructs the agent and validates/retries on its result.
261 pub fn with_output_schema(mut self, schema: serde_json::Value) -> Self {
262 self.output_schema = Some(schema);
263 self
264 }
265}
266
267/// Role-appropriate defaults for a freshly templated node. Verifiers/explorers run
268/// read-only with minimal inherited context to resist self-preferential bias.
269fn role_defaults(role: AgentRole) -> (AgentIsolation, ContextInheritance) {
270 match role {
271 AgentRole::Explore => (AgentIsolation::ReadOnly, ContextInheritance::SystemOnly),
272 AgentRole::Verify => (AgentIsolation::ReadOnly, ContextInheritance::None),
273 AgentRole::Plan => (AgentIsolation::Shared, ContextInheritance::Full),
274 AgentRole::Implement => (AgentIsolation::Worktree, ContextInheritance::Full),
275 AgentRole::Custom => (AgentIsolation::Shared, ContextInheritance::None),
276 }
277}
278
279/// A declarative workflow DAG.
280#[derive(Debug, Clone, Default, Serialize, Deserialize)]
281pub struct WorkflowSpec {
282 pub nodes: Vec<WorkflowNode>,
283}
284
285impl WorkflowSpec {
286 pub fn new(nodes: Vec<WorkflowNode>) -> Self {
287 Self { nodes }
288 }
289
290 /// Validate dependency indices are in range and the graph is acyclic.
291 pub fn validate(&self) -> Result<TaskGraph> {
292 let n = self.nodes.len();
293 for (i, node) in self.nodes.iter().enumerate() {
294 if let NodeKind::Loop { max_iters: 0 } = node.kind {
295 return Err(DeepStrikeError::InvalidConfig(format!(
296 "node {i} is a loop with max_iters=0 (would never run)"
297 )));
298 }
299 if let NodeKind::Tournament { entrants } = &node.kind {
300 if entrants.len() < 2 {
301 return Err(DeepStrikeError::InvalidConfig(format!(
302 "tournament node {i} needs at least 2 entrants (have {})",
303 entrants.len()
304 )));
305 }
306 }
307 if let NodeKind::Classify { branches } = &node.kind {
308 for branch in branches {
309 for &bn in &branch.nodes {
310 if bn >= n {
311 return Err(DeepStrikeError::InvalidConfig(format!(
312 "classify node {i} branch '{}' references out-of-range node {bn}",
313 branch.label
314 )));
315 }
316 // Branch nodes must be gated by the classifier, else they'd run before
317 // classification and the prune would come too late.
318 if !self.nodes[bn].depends_on.contains(&i) {
319 return Err(DeepStrikeError::InvalidConfig(format!(
320 "classify node {i} branch '{}' node {bn} must depends_on {i}",
321 branch.label
322 )));
323 }
324 }
325 }
326 }
327 for &dep in &node.depends_on {
328 if dep >= n {
329 return Err(DeepStrikeError::InvalidConfig(format!(
330 "node {i} depends on out-of-range node {dep} (have {n})"
331 )));
332 }
333 if dep == i {
334 return Err(DeepStrikeError::InvalidConfig(format!(
335 "node {i} depends on itself"
336 )));
337 }
338 }
339 }
340 // Reuse the executor's cycle detection; hand the built graph back so callers
341 // that need it (WorkflowRun::new) don't lower + range-check a second time.
342 let graph = self.to_task_graph()?;
343 graph.topological_sort()?;
344 Ok(graph)
345 }
346
347 /// Lower into an executable [`TaskGraph`] (preserves node order as task ids).
348 pub fn to_task_graph(&self) -> Result<TaskGraph> {
349 let n = self.nodes.len();
350 let mut graph = TaskGraph::new();
351 for node in &self.nodes {
352 if let Some(&bad) = node.depends_on.iter().find(|&&d| d >= n) {
353 return Err(DeepStrikeError::InvalidConfig(format!(
354 "dependency index {bad} out of range (have {n})"
355 )));
356 }
357 graph.add(node.task.clone(), node.depends_on.clone());
358 }
359 Ok(graph)
360 }
361}
362
363// ---------------------------------------------------------------------------
364// Pattern 1 — Fan-out-and-synthesize
365// ---------------------------------------------------------------------------
366
367/// N parallel workers feeding a single synthesize barrier that depends on all of them.
368///
369/// Workers run as read-only `Explore` agents in the `Retrieve` lane (parallelisable, each
370/// with its own clean context); the synthesizer is a `Plan` agent that merges their
371/// structured outputs.
372pub fn fanout_synthesize(workers: Vec<RuntimeTask>, synthesize: RuntimeTask) -> WorkflowSpec {
373 let mut nodes: Vec<WorkflowNode> = workers
374 .into_iter()
375 .map(|t| WorkflowNode::new(t, AgentRole::Explore))
376 .collect();
377 let worker_ids: Vec<usize> = (0..nodes.len()).collect();
378 nodes.push(WorkflowNode::new(synthesize, AgentRole::Plan).with_depends_on(worker_ids));
379 WorkflowSpec::new(nodes)
380}
381
382// ---------------------------------------------------------------------------
383// Pattern 2 — Generate-and-filter
384// ---------------------------------------------------------------------------
385
386/// N parallel generators feeding a single filter/dedupe step that depends on all of them.
387///
388/// Structurally a fan-out barrier, but semantically distinct: generators are `Implement`
389/// agents producing candidates; the filter is a `Verify` agent that ranks/dedupes against
390/// a rubric (pair with the [`gen_eval`] verdict schema for the rubric).
391pub fn generate_and_filter(generators: Vec<RuntimeTask>, filter: RuntimeTask) -> WorkflowSpec {
392 let mut nodes: Vec<WorkflowNode> = generators
393 .into_iter()
394 .map(|t| WorkflowNode::new(t, AgentRole::Implement))
395 .collect();
396 let gen_ids: Vec<usize> = (0..nodes.len()).collect();
397 nodes.push(WorkflowNode::new(filter, AgentRole::Verify).with_depends_on(gen_ids));
398 WorkflowSpec::new(nodes)
399}
400
401// ---------------------------------------------------------------------------
402// W2 — Adversarial verification (the default contract)
403// ---------------------------------------------------------------------------
404
405/// One fresh-context verifier per rule/claim, optionally followed by a skeptic that re-checks
406/// every flag to suppress false positives.
407///
408/// This is the article's rule-adherence pattern. Each verifier runs as a `Verify` agent, which
409/// [`role_defaults`] gives `ReadOnly` isolation + [`ContextInheritance::None`] — the verifier does
410/// **not** inherit the author's reasoning, so it cannot rubber-stamp it (the structural defence
411/// against self-preferential bias). The optional `skeptic` depends on all verifiers and reviews
412/// their flags (real violation vs. false positive). Runs on the W0 workflow executor.
413///
414/// For unknown-size rule sets (claim extraction), a dynamic-fan-out variant is a later round; this
415/// covers the case where the rule/claim set is known up front. For the generate→evaluate→retry
416/// quality gate (scoring one author's output against criteria), see [`gen_eval`].
417pub fn verify_rules(rules: Vec<RuntimeTask>, skeptic: Option<RuntimeTask>) -> WorkflowSpec {
418 let mut nodes: Vec<WorkflowNode> = rules
419 .into_iter()
420 .map(|t| WorkflowNode::new(t, AgentRole::Verify))
421 .collect();
422 if let Some(skeptic) = skeptic {
423 let verifier_ids: Vec<usize> = (0..nodes.len()).collect();
424 nodes.push(WorkflowNode::new(skeptic, AgentRole::Verify).with_depends_on(verifier_ids));
425 }
426 WorkflowSpec::new(nodes)
427}
428
429// ---------------------------------------------------------------------------
430// Quality gate — generate → evaluate (#6, the EvalPipeline successor)
431// ---------------------------------------------------------------------------
432
433/// The generate→evaluate quality gate as a workflow: a `Loop` **worker** node (the task, re-run up
434/// to `max_iters`, stopping early on a `loop_continue=false` self-signal) followed by a `Verify`
435/// **eval** node that scores the worker's output against the goal/criteria and emits a structured
436/// verdict ([`crate::harness::verdict_output_schema`] as its `output_schema`).
437///
438/// This is the declarative substrate form of the former `EvalPipeline` (0.5.0 fold, OS-axis #6).
439/// The eval node is a `Verify` agent — [`role_defaults`] gives it `ReadOnly` + [`ContextInheritance::None`]
440/// so it does not inherit the worker's reasoning (bias resistance); it evaluates the worker's
441/// *output*, carried in via its task goal. The verdict's `passed` is the gate.
442///
443/// For the **iterative retry-with-feedback** variant (re-run the worker with the eval's feedback
444/// folded into the next attempt), the SDK `AttemptLoop` drives this with the same
445/// [`crate::harness::build_eval_messages`] / [`crate::harness::parse_verdict`] primitives — the
446/// kernel `Loop` re-arms a single node, so per-iteration eval is necessarily SDK-driven.
447pub fn gen_eval(
448 worker: RuntimeTask,
449 eval: RuntimeTask,
450 max_iters: usize,
451 extract_skill_on_pass: bool,
452) -> WorkflowSpec {
453 let worker_node = WorkflowNode::new(worker, AgentRole::Implement).with_loop(max_iters.max(1));
454 let eval_node = WorkflowNode::new(eval, AgentRole::Verify)
455 .with_depends_on(vec![0])
456 .with_output_schema(crate::harness::verdict_output_schema(extract_skill_on_pass));
457 WorkflowSpec::new(vec![worker_node, eval_node])
458}
459
460#[cfg(test)]
461mod tests {
462 use super::*;
463
464 fn task(goal: &str) -> RuntimeTask {
465 RuntimeTask::new(goal)
466 }
467
468 #[test]
469 fn fanout_synthesize_shape() {
470 let spec = fanout_synthesize(
471 vec![task("search A"), task("search B"), task("search C")],
472 task("merge findings"),
473 );
474 assert_eq!(spec.nodes.len(), 4);
475 // synthesize node depends on all three workers
476 assert_eq!(spec.nodes[3].depends_on, vec![0, 1, 2]);
477 assert_eq!(spec.nodes[3].role, AgentRole::Plan);
478 assert_eq!(spec.nodes[0].role, AgentRole::Explore);
479 assert_eq!(spec.nodes[0].isolation, AgentIsolation::ReadOnly);
480 spec.validate().unwrap();
481 // workers are the only ready tasks before any completion
482 let mut graph = spec.to_task_graph().unwrap();
483 assert_eq!(graph.ready_tasks(), vec![0, 1, 2]);
484 }
485
486 #[test]
487 fn generate_and_filter_shape() {
488 let spec = generate_and_filter(vec![task("idea 1"), task("idea 2")], task("dedupe + rank"));
489 assert_eq!(spec.nodes.len(), 3);
490 assert_eq!(spec.nodes[2].depends_on, vec![0, 1]);
491 assert_eq!(spec.nodes[2].role, AgentRole::Verify);
492 assert_eq!(spec.nodes[2].context_inheritance, ContextInheritance::None);
493 assert_eq!(spec.nodes[0].role, AgentRole::Implement);
494 spec.validate().unwrap();
495 }
496
497 #[test]
498 fn verify_rules_with_skeptic_shape() {
499 let spec = verify_rules(
500 vec![
501 task("money is integer cents"),
502 task("errors propagate"),
503 task("utc timestamps"),
504 ],
505 Some(task("skeptic: real violation or false positive?")),
506 );
507 assert_eq!(spec.nodes.len(), 4);
508 // skeptic depends on every verifier
509 assert_eq!(spec.nodes[3].depends_on, vec![0, 1, 2]);
510 assert_eq!(spec.nodes[3].role, AgentRole::Verify);
511 spec.validate().unwrap();
512 // verifiers are the ready set; skeptic gated behind them
513 assert_eq!(spec.to_task_graph().unwrap().ready_tasks(), vec![0, 1, 2]);
514 }
515
516 #[test]
517 fn verify_rules_verifiers_are_bias_resistant() {
518 // The default contract: every verifier runs with no inherited author context.
519 let spec = verify_rules(vec![task("rule a"), task("rule b")], None);
520 assert_eq!(spec.nodes.len(), 2); // no skeptic → just the verifiers
521 for node in &spec.nodes {
522 assert_eq!(node.role, AgentRole::Verify);
523 assert_eq!(node.context_inheritance, ContextInheritance::None);
524 assert_eq!(node.isolation, AgentIsolation::ReadOnly);
525 assert!(node.depends_on.is_empty()); // all parallel
526 }
527 spec.validate().unwrap();
528 }
529
530 #[test]
531 fn gen_eval_shape() {
532 // Worker loops; eval is a bias-resistant Verify node gated on the worker, carrying the
533 // verdict output_schema.
534 let spec = gen_eval(
535 task("implement feature"),
536 task("score against criteria"),
537 3,
538 true,
539 );
540 assert_eq!(spec.nodes.len(), 2);
541
542 let worker = &spec.nodes[0];
543 assert_eq!(worker.role, AgentRole::Implement);
544 assert_eq!(worker.kind, NodeKind::Loop { max_iters: 3 });
545 assert!(worker.depends_on.is_empty());
546
547 let eval = &spec.nodes[1];
548 assert_eq!(eval.role, AgentRole::Verify);
549 assert_eq!(eval.context_inheritance, ContextInheritance::None);
550 assert_eq!(eval.isolation, AgentIsolation::ReadOnly);
551 assert_eq!(eval.depends_on, vec![0]);
552 let schema = eval
553 .output_schema
554 .as_ref()
555 .expect("eval node carries verdict schema");
556 assert!(schema["properties"]["passed"].is_object());
557 assert!(schema["properties"]["skill"].is_object()); // extract_skill_on_pass=true
558
559 spec.validate().unwrap();
560 // Worker is the only initially-ready node; eval is gated.
561 assert_eq!(spec.to_task_graph().unwrap().ready_tasks(), vec![0]);
562 }
563
564 #[test]
565 fn gen_eval_max_iters_floor_and_no_skill() {
566 // max_iters=0 would be an invalid loop; the template floors it to 1.
567 let spec = gen_eval(task("w"), task("e"), 0, false);
568 assert_eq!(spec.nodes[0].kind, NodeKind::Loop { max_iters: 1 });
569 // extract_skill_on_pass=false ⇒ no skill property in the verdict schema.
570 let schema = spec.nodes[1].output_schema.as_ref().unwrap();
571 assert!(schema["properties"]["skill"].is_null());
572 spec.validate().unwrap();
573 }
574
575 #[test]
576 fn verify_rules_empty_with_skeptic_is_just_skeptic() {
577 // No rules → skeptic has nothing to depend on; still a valid single-node spec.
578 let spec = verify_rules(vec![], Some(task("skeptic")));
579 assert_eq!(spec.nodes.len(), 1);
580 assert!(spec.nodes[0].depends_on.is_empty());
581 spec.validate().unwrap();
582 }
583
584 #[test]
585 fn validate_rejects_out_of_range_dep() {
586 let spec = WorkflowSpec::new(vec![
587 WorkflowNode::new(task("a"), AgentRole::Explore),
588 WorkflowNode::new(task("b"), AgentRole::Plan).with_depends_on(vec![5]),
589 ]);
590 assert!(spec.validate().is_err());
591 }
592
593 #[test]
594 fn validate_rejects_self_dependency() {
595 let spec = WorkflowSpec::new(vec![
596 WorkflowNode::new(task("a"), AgentRole::Plan).with_depends_on(vec![0]),
597 ]);
598 assert!(spec.validate().is_err());
599 }
600
601 #[test]
602 fn validate_rejects_cycle() {
603 // 0 -> 1 -> 0 forms a cycle (both reference each other)
604 let spec = WorkflowSpec::new(vec![
605 WorkflowNode::new(task("a"), AgentRole::Plan).with_depends_on(vec![1]),
606 WorkflowNode::new(task("b"), AgentRole::Plan).with_depends_on(vec![0]),
607 ]);
608 assert!(spec.validate().is_err());
609 }
610
611 #[test]
612 fn tournament_node_requires_two_entrants() {
613 // ≥2 entrants is valid; <2 is a spec error (no contest).
614 let ok = WorkflowSpec::new(vec![
615 WorkflowNode::new(task("rank"), AgentRole::Plan)
616 .with_tournament(vec![task("a"), task("b")]),
617 ]);
618 ok.validate().unwrap();
619
620 let one = WorkflowSpec::new(vec![
621 WorkflowNode::new(task("rank"), AgentRole::Plan).with_tournament(vec![task("only")]),
622 ]);
623 assert!(one.validate().is_err());
624 }
625
626 #[test]
627 fn tournament_node_kind_round_trips_and_gates_dependents() {
628 let spec = WorkflowSpec::new(vec![
629 WorkflowNode::new(task("pick best"), AgentRole::Plan).with_tournament(vec![
630 task("x"),
631 task("y"),
632 task("z"),
633 ]),
634 WorkflowNode::new(task("use winner"), AgentRole::Implement).with_depends_on(vec![0]),
635 ]);
636 spec.validate().unwrap();
637 // Only the controller is ready up front; the dependent waits for the bracket.
638 assert_eq!(spec.to_task_graph().unwrap().ready_tasks(), vec![0]);
639 // serde keeps the entrants under the tagged `tournament` kind.
640 let json = serde_json::to_string(&spec.nodes[0].kind).unwrap();
641 assert!(json.contains("\"type\":\"tournament\""), "{json}");
642 let back: NodeKind = serde_json::from_str(&json).unwrap();
643 assert_eq!(back, spec.nodes[0].kind);
644 }
645
646 #[test]
647 fn node_builder_overrides_defaults() {
648 let n = WorkflowNode::new(task("x"), AgentRole::Verify)
649 .with_isolation(AgentIsolation::Worktree)
650 .with_model_hint("opus");
651 assert_eq!(n.isolation, AgentIsolation::Worktree);
652 assert_eq!(n.model_hint.as_deref(), Some("opus"));
653 // default inheritance for Verify is None (bias-resistant)
654 assert_eq!(n.context_inheritance, ContextInheritance::None);
655 }
656}