Skip to main content

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