terraphim_orchestrator 1.20.2

AI Dark Factory orchestrator wiring spawner, router, supervisor into a reconciliation loop
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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
use std::collections::HashMap;
use std::path::PathBuf;
use std::process::ExitCode;
use std::str::FromStr;

use crate::config::{AgentDefinition, OrchestratorConfig};
use crate::{
    AgentOrchestrator, AgentRunRequest, AgentRuntimeValidationReport, ModeResult,
    OrchestratorError, SyntheticEvent, TriggerMode, validate_agent_runtime,
};
use cron::Schedule;
use serde::Serialize;

const LEGACY_PROJECT: &str = "<legacy>";

fn parse_cron(expr: &str) -> Result<Schedule, OrchestratorError> {
    let parts: Vec<&str> = expr.split_whitespace().collect();
    let full_expr = match parts.len() {
        5 => format!("0 {} *", expr),
        6 => format!("{} *", expr),
        7 => expr.to_string(),
        _ => {
            return Err(OrchestratorError::Config(format!(
                "invalid cron '{}': expected 5, 6, or 7 fields, got {}",
                expr,
                parts.len()
            )));
        }
    };
    Schedule::from_str(&full_expr)
        .map_err(|e| OrchestratorError::Config(format!("invalid cron '{}': {}", expr, e)))
}

pub fn applicable_modes(agent: &AgentDefinition) -> Vec<TriggerMode> {
    let mut modes = vec![TriggerMode::Local];
    if agent.schedule.is_some() {
        modes.push(TriggerMode::Cron);
    }
    if agent.event_only {
        modes.push(TriggerMode::PullRequest);
        modes.push(TriggerMode::Push);
    } else {
        modes.push(TriggerMode::Mention);
    }
    modes.push(TriggerMode::Webhook);
    modes
}

pub fn schedule_for_agent(config: &OrchestratorConfig, agent_name: &str) -> Option<String> {
    config
        .agents
        .iter()
        .find(|a| a.name == agent_name)
        .and_then(|a| a.schedule.clone())
}

pub fn is_cron_schedule_valid(expr: &str) -> bool {
    parse_cron(expr).is_ok()
}

fn validate_agent_mode(
    _config: &OrchestratorConfig,
    agent: &AgentDefinition,
    mode: TriggerMode,
) -> ModeResult {
    let mut warnings = Vec::new();
    let runnable = match mode {
        TriggerMode::Cron => {
            if let Some(ref expr) = agent.schedule {
                if is_cron_schedule_valid(expr) {
                    true
                } else {
                    warnings.push(format!("invalid cron expression: {}", expr));
                    false
                }
            } else {
                warnings.push("agent has no cron schedule".to_string());
                false
            }
        }
        TriggerMode::PullRequest | TriggerMode::Push => {
            if agent.event_only {
                true
            } else {
                warnings.push("agent is not event-only".to_string());
                false
            }
        }
        TriggerMode::Mention => {
            if agent.event_only {
                warnings.push("event-only agent cannot be mention-dispatched".to_string());
                false
            } else {
                true
            }
        }
        TriggerMode::Local => !agent.cli_tool.trim().is_empty(),
        TriggerMode::Webhook => true,
    };

    let cli_tool_probe = if !agent.cli_tool.trim().is_empty() {
        Some(crate::probe_cli_tool(&agent.cli_tool).unwrap_or(false))
    } else {
        None
    };

    let model_probe = agent
        .model
        .as_ref()
        .map(|m| crate::probe_model_available(m, agent.provider.as_deref()).unwrap_or(false));

    ModeResult {
        trigger_mode: mode,
        runnable,
        cli_tool_probe,
        model_probe,
        synthetic_event_ok: None,
        warnings,
    }
}

