clausura-core 1.0.6

Core library for Clausura — a CI-native agent for deterministic pipeline gating
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
/// Layered configuration loader for Clausura.
///
/// Configuration is loaded from three sources, in increasing priority:
/// 1. YAML config file (`.clausura.yaml` or `.clausura.yml`)
/// 2. CLI flag overrides
/// 3. Environment variable overrides
///
/// The API key is NEVER read from the YAML file — it must come from
/// a CLI flag or the `CLAUSURA_API_KEY` environment variable.
use crate::types::{
    AmbiguityPolicy, ConfigError, GateAction, GateRule, Severity, TaskContract, VendorConfig,
};
use serde::Deserialize;
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// Log output format.
#[derive(Debug, Clone, PartialEq, Default)]
pub enum LogFormat {
    #[default]
    Json,
    Pretty,
}

/// Resolved Clausura configuration after applying all layers.
#[derive(Debug, Clone)]
pub struct Config {
    /// Path to the YAML config file that was loaded, if any.
    pub config_path: Option<PathBuf>,
    /// The fully resolved task contract.
    pub task: TaskContract,
    /// API key (from CLI or env var only, never from YAML).
    pub api_key: Option<String>,
    /// Workspace root directory.
    pub workspace: PathBuf,
    /// Output path for SARIF results.
    pub output: PathBuf,
    /// Whether to resume from a previous checkpoint.
    pub resume: bool,
    /// Log output format.
    pub log_format: LogFormat,
}

// ---------------------------------------------------------------------------
// Raw YAML structures (file format)
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct YamlConfig {
    version: String,
    task: YamlTaskConfig,
}

#[derive(Debug, Deserialize)]
struct YamlTaskConfig {
    name: String,
    #[serde(default)]
    description: String,
    #[serde(default)]
    model: String,
    #[serde(default)]
    vendor: String,
    #[serde(default = "default_prompt")]
    prompt_template: String,
    #[serde(default)]
    tool_allowlist: Vec<String>,
    #[serde(default = "default_token_budget")]
    token_budget: u64,
    #[serde(default = "default_timeout")]
    timeout_secs: u64,
    #[serde(default = "default_ambiguity")]
    ambiguity_policy: String,
    #[serde(default)]
    gating: Vec<YamlGateRule>,
    #[serde(default = "default_max_iterations")]
    max_iterations: u32,
}

#[derive(Debug, Deserialize)]
struct YamlGateRule {
    rule: String,
    description: String,
    min_severity: String,
    max_findings: u32,
    action: String,
}

// ---------------------------------------------------------------------------
// Default helpers
// ---------------------------------------------------------------------------

fn default_prompt() -> String {
    "{{task_description}}".to_string()
}

fn default_token_budget() -> u64 {
    32000
}

fn default_timeout() -> u64 {
    300
}

fn default_max_iterations() -> u32 {
    10
}

fn default_ambiguity() -> String {
    "fail_closed".to_string()
}

// ---------------------------------------------------------------------------
// Parsing helpers
// ---------------------------------------------------------------------------

fn parse_severity(s: &str) -> Severity {
    match s.to_lowercase().as_str() {
        "error" => Severity::Error,
        "warning" => Severity::Warning,
        "info" => Severity::Info,
        "hint" => Severity::Hint,
        _ => Severity::Warning,
    }
}

