runkon-flow 0.1.0-alpha

Portable workflow execution engine — DSL, traits, and in-memory reference implementations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
use std::collections::HashMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// AST types
// ---------------------------------------------------------------------------

/// A complete workflow definition parsed from a `.wf` file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowDef {
    pub name: String,
    #[serde(default)]
    pub title: Option<String>,
    pub description: String,
    pub trigger: WorkflowTrigger,
    #[serde(default)]
    pub targets: Vec<String>,
    #[serde(default)]
    pub group: Option<String>,
    pub inputs: Vec<InputDecl>,
    pub body: Vec<WorkflowNode>,
    pub always: Vec<WorkflowNode>,
    pub source_path: String,
}

impl WorkflowDef {
    /// Returns the human-readable display name for this workflow.
    /// Falls back to `name` if no `title` is set.
    pub fn display_name(&self) -> &str {
        self.title.as_deref().unwrap_or(&self.name)
    }

    /// Total number of nodes across body and always blocks.
    pub fn total_nodes(&self) -> usize {
        count_nodes(&self.body) + count_nodes(&self.always)
    }

    /// Number of top-level steps (body + always, non-recursive).
    /// Better for user-facing progress display than `total_nodes()`.
    pub fn top_level_steps(&self) -> usize {
        self.body.len() + self.always.len()
    }

    /// Find the `max_iterations` of the do-while or while loop that owns
    /// the step with the given name. Returns `None` if the step is not
    /// inside a loop or the step name is not found.
    pub fn max_iterations_for_step(&self, step_name: &str) -> Option<u32> {
        fn search(nodes: &[WorkflowNode], name: &str) -> Option<u32> {
            for node in nodes {
                match node {
                    WorkflowNode::DoWhile(n) => {
                        if n.step == name {
                            return Some(n.max_iterations);
                        }
                        if let Some(v) = search(&n.body, name) {
                            return Some(v);
                        }
                    }
                    WorkflowNode::While(n) => {
                        if n.step == name {
                            return Some(n.max_iterations);
                        }
                        if let Some(v) = search(&n.body, name) {
                            return Some(v);
                        }
                    }
                    _ => {
                        if let Some(body) = node.body() {
                            if let Some(v) = search(body, name) {
                                return Some(v);
                            }
                        }
                    }
                }
            }
            None
        }
        search(&self.body, step_name).or_else(|| search(&self.always, step_name))
    }

    /// Collect all prompt snippet references across body and always blocks, sorted and deduplicated.
    pub fn collect_all_snippet_refs(&self) -> Vec<String> {
        let mut refs = collect_snippet_refs(&self.body);
        refs.extend(collect_snippet_refs(&self.always));
        refs.sort();
        refs.dedup();
        refs
    }

    /// Collect all output schema references across body and always blocks, sorted and deduplicated.
    pub fn collect_all_schema_refs(&self) -> Vec<String> {
        let mut refs = collect_schema_refs(&self.body);
        refs.extend(collect_schema_refs(&self.always));
        refs.sort();
        refs.dedup();
        refs
    }

    /// Collect all agent references across body and always blocks, sorted and deduplicated.
    pub fn collect_all_agent_refs(&self) -> Vec<AgentRef> {
        let mut refs = collect_agent_names(&self.body);
        refs.extend(collect_agent_names(&self.always));
        refs.sort();
        refs.dedup();
        refs
    }

    /// Collect all bot names referenced across body and always blocks, sorted and deduplicated.
    pub fn collect_all_bot_names(&self) -> Vec<String> {
        let mut names = collect_bot_names(&self.body);
        names.extend(collect_bot_names(&self.always));
        names.sort();
        names.dedup();
        names
    }

    /// Collect all plugin_dirs from call nodes across body and always blocks, sorted and deduplicated.
    pub fn collect_all_plugin_dirs(&self) -> Vec<String> {
        let mut dirs = collect_plugin_dirs(&self.body);
        dirs.extend(collect_plugin_dirs(&self.always));
        dirs.sort();
        dirs.dedup();
        dirs
    }
}