pub fn validate_agent_all_modes(
    config: &OrchestratorConfig,
    agent: &AgentDefinition,
) -> (
    AgentRuntimeValidationReport,
    HashMap<TriggerMode, ModeResult>,
) {
    let request = match &agent.project {
        Some(p) => AgentRunRequest::new(&agent.name).with_project(p),
        None => AgentRunRequest::new(&agent.name),
    };

    let runtime_report =
        validate_agent_runtime(config, &request).unwrap_or_else(|_| AgentRuntimeValidationReport {
            agent_name: agent.name.clone(),
            project: agent
                .project
                .clone()
                .unwrap_or_else(|| LEGACY_PROJECT.to_string()),
            layer: format!("{:?}", agent.layer),
            schedule: agent.schedule.clone(),
            cli_tool: agent.cli_tool.clone(),
            model: agent.model.clone(),
            working_dir: config.working_dir_for_agent(agent).display().to_string(),
            repo_ok: config.working_dir_for_agent(agent).is_dir(),
            gitea_target: None,
            evolution_requested: agent.evolution_enabled,
            evolution_available: config.evolution.enabled && agent.evolution_enabled,
            runnable: false,
            cli_tool_probe: None,
            model_probe: None,
            warnings: vec!["validation failed".to_string()],
        });

    let modes = applicable_modes(agent);
    let mode_results: HashMap<TriggerMode, ModeResult> = modes
        .into_iter()
        .map(|m| (m, validate_agent_mode(config, agent, m)))
        .collect();

    let all_runnable = mode_results.values().all(|r| r.runnable);

    let report = AgentRuntimeValidationReport {
        runnable: runtime_report.runnable && all_runnable,
        ..runtime_report
    };

    (report, mode_results)
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentSubcommand {
    Validate {
        agent_name: Option<String>,
        project: Option<String>,
        format: OutputFormat,
        skip_model_probe: bool,
    },
    ValidateAll {
        config: PathBuf,
        format: OutputFormat,
        skip_model_probe: bool,
    },
    RunSynthetic {
        agent_name: String,
        project: Option<String>,
        event: SyntheticEvent,
        format: OutputFormat,
        /// Optional path to a file whose contents are injected into the agent
        /// task as the verbatim reviewer findings (Gitea terraphim-ai#2264).
        findings: Option<PathBuf>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
    Human,
    #[default]
    Json,
}

impl std::str::FromStr for OutputFormat {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "human" => Ok(OutputFormat::Human),
            "json" => Ok(OutputFormat::Json),
            _ => Err(format!("unknown format: {s}")),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct AgentValidateAllReport {
    pub agents: HashMap<String, AgentRuntimeValidationReport>,
    pub mode_results: HashMap<String, HashMap<TriggerMode, ModeResult>>,
    pub total: usize,
    pub runnable: usize,
    pub failed: usize,
    pub all_modes_runnable: bool,
}

pub fn parse_agent_args(args: &[String]) -> Result<AgentSubcommand, String> {
    let mut iter = args.iter();
    let mut subcommand: Option<String> = None;
    let mut agent_name: Option<String> = None;
    let mut project: Option<String> = None;
    let mut format: OutputFormat = OutputFormat::default();
    let mut skip_model_probe = false;
    let mut config: Option<PathBuf> = None;
    let mut event: Option<SyntheticEvent> = None;
    let mut findings: Option<PathBuf> = None;

    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "validate" | "validate-all" | "run" => {
                if let Some(prev) = &subcommand {
                    return Err(format!("multiple subcommands: {} and {}", prev, arg));
                }
                subcommand = Some(arg.clone());
            }
            "--project" | "-p" => {
                project = Some(iter.next().ok_or("--project requires a value")?.clone());
            }
            "--format" | "-f" => {
                let val = iter.next().ok_or("--format requires a value")?;
                format = val.parse().map_err(|e: String| e)?;
            }
            "--skip-model-probe" => {
                skip_model_probe = true;
            }
            "--config" | "-c" => {
                config = Some(PathBuf::from(
                    iter.next().ok_or("--config requires a value")?,
                ));
            }
            "--synthetic-event" => {
                let ev = iter
                    .next()
                    .ok_or("--synthetic-event requires an event type")?;
                event = match ev.as_str() {
                    "pr" | "pull_request" => Some(SyntheticEvent::PullRequest {
                        number: 1,
                        head_sha: "HEAD_SHA".to_string(),
                        author: "test".to_string(),
                        title: "Test PR".to_string(),
                        diff_loc: 100,
                    }),
                    "push" => Some(SyntheticEvent::Push {
                        sha: "HEAD_SHA".to_string(),
                        ref_name: "refs/heads/main".to_string(),
                        pusher: "test".to_string(),
                        files: vec![],
                    }),
                    _ => return Err(format!("unknown synthetic event type: {ev}")),
                };
            }
            "--pr" => {
                let num: u64 = iter
                    .next()
                    .ok_or("--pr requires a number")?
                    .parse()
                    .map_err(|e| format!("--pr requires a number: {e}"))?;
                event = Some(SyntheticEvent::PullRequest {
                    number: num,
                    head_sha: "HEAD_SHA".to_string(),
                    author: "test".to_string(),
                    title: "Test PR".to_string(),
                    diff_loc: 100,
                });
            }
            "--push" => {
                event = Some(SyntheticEvent::Push {
                    sha: "HEAD_SHA".to_string(),
                    ref_name: "refs/heads/main".to_string(),
                    pusher: "test".to_string(),
                    files: vec![],
                });
            }
            "--findings" => {
                findings = Some(PathBuf::from(
                    iter.next().ok_or("--findings requires a path")?,
                ));
            }
            _ if arg.starts_with("-") => {
                return Err(format!("unknown flag: {arg}"));
            }
            _ => {
                if agent_name.is_some() {
                    return Err(format!("unexpected positional argument: {arg}"));
                }
                agent_name = Some(arg.clone());
            }
        }
    }

    let subcommand = subcommand.unwrap_or("validate".to_string());
    match subcommand.as_str() {
        "validate" => Ok(AgentSubcommand::Validate {
            agent_name,
            project,
            format,
            skip_model_probe,
        }),
        "validate-all" => Ok(AgentSubcommand::ValidateAll {
            config: config.ok_or("--config required for validate-all")?,
            format,
            skip_model_probe,
        }),
        "run" => Ok(AgentSubcommand::RunSynthetic {
            agent_name: agent_name.ok_or("run requires an agent name")?,
            project,
            event: event.ok_or("run requires --synthetic-event")?,
            format,
            findings,
        }),
        _ => Err(format!("unknown subcommand: {subcommand}")),
    }
}

pub fn run_validate(
    config: &OrchestratorConfig,
    agent_name: Option<String>,
    project: Option<String>,
    format: OutputFormat,
    _skip_model_probe: bool,
) -> ExitCode {
    if let Some(name) = agent_name {
        let request = match &project {
            Some(p) => AgentRunRequest::new(&name).with_project(p),
            None => AgentRunRequest::new(&name),
        };
        match validate_agent_runtime(config, &request) {
            Ok(report) => {
                print_validation_report(&report, format);
                if report.runnable {
                    ExitCode::SUCCESS
                } else {
                    ExitCode::from(1)
                }
            }
            Err(e) => {
                eprintln!("validate failed: {e}");
                ExitCode::from(1)
            }
        }
    } else {
        let mut reports: HashMap<String, AgentRuntimeValidationReport> = HashMap::new();
        let mut mode_results: HashMap<String, HashMap<TriggerMode, ModeResult>> = HashMap::new();
        let mut runnable = 0;
        let mut failed = 0;
        for agent in &config.agents {
            let (report, modes) = validate_agent_all_modes(config, agent);
            if report.runnable {
                runnable += 1;
            } else {
                failed += 1;
            }
            reports.insert(agent.name.clone(), report);
            mode_results.insert(agent.name.clone(), modes);
        }
        let all_modes_runnable = failed == 0;
        let all_report = AgentValidateAllReport {
            agents: reports,
            mode_results,
            total: runnable + failed,
            runnable,
            failed,
            all_modes_runnable,
        };
        print_validate_all_report(&all_report, format);
        if !all_modes_runnable {
            ExitCode::from(1)
        } else {
            ExitCode::SUCCESS
        }
    }
}

pub fn run_validate_all(
    config: PathBuf,
    format: OutputFormat,
    _skip_model_probe: bool,
) -> ExitCode {
    let config = match OrchestratorConfig::from_file(&config) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("failed to load config: {e}");
            return ExitCode::from(1);
        }
    };
    let mut reports: HashMap<String, AgentRuntimeValidationReport> = HashMap::new();
    let mut mode_results: HashMap<String, HashMap<TriggerMode, ModeResult>> = HashMap::new();
    let mut runnable = 0;
    let mut failed = 0;
    for agent in &config.agents {
        let (report, modes) = validate_agent_all_modes(&config, agent);
        if report.runnable {
            runnable += 1;
        } else {
            failed += 1;
        }
        reports.insert(agent.name.clone(), report);
        mode_results.insert(agent.name.clone(), modes);
    }
    let all_modes_runnable = failed == 0;
    let all_report = AgentValidateAllReport {
        agents: reports,
        mode_results,
        total: runnable + failed,
        runnable,
        failed,
        all_modes_runnable,
    };
    print_validate_all_report(&all_report, format);
    if !all_modes_runnable {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

/// Run a named agent against a synthetic event (Gitea terraphim-ai#2264).
///
/// Resolves the agent from `config`, injects the synthetic event env vars and
/// (for the PullRequest event) the optional `--findings` body into the agent
/// task, and spawns it through the orchestrator's existing local-spawn path
/// (`spawn_agent_with_event`). Returns exit 0 on a clean spawn, non-zero on
/// resolution or spawn failure.
///
/// The Push event is not supported for synthetic runs in this scope and returns
/// a clear error.
pub fn run_synthetic(
    config: &OrchestratorConfig,
    agent_name: &str,
    project: Option<String>,
    event: SyntheticEvent,
    format: OutputFormat,
) -> ExitCode {
    run_synthetic_with_findings(config, agent_name, project, event, format, None)
}

/// As [`run_synthetic`] but with an explicit findings path injected into the
/// PR-event agent task. Split out so the CLI dispatcher and tests can supply
/// `--findings` without re-parsing.
pub fn run_synthetic_with_findings(
    config: &OrchestratorConfig,
    agent_name: &str,
    project: Option<String>,
    event: SyntheticEvent,
    format: OutputFormat,
    findings: Option<PathBuf>,
) -> ExitCode {
    // Only the PullRequest event is supported for synthetic spawn in this scope.
    if let SyntheticEvent::Push { .. } = event {
        eprintln!("synthetic run not supported for the Push event in this scope");
        let report =
            synthetic_failure_report(agent_name, &project, "synthetic Push event not supported");
        print_validation_report(&report, format);
        return ExitCode::from(1);
    }

    // Resolve the agent definition. Match on name and, when a project is given,
    // on the project binding so repo-local agents resolve correctly.
    let def = config.agents.iter().find(|a| {
        a.name == agent_name
            && match &project {
                Some(p) => a.project.as_deref() == Some(p.as_str()),
                None => true,
            }
    });
    let Some(def) = def else {
        eprintln!(
            "synthetic run: agent '{}' not found{}",
            agent_name,
            project
                .as_ref()
                .map(|p| format!(" in project '{p}'"))
                .unwrap_or_default()
        );
        let report = synthetic_failure_report(agent_name, &project, "agent not found");
        print_validation_report(&report, format);
        return ExitCode::from(1);
    };

    // Clone the definition and inject the findings (when supplied) into the task
    // as a read-only "Reviewer findings" preamble, mirroring what the
    // @adf:pr-remediation trigger comment carries in production.
    let mut def = def.clone();
    if let Some(path) = &findings {
        match std::fs::read_to_string(path) {
            Ok(body) => {
                def.task = format!(
                    "## Reviewer findings (verbatim, read-only)\n\n{}\n\n---\n\n{}",
                    body.trim_end(),
                    def.task
                );
            }
            Err(e) => {
                eprintln!(
                    "synthetic run: failed to read --findings {}: {e}",
                    path.display()
                );
                let report =
                    synthetic_failure_report(agent_name, &project, "failed to read findings file");
                print_validation_report(&report, format);
                return ExitCode::from(1);
            }
        }
    }

    // Build the orchestrator and spawn through the existing event-aware path.
    // run_synthetic is synchronous but the spawn path is async; bridge via a
    // current-thread runtime, or block_in_place when already inside a runtime.
    // `AgentOrchestrator::new` itself spawns reactor-bound tasks, so both the
    // construction and the spawn must run inside a Tokio runtime.
    let event_desc = format!("{event:?}");
    let cfg = config.clone();
    let drive = async move {
        let mut orch = AgentOrchestrator::new(cfg)?;
        orch.spawn_agent_with_event(&def, Some(&event)).await
    };

    let result = match tokio::runtime::Handle::try_current() {
        Ok(handle) => tokio::task::block_in_place(|| handle.block_on(drive)),
        Err(_) => {
            let rt = match tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
            {
                Ok(rt) => rt,
                Err(e) => {
                    eprintln!("synthetic run: failed to build runtime: {e}");
                    let report =
                        synthetic_failure_report(agent_name, &project, "failed to build runtime");
                    print_validation_report(&report, format);
                    return ExitCode::from(1);
                }
            };
            rt.block_on(drive)
        }
    };

    match result {
        Ok(()) => {
            println!("synthetic run: spawned agent '{agent_name}' for {event_desc}");
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("synthetic run: failed to spawn '{}': {e}", agent_name);
            let report = synthetic_failure_report(agent_name, &project, "spawn failed");
            print_validation_report(&report, format);
            ExitCode::from(1)
        }
    }
}

fn synthetic_failure_report(
    agent_name: &str,
    project: &Option<String>,
    warning: &str,
) -> AgentRuntimeValidationReport {
    AgentRuntimeValidationReport {
        agent_name: agent_name.to_string(),
        project: project
            .clone()
            .unwrap_or_else(|| LEGACY_PROJECT.to_string()),
        layer: "unknown".to_string(),
        schedule: None,
        cli_tool: String::new(),
        model: None,
        working_dir: ".".to_string(),
        repo_ok: false,
        gitea_target: None,
        evolution_requested: false,
        evolution_available: false,
        runnable: false,
        cli_tool_probe: None,
        model_probe: None,
        warnings: vec![warning.to_string()],
    }
}

fn print_validation_report(report: &AgentRuntimeValidationReport, format: OutputFormat) {
    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(report).unwrap());
        }
        OutputFormat::Human => {
            println!("Agent: {}", report.agent_name);
            println!("Project: {}", report.project);
            println!("Layer: {}", report.layer);
            println!("Schedule: {:?}", report.schedule);
            println!("CLI Tool: {}", report.cli_tool);
            println!("Model: {:?}", report.model);
            println!("Working Dir: {}", report.working_dir);
            println!("Repo OK: {}", report.repo_ok);
            println!("CLI Probe: {:?}", report.cli_tool_probe);
            println!("Model Probe: {:?}", report.model_probe);
            println!("Runnable: {}", report.runnable);
            if !report.warnings.is_empty() {
                println!("Warnings:");
                for w in &report.warnings {
                    println!("  - {w}");
                }
            }
        }
    }
}

