klasp-core 0.2.2

Public traits, types, and protocol for klasp — block AI coding agents on the same quality gates humans hit at git commit.
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
//! `klasp.toml` config — `version = 1` schema.
//!
//! Design: [docs/design.md §3.5]. The `version` field is enforced at parse
//! time so v2 configs reject loudly with an upgrade message rather than
//! silently dropping unknown sections. `CheckSourceConfig` is
//! `#[serde(tag = "type")]`-tagged so unknown source types also fail at
//! parse time.

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::error::{KlaspError, Result};
use crate::verdict::VerdictPolicy;

/// Config schema version. Bumps only when the TOML syntax breaks; new
/// optional fields do not bump it.
pub const CONFIG_VERSION: u32 = 1;

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ConfigV1 {
    /// Schema version. Must equal [`CONFIG_VERSION`]; mismatches fail with
    /// [`KlaspError::ConfigVersion`].
    pub version: u32,

    pub gate: GateConfig,

    #[serde(default)]
    pub checks: Vec<CheckConfig>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GateConfig {
    #[serde(default)]
    pub agents: Vec<String>,

    #[serde(default)]
    pub policy: VerdictPolicy,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CheckConfig {
    pub name: String,

    #[serde(default)]
    pub triggers: Vec<TriggerConfig>,

    pub source: CheckSourceConfig,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_secs: Option<u64>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct TriggerConfig {
    pub on: Vec<String>,
}

/// Tagged enum: TOML `type = "shell"` selects the `Shell` variant,
/// `type = "pre_commit"` selects the v0.2 W4 `PreCommit` named recipe,
/// `type = "fallow"` selects the v0.2 W5 `Fallow` named recipe,
/// `type = "pytest"` selects the v0.2 W6 `Pytest` named recipe,
/// `type = "cargo"` selects the v0.2 W6 `Cargo` named recipe.
/// Unknown `type` values fail at parse time — that's the v0.1 contract
/// for additive forwards-incompatibility, preserved as new recipes land.
///
/// **Adding new variants is the v0.2 named-recipe extension point** —
/// each new recipe is a sibling variant here plus a paired `CheckSource`
/// impl in the binary crate. Field shape is per-recipe: `Shell` carries
/// a free-form `command`, `PreCommit` carries optional `hook_stage` /
/// `config_path` fields, `Fallow` carries optional `config_path` /
/// `base` fields, `Pytest` carries optional `extra_args`, `config_path`,
/// and `junit_xml` toggle, `Cargo` requires a `subcommand` plus optional
/// `extra_args` / `package`. `verdict_path` is deferred — see
/// [docs/design.md §14] for the explicit scope note.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum CheckSourceConfig {
    Shell {
        command: String,
    },
    PreCommit {
        /// Maps to `pre-commit run --hook-stage <stage>`. `None` defaults
        /// to `"pre-commit"` at run time, matching pre-commit's own
        /// default when invoked from a `.git/hooks/pre-commit` shim.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        hook_stage: Option<String>,

        /// Maps to `pre-commit run -c <config_path>`. `None` lets
        /// pre-commit fall back to its own default discovery
        /// (`.pre-commit-config.yaml` at the repo root).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        config_path: Option<PathBuf>,
    },
    Fallow {
        /// Maps to `fallow audit -c <config_path>`. `None` lets fallow
        /// fall back to its own discovery (`.fallowrc.json`,
        /// `.fallowrc.jsonc`, or `fallow.toml` at the repo root).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        config_path: Option<PathBuf>,

        /// Maps to `fallow audit --base <ref>`. `None` falls back to
        /// `${KLASP_BASE_REF}` at run time, which the gate runtime
        /// resolves to the merge-base of `HEAD` against the upstream
        /// tracking branch. Set this only when the diff-base for the
        /// audit should diverge from the gate's resolved base ref —
        /// e.g. auditing against a fixed mainline for a long-lived
        /// release branch.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        base: Option<String>,
    },
    Pytest {
        /// Free-form extra args appended after pytest's own flags.
        /// e.g. `"-x -q tests/integration"`. `None` runs pytest with
        /// its own defaults.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        extra_args: Option<String>,

        /// Maps to `pytest -c <config_path>`. `None` lets pytest fall
        /// back to its own discovery (`pytest.ini`, `pyproject.toml`,
        /// `tox.ini`, …).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        config_path: Option<PathBuf>,

        /// When `true`, the recipe asks pytest to write a JUnit XML
        /// report and parses it for per-failure findings. When `false`
        /// (default), the recipe falls back to a generic count-based
        /// finding from pytest's exit code alone.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        junit_xml: Option<bool>,
    },
    Cargo {
        /// Required: which `cargo <subcommand>` to dispatch. Accepted
        /// values are `"check"`, `"clippy"`, `"test"`, `"build"`. Any
        /// other value fails at run time with an unparseable detail
        /// (the schema doesn't enum-restrict this so a future cargo
        /// subcommand can be tried by an adventurous user without a
        /// klasp release).
        subcommand: String,

        /// Free-form extra args appended after cargo's own flags
        /// (e.g. `"--all-features"`). `None` runs cargo with its
        /// own defaults.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        extra_args: Option<String>,

        /// Maps to `cargo <sub> -p <package>`. `None` runs across
        /// the workspace via `--workspace`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        package: Option<String>,
    },
}

impl ConfigV1 {
    /// Resolve and load `klasp.toml`. The lookup order matches design §14:
    /// `$CLAUDE_PROJECT_DIR` first (set by Claude Code), then the supplied
    /// `repo_root`. The first existing file wins; any parse error
    /// short-circuits.
    pub fn load(repo_root: &Path) -> Result<Self> {
        let mut searched = Vec::new();

        if let Ok(claude_dir) = std::env::var("CLAUDE_PROJECT_DIR") {
            let candidate = PathBuf::from(claude_dir).join("klasp.toml");
            if candidate.is_file() {
                return Self::from_file(&candidate);
            }
            searched.push(candidate);
        }

        let candidate = repo_root.join("klasp.toml");
        if candidate.is_file() {
            return Self::from_file(&candidate);
        }
        searched.push(candidate);

        Err(KlaspError::ConfigNotFound { searched })
    }

    /// Read and parse a specific TOML file. Public so tests and callers
    /// that already know the path can skip the lookup logic.
    pub fn from_file(path: &Path) -> Result<Self> {
        let bytes = std::fs::read_to_string(path).map_err(|source| KlaspError::Io {
            path: path.to_path_buf(),
            source,
        })?;
        Self::parse(&bytes)
    }

    /// Parse from raw TOML. Validates the `version` field as part of the
    /// parse step so caller code never sees a malformed `ConfigV1`.
    pub fn parse(s: &str) -> Result<Self> {
        let config: ConfigV1 = toml::from_str(s)?;
        if config.version != CONFIG_VERSION {
            return Err(KlaspError::ConfigVersion {
                found: config.version,
                supported: CONFIG_VERSION,
            });
        }
        Ok(config)
    }
}

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

    #[test]
    fn parses_minimal_config() {
        let toml = r#"
            version = 1

            [gate]
            agents = ["claude_code"]
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        assert_eq!(config.version, 1);
        assert_eq!(config.gate.agents, vec!["claude_code"]);
        assert_eq!(config.gate.policy, VerdictPolicy::AnyFail);
        assert!(config.checks.is_empty());
    }

    #[test]
    fn parses_full_config() {
        let toml = r#"
            version = 1

            [gate]
            agents = ["claude_code"]
            policy = "any_fail"

            [[checks]]
            name = "ruff"
            triggers = [{ on = ["commit"] }]
            timeout_secs = 60
            [checks.source]
            type = "shell"
            command = "ruff check ."

            [[checks]]
            name = "pytest"
            triggers = [{ on = ["push"] }]
            [checks.source]
            type = "shell"
            command = "pytest -q"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        assert_eq!(config.checks.len(), 2);
        assert_eq!(config.checks[0].name, "ruff");
        assert_eq!(config.checks[0].timeout_secs, Some(60));
        assert!(matches!(
            &config.checks[0].source,
            CheckSourceConfig::Shell { command } if command == "ruff check ."
        ));
        assert_eq!(config.checks[0].triggers[0].on, vec!["commit"]);
        assert!(config.checks[1].timeout_secs.is_none());
    }

    #[test]
    fn rejects_wrong_version() {
        let toml = r#"
            version = 2
            [gate]
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        match err {
            KlaspError::ConfigVersion { found, supported } => {
                assert_eq!(found, 2);
                assert_eq!(supported, CONFIG_VERSION);
            }
            other => panic!("expected ConfigVersion, got {other:?}"),
        }
    }

    #[test]
    fn rejects_missing_version() {
        let toml = r#"
            [gate]
            agents = []
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn rejects_missing_gate() {
        let toml = "version = 1";
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn rejects_unknown_source_type() {
        // `pre_commit` was an unknown recipe in v0.1, `fallow` was unknown
        // in v0.2 W4, `pytest` / `cargo` were unknown in W5; all are
        // first-class variants now. Pivot to a recipe that hasn't landed
        // yet (placeholder for whichever recipe lands next post-W6) so
        // the additive-forwards-incompat contract keeps its regression
        // coverage.
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "future-recipe"
            [checks.source]
            type = "future_recipe_not_yet_landed"
            command = "noop"
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn rejects_unknown_field_on_pre_commit_variant() {
        // A typo like `hook_stages` (plural) on the `pre_commit` variant
        // would silently parse as the default `None` without
        // `#[serde(deny_unknown_fields)]` on the tagged enum — defaulting
        // to `--hook-stage pre-commit` regardless of the user's intent.
        // Locks in the variant-level footgun closure so a future serde
        // refactor (e.g. `untagged`) doesn't silently regress it.
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "typo-test"
            [checks.source]
            type = "pre_commit"
            hook_stages = "pre-push"
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn parses_pre_commit_recipe_minimal() {
        // Bare `type = "pre_commit"` with no extra fields: both optional
        // fields default to `None` and the recipe applies its own
        // run-time defaults (`hook_stage = "pre-commit"`,
        // `config_path = ".pre-commit-config.yaml"`).
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "lint"
            [checks.source]
            type = "pre_commit"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        assert_eq!(config.checks.len(), 1);
        match &config.checks[0].source {
            CheckSourceConfig::PreCommit {
                hook_stage,
                config_path,
            } => {
                assert!(hook_stage.is_none());
                assert!(config_path.is_none());
            }
            other => panic!("expected PreCommit, got {other:?}"),
        }
    }

    #[test]
    fn parses_pre_commit_recipe_with_fields() {
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "lint"
            [checks.source]
            type = "pre_commit"
            hook_stage = "pre-push"
            config_path = "tools/pre-commit.yaml"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        match &config.checks[0].source {
            CheckSourceConfig::PreCommit {
                hook_stage,
                config_path,
            } => {
                assert_eq!(hook_stage.as_deref(), Some("pre-push"));
                assert_eq!(
                    config_path
                        .as_ref()
                        .map(|p| p.to_string_lossy().into_owned()),
                    Some("tools/pre-commit.yaml".to_string())
                );
            }
            other => panic!("expected PreCommit, got {other:?}"),
        }
    }

    #[test]
    fn parses_fallow_recipe_minimal() {
        // Bare `type = "fallow"` with no extra fields: both optional
        // fields default to `None` and the recipe applies its own
        // run-time defaults (`base = "${KLASP_BASE_REF}"`,
        // `config_path = <fallow's own discovery>`).
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "audit"
            [checks.source]
            type = "fallow"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        assert_eq!(config.checks.len(), 1);
        match &config.checks[0].source {
            CheckSourceConfig::Fallow { config_path, base } => {
                assert!(config_path.is_none());
                assert!(base.is_none());
            }
            other => panic!("expected Fallow, got {other:?}"),
        }
    }

    #[test]
    fn parses_fallow_recipe_with_fields() {
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "audit"
            [checks.source]
            type = "fallow"
            config_path = "tools/.fallowrc.json"
            base = "origin/main"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        match &config.checks[0].source {
            CheckSourceConfig::Fallow { config_path, base } => {
                assert_eq!(
                    config_path
                        .as_ref()
                        .map(|p| p.to_string_lossy().into_owned()),
                    Some("tools/.fallowrc.json".to_string())
                );
                assert_eq!(base.as_deref(), Some("origin/main"));
            }
            other => panic!("expected Fallow, got {other:?}"),
        }
    }

    #[test]
    fn rejects_unknown_field_on_fallow_variant() {
        // Same footgun closure as the pre_commit variant: a typo like
        // `bases` (plural) on the `fallow` variant must fail at parse
        // time rather than silently default to `None`.
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "audit"
            [checks.source]
            type = "fallow"
            bases = "main"
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn parses_pytest_recipe_minimal() {
        // Bare `type = "pytest"` with no extra fields: every optional
        // field defaults to `None` and the recipe applies its own
        // run-time defaults.
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "tests"
            [checks.source]
            type = "pytest"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        assert_eq!(config.checks.len(), 1);
        match &config.checks[0].source {
            CheckSourceConfig::Pytest {
                extra_args,
                config_path,
                junit_xml,
            } => {
                assert!(extra_args.is_none());
                assert!(config_path.is_none());
                assert!(junit_xml.is_none());
            }
            other => panic!("expected Pytest, got {other:?}"),
        }
    }

    #[test]
    fn parses_pytest_recipe_with_fields() {
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "tests"
            [checks.source]
            type = "pytest"
            extra_args = "-x -q tests/"
            config_path = "pytest.ini"
            junit_xml = true
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        match &config.checks[0].source {
            CheckSourceConfig::Pytest {
                extra_args,
                config_path,
                junit_xml,
            } => {
                assert_eq!(extra_args.as_deref(), Some("-x -q tests/"));
                assert_eq!(
                    config_path
                        .as_ref()
                        .map(|p| p.to_string_lossy().into_owned()),
                    Some("pytest.ini".to_string())
                );
                assert_eq!(*junit_xml, Some(true));
            }
            other => panic!("expected Pytest, got {other:?}"),
        }
    }

    #[test]
    fn rejects_unknown_field_on_pytest_variant() {
        // Same footgun closure as the pre_commit / fallow variants: a
        // typo on the `pytest` variant must fail at parse time.
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "tests"
            [checks.source]
            type = "pytest"
            extra_arg = "-x"
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn parses_cargo_recipe_minimal() {
        // `type = "cargo"` requires `subcommand`; the other fields
        // default to `None` and the recipe runs across the workspace.
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "build"
            [checks.source]
            type = "cargo"
            subcommand = "check"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        assert_eq!(config.checks.len(), 1);
        match &config.checks[0].source {
            CheckSourceConfig::Cargo {
                subcommand,
                extra_args,
                package,
            } => {
                assert_eq!(subcommand, "check");
                assert!(extra_args.is_none());
                assert!(package.is_none());
            }
            other => panic!("expected Cargo, got {other:?}"),
        }
    }

    #[test]
    fn parses_cargo_recipe_with_fields() {
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "lint"
            [checks.source]
            type = "cargo"
            subcommand = "clippy"
            extra_args = "--all-features -- -D warnings"
            package = "klasp-core"
        "#;
        let config = ConfigV1::parse(toml).expect("should parse");
        match &config.checks[0].source {
            CheckSourceConfig::Cargo {
                subcommand,
                extra_args,
                package,
            } => {
                assert_eq!(subcommand, "clippy");
                assert_eq!(extra_args.as_deref(), Some("--all-features -- -D warnings"));
                assert_eq!(package.as_deref(), Some("klasp-core"));
            }
            other => panic!("expected Cargo, got {other:?}"),
        }
    }

    #[test]
    fn rejects_cargo_recipe_missing_subcommand() {
        // `subcommand` is required (no `#[serde(default)]`), so a
        // bare `type = "cargo"` must fail at parse time.
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "build"
            [checks.source]
            type = "cargo"
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn rejects_unknown_field_on_cargo_variant() {
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            name = "build"
            [checks.source]
            type = "cargo"
            subcommand = "check"
            packages = "klasp-core"
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }

    #[test]
    fn rejects_missing_check_name() {
        let toml = r#"
            version = 1
            [gate]

            [[checks]]
            [checks.source]
            type = "shell"
            command = "echo"
        "#;
        let err = ConfigV1::parse(toml).expect_err("should reject");
        assert!(matches!(err, KlaspError::ConfigParse(_)));
    }
}