/// A structured parse warning produced when a `.wf` file fails to load.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowWarning {
    /// The filename (e.g. `bad.wf`) that failed to parse.
    pub file: String,
    /// Human-readable description of the parse error.
    pub message: String,
}

/// Trigger type for when a workflow should run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkflowTrigger {
    Manual,
    Pr,
    Scheduled,
}

impl std::fmt::Display for WorkflowTrigger {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Manual => write!(f, "manual"),
            Self::Pr => write!(f, "pr"),
            Self::Scheduled => write!(f, "scheduled"),
        }
    }
}

impl std::str::FromStr for WorkflowTrigger {
    type Err = String;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "manual" => Ok(Self::Manual),
            "pr" => Ok(Self::Pr),
            "scheduled" => Ok(Self::Scheduled),
            _ => Err(format!("unknown trigger: {s}")),
        }
    }
}

/// The type of a workflow input.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum InputType {
    #[default]
    String,
    Boolean,
}

/// An input declaration for a workflow.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputDecl {
    pub name: String,
    pub required: bool,
    pub default: Option<String>,
    pub description: Option<String>,
    #[serde(default)]
    pub input_type: InputType,
}

/// A node in the workflow execution graph.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum WorkflowNode {
    Call(CallNode),
    CallWorkflow(CallWorkflowNode),
    If(IfNode),
    Unless(UnlessNode),
    While(WhileNode),
    DoWhile(DoWhileNode),
    Do(DoNode),
    Parallel(ParallelNode),
    Gate(GateNode),
    Always(AlwaysNode),
    Script(ScriptNode),
    ForEach(ForEachNode),
}

impl WorkflowNode {
    /// Returns the child body slice for block-node variants, or `None` for leaf nodes.
    pub fn body(&self) -> Option<&[WorkflowNode]> {
        match self {
            WorkflowNode::If(n) => Some(&n.body),
            WorkflowNode::Unless(n) => Some(&n.body),
            WorkflowNode::While(n) => Some(&n.body),
            WorkflowNode::DoWhile(n) => Some(&n.body),
            WorkflowNode::Do(n) => Some(&n.body),
            WorkflowNode::Always(n) => Some(&n.body),
            _ => None,
        }
    }
}

/// A foreach step node — fans out a child workflow over a collection of items.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForEachNode {
    /// Step name used as the key in step_results and resume skip sets.
    pub name: String,
    /// The collection type to fan out over.
    pub over: ForeachOver,
    /// Raw scope key-value map passed to the provider's `parse_scope` method.
    pub scope: Option<HashMap<String, String>>,
    /// Generic filter map (required for workflow_run fan-outs, reserved for repos).
    #[serde(default)]
    pub filter: HashMap<String, String>,
    /// Whether to use dependency-ordered dispatch (tickets only).
    pub ordered: bool,
    /// What to do when a ticket cycle is detected (tickets + ordered only).
    pub on_cycle: OnCycle,
    /// Maximum number of child workflows to run concurrently.
    pub max_parallel: u32,
    /// Name of the child workflow to invoke for each item.
    pub workflow: String,
    /// Input map passed to each child workflow invocation.
    /// Values may contain `{{item.*}}` template references.
    #[serde(default)]
    pub inputs: HashMap<String, String>,
    /// How to handle a child workflow failure.
    pub on_child_fail: OnChildFail,
}

/// The collection type for a foreach step — the registered provider name.
pub type ForeachOver = String;

/// What to do when a child workflow fails.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnChildFail {
    /// Cancel in-flight runs and fail the step immediately.
    Halt,
    /// Log the failure and keep dispatching remaining items.
    Continue,
    /// Mark the failed item's transitive dependents as skipped (ordered tickets only).
    SkipDependents,
}