fn print_validate_all_report(report: &AgentValidateAllReport, format: OutputFormat) {
    match format {
        OutputFormat::Json => {
            println!("{}", serde_json::to_string_pretty(report).unwrap());
        }
        OutputFormat::Human => {
            println!("Validation Summary:");
            println!("  Total: {}", report.total);
            println!("  Runnable: {}", report.runnable);
            println!("  Failed: {}", report.failed);
            println!("  All Modes Runnable: {}", report.all_modes_runnable);
            println!();
            for (name, r) in &report.agents {
                println!(
                    "  [{}] {} ({})",
                    if r.runnable { "OK" } else { "FAIL" },
                    name,
                    r.project
                );
                if let Some(modes) = report.mode_results.get(name) {
                    for (mode, result) in modes {
                        println!(
                            "    {:?}: runnable={}, cli_probe={:?}, model_probe={:?}",
                            mode, result.runnable, result.cli_tool_probe, result.model_probe
                        );
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_validate_no_args() {
        let args = vec!["validate".to_string()];
        let cmd = parse_agent_args(&args).unwrap();
        assert!(matches!(
            cmd,
            AgentSubcommand::Validate {
                agent_name: None,
                ..
            }
        ));
    }

    #[test]
    fn parse_validate_with_agent() {
        let args = vec!["validate".to_string(), "security-sentinel".to_string()];
        let cmd = parse_agent_args(&args).unwrap();
        let AgentSubcommand::Validate { agent_name, .. } = cmd else {
            panic!("expected Validate")
        };
        assert_eq!(agent_name, Some("security-sentinel".to_string()));
    }

    #[test]
    fn parse_validate_all_requires_config() {
        let args = vec!["validate-all".to_string()];
        let err = parse_agent_args(&args).unwrap_err();
        assert!(err.contains("--config required"));
    }

    #[test]
    fn parse_validate_all_with_config() {
        let args = vec![
            "validate-all".to_string(),
            "--config".to_string(),
            "/path/to/config.toml".to_string(),
        ];
        let cmd = parse_agent_args(&args).unwrap();
        let AgentSubcommand::ValidateAll { config, .. } = cmd else {
            panic!("expected ValidateAll")
        };
        assert_eq!(config, PathBuf::from("/path/to/config.toml"));
    }

    #[test]
    fn parse_run_requires_agent_and_event() {
        let args = vec!["run".to_string()];
        let err = parse_agent_args(&args).unwrap_err();
        assert!(err.contains("run requires an agent name"));

        let args = vec!["run".to_string(), "security-sentinel".to_string()];
        let err = parse_agent_args(&args).unwrap_err();
        assert!(err.contains("run requires --synthetic-event"));
    }

    #[test]
    fn parse_run_with_synthetic_pr() {
        let args = vec![
            "run".to_string(),
            "security-sentinel".to_string(),
            "--synthetic-event".to_string(),
            "pr".to_string(),
            "--pr".to_string(),
            "42".to_string(),
        ];
        let cmd = parse_agent_args(&args).unwrap();
        let AgentSubcommand::RunSynthetic {
            agent_name, event, ..
        } = cmd
        else {
            panic!("expected RunSynthetic")
        };
        assert_eq!(agent_name, "security-sentinel");
        assert!(matches!(
            event,
            SyntheticEvent::PullRequest { number: 42, .. }
        ));
    }

    #[test]
    fn parse_run_with_findings() {
        let args = vec![
            "run".to_string(),
            "pr-remediation".to_string(),
            "--synthetic-event".to_string(),
            "pr".to_string(),
            "--pr".to_string(),
            "17".to_string(),
            "--findings".to_string(),
            "/tmp/findings.md".to_string(),
        ];
        let cmd = parse_agent_args(&args).unwrap();
        let AgentSubcommand::RunSynthetic {
            agent_name,
            findings,
            ..
        } = cmd
        else {
            panic!("expected RunSynthetic")
        };
        assert_eq!(agent_name, "pr-remediation");
        assert_eq!(findings, Some(PathBuf::from("/tmp/findings.md")));
    }

    #[test]
    fn parse_run_with_synthetic_push() {
        let args = vec![
            "run".to_string(),
            "pr-reviewer".to_string(),
            "--synthetic-event".to_string(),
            "push".to_string(),
        ];
        let cmd = parse_agent_args(&args).unwrap();
        let AgentSubcommand::RunSynthetic {
            agent_name, event, ..
        } = cmd
        else {
            panic!("expected RunSynthetic")
        };
        assert_eq!(agent_name, "pr-reviewer");
        assert!(matches!(event, SyntheticEvent::Push { .. }));
    }

    #[test]
    fn parse_validate_with_project() {
        let args = vec![
            "validate".to_string(),
            "security-sentinel".to_string(),
            "--project".to_string(),
            "terraphim".to_string(),
        ];
        let cmd = parse_agent_args(&args).unwrap();
        let AgentSubcommand::Validate {
            agent_name,
            project,
            ..
        } = cmd
        else {
            panic!("expected Validate")
        };
        assert_eq!(agent_name, Some("security-sentinel".to_string()));
        assert_eq!(project, Some("terraphim".to_string()));
    }

    #[test]
    fn output_format_parsing() {
        assert!(matches!(
            "human".parse::<OutputFormat>(),
            Ok(OutputFormat::Human)
        ));
        assert!(matches!(
            "json".parse::<OutputFormat>(),
            Ok(OutputFormat::Json)
        ));
        assert!("yaml".parse::<OutputFormat>().is_err());
    }

    fn make_agent(name: &str, schedule: Option<&str>, event_only: bool) -> AgentDefinition {
        AgentDefinition {
            extra_projects: Vec::new(),
            name: name.to_string(),
            layer: AgentLayer::Core,
            cli_tool: "echo".to_string(),
            task: "test".to_string(),
            schedule: schedule.map(String::from),
            model: Some("minimax-coding-plan/MiniMax-M2.5".to_string()),
            default_tier: None,
            capabilities: vec![],
            max_memory_bytes: None,
            budget_monthly_cents: None,
            provider: None,
            persona: None,
            terraphim_role: None,
            skill_chain: vec![],
            sfia_skills: vec![],
            fallback_provider: None,
            fallback_model: None,
            grace_period_secs: None,
            max_cpu_seconds: None,
            pre_check: None,
            gitea_issue: None,
            event_only,
            project: None,
            evolution_enabled: false,
            rlm_enabled: None,
            bypass_kg_routing: false,
            enabled: true,
        }
    }

    #[test]
    fn applicable_modes_cron_agent() {
        let agent = make_agent("security-sentinel", Some("0 */6 * * *"), false);
        let modes = applicable_modes(&agent);
        assert!(modes.contains(&TriggerMode::Cron));
        assert!(modes.contains(&TriggerMode::Local));
        assert!(!modes.contains(&TriggerMode::PullRequest));
        assert!(!modes.contains(&TriggerMode::Push));
    }

    #[test]
    fn applicable_modes_event_only_agent() {
        let agent = make_agent("pr-reviewer", None, true);
        let modes = applicable_modes(&agent);
        assert!(modes.contains(&TriggerMode::PullRequest));
        assert!(modes.contains(&TriggerMode::Push));
        assert!(modes.contains(&TriggerMode::Local));
        assert!(!modes.contains(&TriggerMode::Cron));
    }

    #[test]
    fn is_cron_schedule_valid_valid() {
        assert!(is_cron_schedule_valid("0 */6 * * *"));
        assert!(is_cron_schedule_valid("15 0-10 * * *"));
        assert!(is_cron_schedule_valid("*/30 * * * *"));
    }

    #[test]
    fn is_cron_schedule_valid_invalid() {
        assert!(!is_cron_schedule_valid("not a cron"));
        assert!(!is_cron_schedule_valid(""));
        assert!(!is_cron_schedule_valid("60 0 * * *"));
    }

    use crate::OrchestratorConfig;
    use crate::config::{AgentDefinition, AgentLayer};
    use tempfile::TempDir;

    fn test_config(agents: Vec<AgentDefinition>) -> OrchestratorConfig {
        let tmp = TempDir::new().unwrap();
        OrchestratorConfig {
            project_sources: Vec::new(),
            working_dir: tmp.path().to_path_buf(),
            nightwatch: Default::default(),
            compound_review: Default::default(),
            workflow: None,
            agents,
            restart_cooldown_secs: 60,
            max_restart_count: 10,
            restart_budget_window_secs: 43_200,
            disk_usage_threshold: 90,
            tick_interval_secs: 30,
            gate_reconcile_interval_ticks: 20,
            handoff_buffer_ttl_secs: None,
            persona_data_dir: None,
            skill_data_dir: None,
            flows: vec![],
            flow_state_dir: None,
            gitea: None,
            mentions: None,
            webhook: None,
            role_config_path: None,
            routing: None,
            #[cfg(feature = "quickwit")]
            quickwit: None,
            projects: vec![],
            include: vec![],
            providers: vec![],
            provider_budget_state_file: None,
            pause_dir: None,
            project_circuit_breaker_threshold: 3,
            fleet_escalation_owner: None,
            fleet_escalation_repo: None,
            post_merge_gate: None,
            auto_merge: None,
            learning: Default::default(),
            evolution: Default::default(),
            pr_dispatch: None,
            pr_dispatch_per_project: std::collections::HashMap::new(),
            gitea_skill_repo: None,
            direct_dispatch: None,
        }
    }

    #[test]
    fn schedule_for_agent_finds_schedule() {
        let agent = make_agent("security-sentinel", Some("0 */6 * * *"), false);
        let config = test_config(vec![agent]);
        assert_eq!(
            schedule_for_agent(&config, "security-sentinel"),
            Some("0 */6 * * *".to_string())
        );
    }

    #[test]
    fn schedule_for_agent_not_found() {
        let agent = make_agent("security-sentinel", Some("0 */6 * * *"), false);
        let config = test_config(vec![agent]);
        assert_eq!(schedule_for_agent(&config, "nonexistent"), None);
    }

    #[test]
    fn validate_agent_all_modes_cron_agent() {
        let agent = make_agent("security-sentinel", Some("0 */6 * * *"), false);
        let config = test_config(vec![agent.clone()]);
        let (report, mode_results) = validate_agent_all_modes(&config, &agent);
        assert_eq!(report.agent_name, "security-sentinel");
        assert!(mode_results.contains_key(&TriggerMode::Cron));
        assert!(mode_results.contains_key(&TriggerMode::Local));
        assert!(mode_results.get(&TriggerMode::Cron).unwrap().runnable);
    }

    #[test]
    fn validate_agent_all_modes_event_only_agent() {
        let agent = make_agent("pr-reviewer", None, true);
        let config = test_config(vec![agent.clone()]);
        let (_report, mode_results) = validate_agent_all_modes(&config, &agent);
        assert!(mode_results.contains_key(&TriggerMode::PullRequest));
        assert!(mode_results.contains_key(&TriggerMode::Push));
        assert!(mode_results.contains_key(&TriggerMode::Local));
    }
}