fn parse_gate_action(s: &str) -> GateAction {
    match s.to_lowercase().as_str() {
        "fail" => GateAction::Fail,
        "warn" => GateAction::Warn,
        "ignore" => GateAction::Ignore,
        _ => GateAction::Warn,
    }
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

fn validate_yaml(yaml: &YamlConfig) -> Result<(), ConfigError> {
    if yaml.version.is_empty() {
        return Err(ConfigError::ValidationError("version is required".into()));
    }
    if yaml.version != "1" {
        return Err(ConfigError::ValidationError(format!(
            "Unsupported schema version '{}'. Expected '1'",
            yaml.version
        )));
    }
    if yaml.task.model.is_empty() && std::env::var("CLAUSURA_MODEL").is_err() {
        return Err(ConfigError::ValidationError(
            "task.model is required (or set CLAUSURA_MODEL)".into(),
        ));
    }
    if yaml.task.token_budget == 0 {
        return Err(ConfigError::ValidationError(
            "task.token_budget must be > 0".into(),
        ));
    }
    if yaml.task.timeout_secs == 0 {
        return Err(ConfigError::ValidationError(
            "task.timeout_secs must be > 0".into(),
        ));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Config file discovery
// ---------------------------------------------------------------------------

fn find_config_in_cwd() -> Option<PathBuf> {
    let cwd = std::env::current_dir().ok()?;
    for name in &[".clausura.yaml", ".clausura.yml"] {
        let path = cwd.join(name);
        if path.exists() {
            return Some(path);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Config loading
// ---------------------------------------------------------------------------

impl Config {
    /// Load configuration from a layered pipeline:
    ///
    /// 1. YAML file (auto-discovered or explicit path)
    /// 2. CLI flag overrides
    /// 3. Environment variable overrides
    ///
    /// Each subsequent layer overrides the previous one.
    #[allow(clippy::too_many_arguments)]
    pub fn load(
        config_path: Option<&Path>,
        cli_model: Option<&str>,
        cli_vendor: Option<&str>,
        cli_api_key: Option<&str>,
        cli_token_budget: Option<u64>,
        cli_timeout: Option<u64>,
        cli_max_iterations: Option<u32>,
        workspace: PathBuf,
        output: PathBuf,
        resume: bool,
        log_format: LogFormat,
    ) -> Result<Self, ConfigError> {
        // ---- Layer 1: YAML file ----
        let yaml_path = config_path
            .map(|p| p.to_path_buf())
            .or_else(find_config_in_cwd);

        let (yaml_task, config_path) = if let Some(ref path) = yaml_path {
            let content = std::fs::read_to_string(path)
                .map_err(|e| ConfigError::FileNotFound(format!("{}: {}", path.display(), e)))?;
            let yaml: YamlConfig = serde_yaml::from_str(&content)
                .map_err(|e| ConfigError::ParseError(format!("YAML error: {}", e)))?;
            validate_yaml(&yaml)?;
            (yaml.task, Some(path.clone()))
        } else {
            // No config file — use defaults; CLI / env vars will fill in.
            (
                YamlTaskConfig {
                    name: "default".into(),
                    description: String::new(),
                    model: String::new(),
                    vendor: String::new(),
                    prompt_template: default_prompt(),
                    tool_allowlist: vec![],
                    token_budget: default_token_budget(),
                    timeout_secs: default_timeout(),
                    ambiguity_policy: default_ambiguity(),
                    gating: vec![],
                    max_iterations: default_max_iterations(),
                },
                None,
            )
        };

        // ---- Layer 2: Environment variable + CLI overrides ----
        let model = std::env::var("CLAUSURA_MODEL")
            .ok()
            .or_else(|| cli_model.map(|m| m.to_string()))
            .unwrap_or_else(|| yaml_task.model.clone());

        let vendor_input = std::env::var("CLAUSURA_VENDOR")
            .ok()
            .or_else(|| cli_vendor.map(|v| v.to_string()))
            .unwrap_or_else(|| yaml_task.vendor.clone());
        let vendor = VendorConfig::from_name(&vendor_input);

        let token_budget = std::env::var("CLAUSURA_TOKEN_BUDGET")
            .ok()
            .and_then(|v| v.parse().ok())
            .or(cli_token_budget)
            .unwrap_or(yaml_task.token_budget);

        let timeout = std::env::var("CLAUSURA_TIMEOUT")
            .ok()
            .and_then(|v| v.parse().ok())
            .or(cli_timeout)
            .unwrap_or(yaml_task.timeout_secs);

        let max_iterations = std::env::var("CLAUSURA_MAX_ITERATIONS")
            .ok()
            .and_then(|v| v.parse().ok())
            .or(cli_max_iterations)
            .unwrap_or(yaml_task.max_iterations);

        // ---- Layer 3: Environment variable overrides ----
        let api_key = std::env::var("CLAUSURA_API_KEY")
            .ok()
            .or_else(|| cli_api_key.map(|s| s.to_string()));

        let ambiguity_str =
            std::env::var("CLAUSURA_AMBIGUITY_POLICY").unwrap_or(yaml_task.ambiguity_policy);

        let ambiguity_policy = match ambiguity_str.as_str() {
            "proceed_with_caution" => AmbiguityPolicy::ProceedWithCaution,
            _ => AmbiguityPolicy::FailClosed,
        };

        let gating_rules = yaml_task
            .gating
            .iter()
            .map(|g| GateRule {
                rule_id: g.rule.clone(),
                description: g.description.clone(),
                min_severity: parse_severity(&g.min_severity),
                max_findings: g.max_findings,
                action: parse_gate_action(&g.action),
            })
            .collect();

        Ok(Config {
            config_path,
            task: TaskContract {
                id: format!("task-{}", yaml_task.name.replace(' ', "-")),
                name: yaml_task.name,
                description: yaml_task.description,
                model,
                vendor,
                prompt_template: yaml_task.prompt_template,
                tool_allowlist: yaml_task.tool_allowlist,
                token_budget,
                timeout_secs: timeout,
                ambiguity_policy,
                gating_rules,
                max_iterations,
            },
            api_key,
            workspace,
            output,
            resume,
            log_format,
        })
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::VendorType;
    use std::io::Write;
    use std::sync::Mutex;
    use tempfile::NamedTempFile;

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    fn write_yaml(content: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().unwrap();
        write!(file, "{}", content).unwrap();
        file
    }

    #[test]
    fn test_valid_config_with_gating() {
        let _guard = ENV_LOCK.lock().unwrap();
        clean_env_vars();
        let yaml = r#"
version: "1"
task:
  name: code-review
  model: gpt-4o
  vendor: openai
  prompt_template: "Review this diff: {{diff}}"
  token_budget: 16000
  timeout_secs: 120
  ambiguity_policy: fail_closed
  gating:
    - rule: no-critical
      description: No critical errors
      min_severity: error
      max_findings: 0
      action: fail
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.name, "code-review");
        assert_eq!(config.task.model, "gpt-4o");
        assert_eq!(config.task.vendor, VendorConfig::openai());
        assert_eq!(config.task.token_budget, 16000);
        assert_eq!(config.task.timeout_secs, 120);
        assert_eq!(config.task.gating_rules.len(), 1);
        assert_eq!(config.task.gating_rules[0].rule_id, "no-critical");
        assert_eq!(config.task.gating_rules[0].min_severity, Severity::Error);
        assert_eq!(config.task.gating_rules[0].max_findings, 0);
        assert_eq!(config.task.gating_rules[0].action, GateAction::Fail);
    }

    #[test]
    fn test_cli_overrides_model() {
        let _guard = ENV_LOCK.lock().unwrap();
        let yaml = r#"
version: "1"
task:
  name: test
  model: gpt-3.5-turbo
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            Some("gpt-4o"), // CLI overrides model
            None,
            None,
            Some(32000), // CLI overrides token budget
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.model, "gpt-4o");
        assert_eq!(config.task.token_budget, 32000);
        // These should still come from YAML
        assert_eq!(config.task.vendor, VendorConfig::openai());
        assert_eq!(config.task.timeout_secs, 60);
    }

    #[test]
    fn test_env_overrides_cli_model() {
        let _guard = ENV_LOCK.lock().unwrap();
        clean_env_vars();
        unsafe { std::env::set_var("CLAUSURA_MODEL", "claude-sonnet") };
        let yaml = r#"
version: "1"
task:
  name: test
  model: gpt-3.5-turbo
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            Some("gpt-4o"), // CLI model — env should override this
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.model, "claude-sonnet"); // env wins over CLI
        unsafe { std::env::remove_var("CLAUSURA_MODEL") };
    }

    #[test]
    fn test_env_overrides_cli_all_fields() {
        let _guard = ENV_LOCK.lock().unwrap();
        clean_env_vars();
        unsafe {
            std::env::set_var("CLAUSURA_MODEL", "env-model");
            std::env::set_var("CLAUSURA_VENDOR", "deepseek");
            std::env::set_var("CLAUSURA_TOKEN_BUDGET", "99000");
            std::env::set_var("CLAUSURA_TIMEOUT", "600");
            std::env::set_var("CLAUSURA_API_KEY", "sk-env-key");
        }
        let yaml = r#"
version: "1"
task:
  name: test
  model: yaml-model
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            Some("cli-model"),
            Some("ollama"),
            Some("sk-cli-key"),
            Some(16000),
            None,
            Some(120),
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.model, "env-model");
        assert!(matches!(
            config.task.vendor.vendor_type,
            VendorType::OpenAiCompatible
        ));
        assert_eq!(config.task.token_budget, 99000);
        assert_eq!(config.task.timeout_secs, 600);
        assert_eq!(config.api_key, Some("sk-env-key".to_string()));
        unsafe {
            std::env::remove_var("CLAUSURA_MODEL");
            std::env::remove_var("CLAUSURA_VENDOR");
            std::env::remove_var("CLAUSURA_TOKEN_BUDGET");
            std::env::remove_var("CLAUSURA_TIMEOUT");
            std::env::remove_var("CLAUSURA_API_KEY");
        }
    }

    fn clean_env_vars() {
        unsafe {
            std::env::remove_var("CLAUSURA_API_KEY");
            std::env::remove_var("CLAUSURA_MODEL");
            std::env::remove_var("CLAUSURA_VENDOR");
            std::env::remove_var("CLAUSURA_TOKEN_BUDGET");
            std::env::remove_var("CLAUSURA_TIMEOUT");
            std::env::remove_var("CLAUSURA_AMBIGUITY_POLICY");
        }
    }

    #[test]
    fn test_env_override_api_key() {
        let _guard = ENV_LOCK.lock().unwrap();
        clean_env_vars();
        unsafe { std::env::set_var("CLAUSURA_API_KEY", "sk-test-key") };
        let config = Config::load(
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.api_key, Some("sk-test-key".to_string()));
        unsafe { std::env::remove_var("CLAUSURA_API_KEY") };
    }

    #[test]
    fn test_valid_config_minimal() {
        let _guard = ENV_LOCK.lock().unwrap();
        clean_env_vars();
        let yaml = r#"
version: "1"
task:
  name: quick-scan
  model: claude-3-5-sonnet
  vendor: anthropic
  token_budget: 64000
  timeout_secs: 600
  ambiguity_policy: proceed_with_caution
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "out.sarif".into(),
            true,
            LogFormat::Pretty,
        )
        .unwrap();
        assert_eq!(config.task.name, "quick-scan");
        assert_eq!(config.task.model, "claude-3-5-sonnet");
        assert_eq!(
            config.task.ambiguity_policy,
            AmbiguityPolicy::ProceedWithCaution
        );
        assert!(config.resume);
        assert_eq!(config.log_format, LogFormat::Pretty);
        assert_eq!(config.output, PathBuf::from("out.sarif"));
    }

    #[test]
    fn test_missing_model_is_error() {
        let _guard = ENV_LOCK.lock().unwrap();
        clean_env_vars();
        let yaml = r#"
version: "1"
task:
  name: test
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        // CLAUSURA_MODEL is also not set
        let result = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        );
        assert!(result.is_err());
        let err = result.unwrap_err();
        match err {
            ConfigError::ValidationError(msg) => {
                assert!(msg.contains("model"));
            }
            _ => panic!("expected ValidationError, got {:?}", err),
        }
    }

    #[test]
    fn test_zero_token_budget_is_error() {
        let yaml = r#"
version: "1"
task:
  name: test
  model: gpt-4o
  vendor: openai
  token_budget: 0
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let result = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_zero_timeout_is_error() {
        let yaml = r#"
version: "1"
task:
  name: test
  model: gpt-4o
  vendor: openai
  token_budget: 8000
  timeout_secs: 0
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let result = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_env_api_key_takes_precedence_over_cli() {
        let _guard = ENV_LOCK.lock().unwrap();
        clean_env_vars();
        unsafe {
            std::env::set_var("CLAUSURA_API_KEY", "sk-env-key");
        };
        let config = Config::load(
            None,
            None,
            None,
            Some("sk-cli-key"),
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.api_key, Some("sk-env-key".to_string()));
        unsafe { std::env::remove_var("CLAUSURA_API_KEY") };
    }

    #[test]
    fn test_empty_version_is_error() {
        let yaml = r#"
version: ""
task:
  name: test
  model: gpt-4o
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let result = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_max_iterations_from_yaml() {
        let yaml = r#"
version: "1"
task:
  name: test
  model: gpt-4o
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  max_iterations: 5
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.max_iterations, 5);
    }

    #[test]
    fn test_max_iterations_default_is_10() {
        let yaml = r#"
version: "1"
task:
  name: test
  model: gpt-4o
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.max_iterations, 10);
    }

    #[test]
    fn test_defaults_when_no_config_file() {
        let config = Config::load(
            None,
            Some("gpt-4o"),
            Some("openai"),
            Some("sk-test"),
            Some(16000),
            Some(120),
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.name, "default");
        assert_eq!(config.task.model, "gpt-4o");
        assert_eq!(config.task.vendor, VendorConfig::openai());
        assert_eq!(config.task.token_budget, 16000);
        assert_eq!(config.task.timeout_secs, 120);
        assert_eq!(config.task.prompt_template, "{{task_description}}");
        assert!(config.task.tool_allowlist.is_empty());
    }

    #[test]
    fn test_gate_rule_parsing() {
        let yaml = r#"
version: "1"
task:
  name: gate-test
  model: gpt-4o
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
  gating:
    - rule: no-errors
      description: Block on any error
      min_severity: error
      max_findings: 0
      action: fail
    - rule: warn-on-warnings
      description: Warn on warnings
      min_severity: warning
      max_findings: 5
      action: warn
    - rule: ignore-hints
      description: Ignore hints
      min_severity: hint
      max_findings: 100
      action: ignore
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.task.gating_rules.len(), 3);

        assert_eq!(config.task.gating_rules[0].rule_id, "no-errors");
        assert_eq!(config.task.gating_rules[0].min_severity, Severity::Error);
        assert_eq!(config.task.gating_rules[0].max_findings, 0);
        assert_eq!(config.task.gating_rules[0].action, GateAction::Fail);

        assert_eq!(config.task.gating_rules[1].rule_id, "warn-on-warnings");
        assert_eq!(config.task.gating_rules[1].min_severity, Severity::Warning);
        assert_eq!(config.task.gating_rules[1].max_findings, 5);
        assert_eq!(config.task.gating_rules[1].action, GateAction::Warn);

        assert_eq!(config.task.gating_rules[2].rule_id, "ignore-hints");
        assert_eq!(config.task.gating_rules[2].min_severity, Severity::Hint);
        assert_eq!(config.task.gating_rules[2].max_findings, 100);
        assert_eq!(config.task.gating_rules[2].action, GateAction::Ignore);
    }

    #[test]
    fn test_config_path_is_recorded() {
        let yaml = r#"
version: "1"
task:
  name: path-test
  model: gpt-4o
  vendor: openai
  token_budget: 8000
  timeout_secs: 60
  ambiguity_policy: fail_closed
"#;
        let file = write_yaml(yaml);
        let config = Config::load(
            Some(file.path()),
            None,
            None,
            None,
            None,
            None,
            None,
            std::env::current_dir().unwrap(),
            "output.sarif".into(),
            false,
            LogFormat::Json,
        )
        .unwrap();
        assert_eq!(config.config_path, Some(file.path().to_path_buf()));
    }
}