/// What to do when a ticket dependency cycle is detected.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnCycle {
    /// Abort with an error naming the cycle.
    Fail,
    /// Log a warning, break the back-edge, and continue.
    Warn,
}

/// A script step node — runs a shell script directly (no agent/LLM).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScriptNode {
    /// Step name used as the step key in step_results and resume skip sets.
    pub name: String,
    /// Path to the script to run (supports `{{variable}}` substitution).
    /// Resolved in order: worktree dir → repo dir → `~/.claude/skills/`.
    pub run: String,
    /// Environment variable overrides (values support `{{variable}}` substitution).
    #[serde(default)]
    pub env: HashMap<String, String>,
    /// Optional timeout in seconds. If the script does not complete within this
    /// duration it is killed and the step is marked `TimedOut`.
    pub timeout: Option<u64>,
    /// Number of retry attempts after the first failure (0 = no retries).
    #[serde(default)]
    pub retries: u32,
    /// Action to take if all attempts fail.
    pub on_fail: Option<OnFail>,
    /// Named GitHub App bot identity to use for this script (matches `[github.apps.<name>]`).
    /// When set, the resolved installation token is injected as `GH_TOKEN` so the script
    /// uses that bot identity for all `gh` CLI calls.
    pub bot_name: Option<String>,
}

/// The action to take when all retries for a `call`, `script`, or `call workflow` step exhaust.
///
/// - `Agent`: invoke a fallback agent (existing behaviour).
/// - `Continue`: skip the step without marking the workflow failed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum OnFail {
    Agent(AgentRef),
    Continue,
}

/// Reference to an agent — either a short name or an explicit file path.
///
/// - `Name`: bare identifier (e.g. `plan`) resolved via the search order.
/// - `Path`: quoted string (e.g. `".claude/agents/plan.md"`) resolved directly
///   relative to the repository root.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
pub enum AgentRef {
    Name(String),
    Path(String),
}

impl AgentRef {
    /// Human-readable label for display and logging (the inner string value).
    pub fn label(&self) -> &str {
        match self {
            Self::Name(s) | Self::Path(s) => s.as_str(),
        }
    }

    /// Key used to store and look up results in `step_results`.
    ///
    /// - `Name` variants return the name as-is.
    /// - `Path` variants return the file stem without extension
    ///   (e.g. `"plan"` from `".claude/agents/plan.md"`), so that `if`/`while`
    ///   conditions can reference path-based agents by their short name.
    pub fn step_key(&self) -> String {
        match self {
            Self::Name(s) => s.clone(),
            Self::Path(s) => Path::new(s)
                .file_stem()
                .and_then(|stem| stem.to_str())
                .unwrap_or(s.as_str())
                .to_string(),
        }
    }
}

impl std::fmt::Display for AgentRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.label())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallNode {
    pub agent: AgentRef,
    #[serde(default)]
    pub retries: u32,
    pub on_fail: Option<OnFail>,
    /// Optional output schema reference for structured output.
    pub output: Option<String>,
    /// Prompt snippet references to append to the agent prompt.
    #[serde(default)]
    pub with: Vec<String>,
    /// Named GitHub App bot identity to use for this call (matches `[github.apps.<name>]`).
    pub bot_name: Option<String>,
    /// Per-step plugin directories from the `.wf` file. Merged with repo-level
    /// `extra_plugin_dirs` at execution time to give this agent access to
    /// specialist plugins (e.g. `/usr/local/bsg/agent-architecture/planner`).
    #[serde(default)]
    pub plugin_dirs: Vec<String>,
    /// Optional per-step timeout (e.g. "5m", "30s", "1h"). If the step does not
    /// complete within this duration it is cancelled with `CancellationReason::Timeout`.
    pub timeout: Option<String>,
    /// Optional per-step host-enforced turn cap. Overrides the workflow-level default.
    /// `None` defers to `DEFAULT_MAX_TURNS` applied by the executor.
    #[serde(default)]
    pub max_turns: Option<u32>,
}

/// A sub-workflow invocation node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallWorkflowNode {
    pub workflow: String,
    #[serde(default)]
    pub inputs: HashMap<String, String>,
    #[serde(default)]
    pub retries: u32,
    pub on_fail: Option<OnFail>,
    /// Named GitHub App bot identity inherited by child call nodes.
    pub bot_name: Option<String>,
}

/// A condition in an `if`/`unless` block.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Condition {
    /// References a marker produced by a prior step: `step.marker`.
    StepMarker { step: String, marker: String },
    /// References a boolean input directly: `input_name`.
    BoolInput { input: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IfNode {
    pub condition: Condition,
    pub body: Vec<WorkflowNode>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnlessNode {
    pub condition: Condition,
    pub body: Vec<WorkflowNode>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WhileNode {
    pub step: String,
    pub marker: String,
    pub max_iterations: u32,
    pub stuck_after: Option<u32>,
    pub on_max_iter: OnMaxIter,
    pub body: Vec<WorkflowNode>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DoWhileNode {
    pub step: String,
    pub marker: String,
    pub max_iterations: u32,
    pub stuck_after: Option<u32>,
    pub on_max_iter: OnMaxIter,
    pub body: Vec<WorkflowNode>,
}

/// A plain sequential grouping block (`do { ... }`), with optional `output` and `with`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DoNode {
    /// Optional output schema reference for structured output.
    pub output: Option<String>,
    /// Prompt snippet references applied to all calls inside the block.
    #[serde(default)]
    pub with: Vec<String>,
    pub body: Vec<WorkflowNode>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnMaxIter {
    Fail,
    Continue,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParallelNode {
    #[serde(default = "default_true")]
    pub fail_fast: bool,
    pub min_success: Option<u32>,
    pub calls: Vec<AgentRef>,
    /// Block-level output schema reference (applies to all calls unless overridden).
    pub output: Option<String>,
    /// Per-call output schema overrides, keyed by index (as string) in `calls`.
    /// String keys are used because JSON object keys are always strings and serde_json
    /// cannot coerce them back to integer types on deserialization.
    #[serde(default)]
    pub call_outputs: HashMap<String, String>,
    /// Block-level prompt snippet references (applied to all calls).
    #[serde(default)]
    pub with: Vec<String>,
    /// Per-call prompt snippet additions, keyed by index (as string) in `calls`.
    #[serde(default)]
    pub call_with: HashMap<String, Vec<String>>,
    /// Per-call `if` conditions keyed by index (as string) in `calls`.
    /// Value is (step_name, marker_name). Run the call only if that marker is present.
    #[serde(default)]
    pub call_if: HashMap<String, (String, String)>,
    /// Per-call retry counts keyed by index (as string) in `calls`. 0 = no retries.
    #[serde(default)]
    pub call_retries: HashMap<String, u32>,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalMode {
    #[default]
    MinApprovals,
    ReviewDecision,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnFailAction {
    Fail,
    Continue,
}

/// Configuration specific to `GateType::QualityGate` nodes.
///
/// Grouped into a single struct so non-quality-gate construction sites need
/// only `quality_gate: None` instead of three separate optional fields.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityGateConfig {
    /// Step key whose structured output is evaluated.
    pub source: String,
    /// Minimum confidence score (0-100) required to pass.
    pub threshold: u32,
    /// Action when the gate fails (score below threshold).
    #[serde(default = "default_on_fail")]
    pub on_fail_action: OnFailAction,
}

fn default_on_fail() -> OnFailAction {
    OnFailAction::Fail
}

/// Specifies the set of options for a multi-select gate.
///
/// - `Static`: a literal key-value map of option strings defined in the workflow file.
/// - `StepRef`: a `"step.field"` reference resolved at runtime from a prior step's
///   structured output (the field must be a JSON object with string values).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GateOptions {
    Static(HashMap<String, String>),
    /// Raw `"step.field"` dotted reference — resolved at execution time.
    StepRef(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GateNode {
    pub name: String,
    pub gate_type: GateType,
    pub prompt: Option<String>,
    #[serde(default = "default_one")]
    pub min_approvals: u32,
    #[serde(default)]
    pub approval_mode: ApprovalMode,
    pub timeout_secs: u64,
    pub on_timeout: OnTimeout,
    /// Named GitHub App bot identity used for `gh` calls inside this gate.
    pub bot_name: Option<String>,
    /// Quality gate-specific configuration. Present only when `gate_type == QualityGate`.
    #[serde(flatten)]
    pub quality_gate: Option<QualityGateConfig>,
    /// Optional multi-select options for human_approval / human_review gates.
    pub options: Option<GateOptions>,
}

fn default_one() -> u32 {
    1
}

#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GateType {
    HumanApproval,
    HumanReview,
    PrApproval,
    PrChecks,
    QualityGate,
}

impl std::fmt::Display for GateType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::HumanApproval => write!(f, "human_approval"),
            Self::HumanReview => write!(f, "human_review"),
            Self::PrApproval => write!(f, "pr_approval"),
            Self::PrChecks => write!(f, "pr_checks"),
            Self::QualityGate => write!(f, "quality_gate"),
        }
    }
}

impl std::str::FromStr for GateType {
    type Err = String;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "human_approval" => Ok(Self::HumanApproval),
            "human_review" => Ok(Self::HumanReview),
            "pr_approval" => Ok(Self::PrApproval),
            "pr_checks" => Ok(Self::PrChecks),
            "quality_gate" => Ok(Self::QualityGate),
            _ => Err(format!("unknown gate type: {s}")),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnTimeout {
    Fail,
    Continue,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlwaysNode {
    pub body: Vec<WorkflowNode>,
}

// ---------------------------------------------------------------------------
// Tree-walking helpers
// ---------------------------------------------------------------------------

/// Count the total number of nodes in a node list (for display).
pub(crate) fn count_nodes(nodes: &[WorkflowNode]) -> usize {
    let mut count = 0;
    for node in nodes {
        count += 1;
        match node {
            WorkflowNode::Parallel(n) => count += n.calls.len(),
            _ => {
                if let Some(body) = node.body() {
                    count += count_nodes(body);
                }
            }
        }
    }
    count
}

/// Collect all agent references in a node tree (for validation before execution).
pub fn collect_agent_names(nodes: &[WorkflowNode]) -> Vec<AgentRef> {
    let mut refs = Vec::new();
    for node in nodes {
        match node {
            WorkflowNode::Call(n) => {
                refs.push(n.agent.clone());
                if let Some(OnFail::Agent(ref a)) = n.on_fail {
                    refs.push(a.clone());
                }
            }
            WorkflowNode::CallWorkflow(n) => {
                if let Some(OnFail::Agent(ref a)) = n.on_fail {
                    refs.push(a.clone());
                }
            }
            WorkflowNode::Script(n) => {
                if let Some(OnFail::Agent(ref a)) = n.on_fail {
                    refs.push(a.clone());
                }
            }
            WorkflowNode::Parallel(n) => refs.extend(n.calls.iter().cloned()),
            _ => {
                if let Some(body) = node.body() {
                    refs.extend(collect_agent_names(body));
                }
            }
        }
    }
    refs
}

/// Collect all prompt snippet references (`with` values) from a node tree.
pub(crate) fn collect_snippet_refs(nodes: &[WorkflowNode]) -> Vec<String> {
    let mut refs = Vec::new();
    for node in nodes {
        match node {
            WorkflowNode::Call(n) => refs.extend(n.with.iter().cloned()),
            WorkflowNode::Parallel(n) => {
                refs.extend(n.with.iter().cloned());
                for extra in n.call_with.values() {
                    refs.extend(extra.iter().cloned());
                }
            }
            WorkflowNode::Do(n) => {
                refs.extend(n.with.iter().cloned());
                refs.extend(collect_snippet_refs(&n.body));
            }
            _ => {
                if let Some(body) = node.body() {
                    refs.extend(collect_snippet_refs(body));
                }
            }
        }
    }
    refs
}

/// Collect all `call workflow` references in a node tree (for cycle detection).
pub fn collect_workflow_refs(nodes: &[WorkflowNode]) -> Vec<String> {
    let mut refs = Vec::new();
    for node in nodes {
        match node {
            WorkflowNode::Call(_) | WorkflowNode::Gate(_) | WorkflowNode::Script(_) => {}
            WorkflowNode::CallWorkflow(n) => refs.push(n.workflow.clone()),
            WorkflowNode::If(n) => refs.extend(collect_workflow_refs(&n.body)),
            WorkflowNode::Unless(n) => refs.extend(collect_workflow_refs(&n.body)),
            WorkflowNode::While(n) => refs.extend(collect_workflow_refs(&n.body)),
            WorkflowNode::DoWhile(n) => refs.extend(collect_workflow_refs(&n.body)),
            WorkflowNode::Do(n) => refs.extend(collect_workflow_refs(&n.body)),
            WorkflowNode::Parallel(_) => {} // parallel only contains agent calls
            WorkflowNode::Always(n) => refs.extend(collect_workflow_refs(&n.body)),
            // ForEach references a child workflow — include it for cycle detection
            WorkflowNode::ForEach(n) => refs.push(n.workflow.clone()),
        }
    }
    refs
}

/// Collect all output schema references (`output =` values) from a node tree.
pub(crate) fn collect_schema_refs(nodes: &[WorkflowNode]) -> Vec<String> {
    let mut refs = Vec::new();
    for node in nodes {
        match node {
            WorkflowNode::Call(n) => {
                if let Some(ref s) = n.output {
                    refs.push(s.clone());
                }
            }
            WorkflowNode::Do(n) => {
                if let Some(ref s) = n.output {
                    refs.push(s.clone());
                }
                refs.extend(collect_schema_refs(&n.body));
            }
            WorkflowNode::Parallel(n) => {
                if let Some(ref s) = n.output {
                    refs.push(s.clone());
                }
                refs.extend(n.call_outputs.values().cloned());
            }
            _ => {
                if let Some(body) = node.body() {
                    refs.extend(collect_schema_refs(body));
                }
            }
        }
    }
    refs
}

/// Collect all bot names (`bot_name =` values) from a node tree.
pub(crate) fn collect_bot_names(nodes: &[WorkflowNode]) -> Vec<String> {
    let mut names = Vec::new();
    for node in nodes {
        match node {
            WorkflowNode::Call(n) => {
                if let Some(ref b) = n.bot_name {
                    names.push(b.clone());
                }
            }
            WorkflowNode::CallWorkflow(n) => {
                if let Some(ref b) = n.bot_name {
                    names.push(b.clone());
                }
            }
            WorkflowNode::Gate(n) => {
                if let Some(ref b) = n.bot_name {
                    names.push(b.clone());
                }
            }
            WorkflowNode::Script(n) => {
                if let Some(ref b) = n.bot_name {
                    names.push(b.clone());
                }
            }
            _ => {
                if let Some(body) = node.body() {
                    names.extend(collect_bot_names(body));
                }
            }
        }
    }
    names
}

/// Collect all per-step plugin_dirs from call nodes in a node tree.
pub(crate) fn collect_plugin_dirs(nodes: &[WorkflowNode]) -> Vec<String> {
    let mut dirs = Vec::new();
    for node in nodes {
        match node {
            WorkflowNode::Call(n) => dirs.extend(n.plugin_dirs.iter().cloned()),
            _ => {
                if let Some(body) = node.body() {
                    dirs.extend(collect_plugin_dirs(body));
                }
            }
        }
    }
    dirs
}