klasp 0.4.0

Block AI coding agents on the same quality gates your humans hit. See https://github.com/klasp-dev/klasp
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
//! Converts an [`AdoptionPlan`] into a `klasp.toml` and writes it atomically.
//!
//! The generated TOML is built by hand (rather than via `toml::to_string`)
//! so that we can preserve comments and control the exact section ordering.
//! After writing, the generated TOML is validated by round-tripping it through
//! `klasp_core::ConfigV1::parse` — any generator bug is caught before the
//! file reaches the user's repo.

use std::collections::HashMap;
use std::io;
use std::path::{Path, PathBuf};

use crate::adopt::plan::{AdoptionPlan, GateType, ProposedCheckSource};

/// Write (or overwrite) `<repo_root>/klasp.toml` from the adoption plan.
///
/// `agents` — when `Some`, the `[gate].agents` array is set to exactly those
/// values (narrowed to what the machine has installed). When `None`, the
/// three-agent fallback with an "edit me" comment is used.
///
/// Returns the absolute path of the written file on success.
///
/// # Errors
///
/// - `AlreadyExists` — `klasp.toml` already exists and `force` is `false`.
/// - `InvalidData`  — the generated TOML fails `ConfigV1::parse` (generator bug).
/// - Other `io::Error` variants propagated from filesystem operations.
pub fn write_klasp_toml(
    repo_root: &Path,
    plan: &AdoptionPlan,
    force: bool,
    agents: Option<&[String]>,
) -> io::Result<PathBuf> {
    let target = repo_root.join("klasp.toml");

    if target.exists() && !force {
        return Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "klasp.toml already exists; pass --force to overwrite",
        ));
    }

    let toml_content = generate_toml(plan, agents);

    // Safety-net: validate the generated TOML before touching the filesystem.
    klasp_core::ConfigV1::parse(&toml_content).map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("generated klasp.toml failed validation (generator bug): {e}"),
        )
    })?;

    crate::fs_util::atomic_write_text(&target, &toml_content)?;
    Ok(target)
}

/// Generate the TOML content for the given plan.
///
/// `agents` — when `Some`, use exactly that list. When `None`, use the
/// three-agent fallback with an "edit me" comment.
fn generate_toml(plan: &AdoptionPlan, agents: Option<&[String]>) -> String {
    let adopted_note = if plan.findings.is_empty() {
        "# adopted: no existing gates detected\n"
    } else {
        "# adopted: mirroring existing gates detected by `klasp init --adopt`\n"
    };

    let agents_line = match agents {
        Some(list) => {
            let items: Vec<String> = list
                .iter()
                .map(|a| format!("\"{}\"", escape_toml_string(a)))
                .collect();
            format!("agents = [{}]\n", items.join(", "))
        }
        None => {
            // Three-agent fallback — keep today's default with an "edit me" hint.
            "# Agent surfaces that klasp intercepts. Comment out any you don't use.\n\
             agents = [\"claude_code\", \"codex\", \"aider\"]\n"
                .to_string()
        }
    };

    let mut out = format!(
        "# klasp.toml — generated by `klasp init --adopt`\n\
         # Docs: https://github.com/klasp-dev/klasp\n\
         # Verify this install: run `klasp doctor`\n\
         {adopted_note}\
         \n\
         version = 1\n\
         \n\
         [gate]\n\
         {agents_line}\
         policy = \"any_fail\"\n"
    );

    // Track seen names so duplicate checks get a gate-type suffix.
    let mut seen_names: HashMap<String, usize> = HashMap::new();

    for finding in &plan.findings {
        for check in &finding.proposed_checks {
            // Determine the effective name: first occurrence keeps the bare
            // name; subsequent collisions get `<name>-<gate_suffix>`.
            let base = &check.name;
            let count = seen_names.entry(base.clone()).or_insert(0);
            let effective_name = if *count == 0 {
                base.clone()
            } else {
                format!("{}-{}", base, gate_suffix(&finding.gate_type))
            };
            *count += 1;

            out.push('\n');
            out.push_str("[[checks]]\n");
            out.push_str(&format!(
                "name = \"{}\"\n",
                escape_toml_string(&effective_name)
            ));

            let trigger_items: Vec<String> = check
                .triggers
                .iter()
                .map(|t| format!("\"{}\"", escape_toml_string(t.as_str())))
                .collect();
            out.push_str(&format!(
                "triggers = [{{ on = [{}] }}]\n",
                trigger_items.join(", ")
            ));

            out.push_str(&format!("timeout_secs = {}\n", check.timeout_secs));

            out.push_str("[checks.source]\n");
            match &check.source {
                ProposedCheckSource::PreCommit {
                    hook_stage,
                    config_path,
                } => {
                    out.push_str("type = \"pre_commit\"\n");
                    if let Some(stage) = hook_stage {
                        out.push_str(&format!("hook_stage = \"{}\"\n", escape_toml_string(stage)));
                    }
                    if let Some(path) = config_path {
                        out.push_str(&format!(
                            "config_path = \"{}\"\n",
                            escape_toml_string(&path.display().to_string())
                        ));
                    }
                }
                ProposedCheckSource::Shell { command } => {
                    out.push_str("type = \"shell\"\n");
                    out.push_str(&format!("command = \"{}\"\n", escape_toml_string(command)));
                }
            }
        }
    }

    out
}

/// Return a short suffix string for a gate type, used when two checks from
/// different detectors collide on the same base name (e.g. both Husky and
/// Lefthook emit a check named "lint").
///
/// The suffix is appended with a hyphen: `lint` → `lint-husky`.
fn gate_suffix(gate_type: &GateType) -> &'static str {
    match gate_type {
        GateType::PreCommitFramework => "pre-commit",
        GateType::Husky { .. } => "husky",
        GateType::Lefthook => "lefthook",
        GateType::PlainGitHook { .. } => "git-hook",
        GateType::LintStaged => "lint-staged",
        GateType::Tooling(_) => "tooling",
    }
}

/// Minimal TOML string escaping: backslash and double-quote characters only.
/// TOML basic strings require `"` → `\"` and `\` → `\\`.
fn escape_toml_string(s: &str) -> String {
    s.replace('\\', "\\\\").replace('"', "\\\"")
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;
    use crate::adopt::plan::{
        AdoptionPlan, ChainSupport, DetectedGate, GateType, HookStage, ProposedCheck,
        ProposedCheckSource, TriggerKind,
    };

    fn pre_commit_plan() -> AdoptionPlan {
        AdoptionPlan {
            findings: vec![DetectedGate {
                gate_type: GateType::PreCommitFramework,
                source_path: PathBuf::from(".pre-commit-config.yaml"),
                proposed_checks: vec![ProposedCheck {
                    name: "pre-commit".to_string(),
                    triggers: vec![TriggerKind::Commit],
                    timeout_secs: 120,
                    source: ProposedCheckSource::PreCommit {
                        hook_stage: None,
                        config_path: None,
                    },
                }],
                chain_support: ChainSupport::ManualOnly,
                manual_chain_instructions: None,
                warnings: vec![],
            }],
        }
    }

    fn shell_plan(command: &str) -> AdoptionPlan {
        AdoptionPlan {
            findings: vec![DetectedGate {
                gate_type: GateType::LintStaged,
                source_path: PathBuf::from("package.json"),
                proposed_checks: vec![ProposedCheck {
                    name: "lint-staged".to_string(),
                    triggers: vec![TriggerKind::Commit],
                    timeout_secs: 120,
                    source: ProposedCheckSource::Shell {
                        command: command.to_string(),
                    },
                }],
                chain_support: ChainSupport::ManualOnly,
                manual_chain_instructions: None,
                warnings: vec![],
            }],
        }
    }

    #[test]
    fn writes_and_parses_pre_commit_check() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = pre_commit_plan();
        let written = write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        assert_eq!(written, tmp.path().join("klasp.toml"));

        let content = std::fs::read_to_string(&written).unwrap();
        let config =
            klasp_core::ConfigV1::parse(&content).expect("generated TOML should parse cleanly");
        assert_eq!(config.checks.len(), 1);
        assert_eq!(config.checks[0].name, "pre-commit");
        assert!(matches!(
            &config.checks[0].source,
            klasp_core::CheckSourceConfig::PreCommit { hook_stage, config_path }
                if hook_stage.is_none() && config_path.is_none()
        ));
    }

    #[test]
    fn writes_and_parses_shell_check() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = shell_plan("pnpm exec lint-staged");
        let written = write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let content = std::fs::read_to_string(&written).unwrap();
        let config = klasp_core::ConfigV1::parse(&content).unwrap();
        assert_eq!(config.checks.len(), 1);
        assert!(matches!(
            &config.checks[0].source,
            klasp_core::CheckSourceConfig::Shell { command }
                if command == "pnpm exec lint-staged"
        ));
    }

    #[test]
    fn errors_if_file_exists_without_force() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = pre_commit_plan();
        write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let err = write_klasp_toml(tmp.path(), &plan, false, None).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
    }

    #[test]
    fn overwrites_with_force() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = pre_commit_plan();
        write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let result = write_klasp_toml(tmp.path(), &plan, true, None);
        assert!(result.is_ok(), "force should allow overwrite");
    }

    #[test]
    fn empty_plan_writes_minimal_scaffold() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = AdoptionPlan::default();
        let written = write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let content = std::fs::read_to_string(&written).unwrap();
        let config = klasp_core::ConfigV1::parse(&content).unwrap();
        assert!(config.checks.is_empty());
        assert!(content.contains("no existing gates detected"));
    }

    #[test]
    fn pre_commit_with_hook_stage_and_config_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = AdoptionPlan {
            findings: vec![DetectedGate {
                gate_type: GateType::PreCommitFramework,
                source_path: PathBuf::from(".pre-commit-config.yaml"),
                proposed_checks: vec![ProposedCheck {
                    name: "pre-commit-push".to_string(),
                    triggers: vec![TriggerKind::Push],
                    timeout_secs: 120,
                    source: ProposedCheckSource::PreCommit {
                        hook_stage: Some("pre-push".to_string()),
                        config_path: Some(PathBuf::from("tools/pre-commit.yaml")),
                    },
                }],
                chain_support: ChainSupport::ManualOnly,
                manual_chain_instructions: None,
                warnings: vec![],
            }],
        };
        let written = write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let content = std::fs::read_to_string(&written).unwrap();
        let config = klasp_core::ConfigV1::parse(&content).unwrap();
        assert_eq!(config.checks.len(), 1);
        match &config.checks[0].source {
            klasp_core::CheckSourceConfig::PreCommit {
                hook_stage,
                config_path,
            } => {
                assert_eq!(hook_stage.as_deref(), Some("pre-push"));
                assert_eq!(
                    config_path.as_ref().map(|p| p.display().to_string()),
                    Some("tools/pre-commit.yaml".to_string())
                );
            }
            other => panic!("expected PreCommit, got {other:?}"),
        }
    }

    #[test]
    fn toml_string_escaping_works() {
        assert_eq!(escape_toml_string(r#"foo"bar"#), r#"foo\"bar"#);
        assert_eq!(escape_toml_string(r"foo\bar"), r"foo\\bar");
        assert_eq!(escape_toml_string("simple"), "simple");
    }

    #[test]
    fn header_does_not_mention_mode_mirror() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = AdoptionPlan::default();
        let written = write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let content = std::fs::read_to_string(&written).unwrap();
        assert!(
            !content.contains("--mode mirror"),
            "header should not hardcode --mode mirror"
        );
    }

    /// AC: when `agents` is `Some(["claude_code"])`, the generated TOML uses
    /// exactly `agents = ["claude_code"]`.
    #[test]
    fn agents_some_uses_narrowed_list() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = AdoptionPlan::default();
        let agents = vec!["claude_code".to_string()];
        let written = write_klasp_toml(tmp.path(), &plan, false, Some(&agents)).unwrap();
        let content = std::fs::read_to_string(&written).unwrap();
        let config = klasp_core::ConfigV1::parse(&content).unwrap();
        assert_eq!(config.gate.agents, vec!["claude_code"]);
        // The "edit me" fallback comment must NOT appear.
        assert!(
            !content.contains("Comment out any you don't use"),
            "narrowed list should not include fallback comment"
        );
    }

    /// AC: when `agents` is `None`, the three-agent fallback with the
    /// "edit me" comment is used.
    #[test]
    fn agents_none_uses_three_agent_fallback_with_comment() {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = AdoptionPlan::default();
        let written = write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let content = std::fs::read_to_string(&written).unwrap();
        let config = klasp_core::ConfigV1::parse(&content).unwrap();
        assert_eq!(config.gate.agents, vec!["claude_code", "codex", "aider"]);
        assert!(
            content.contains("Comment out any you don't use"),
            "fallback should include edit-me comment"
        );
    }

    /// AC: duplicate check names across gate types get a suffix on the second.
    /// First "lint" stays "lint"; second "lint" (from a different gate) becomes
    /// "lint-<gate_suffix>".
    #[test]
    fn duplicate_name_suffix_on_collision() {
        let plan = AdoptionPlan {
            findings: vec![
                DetectedGate {
                    gate_type: GateType::Husky {
                        hook: HookStage::PreCommit,
                    },
                    source_path: PathBuf::from(".husky/pre-commit"),
                    proposed_checks: vec![ProposedCheck {
                        name: "lint".to_string(),
                        triggers: vec![TriggerKind::Commit],
                        timeout_secs: 60,
                        source: ProposedCheckSource::Shell {
                            command: "pnpm lint".to_string(),
                        },
                    }],
                    chain_support: ChainSupport::ManualOnly,
                    manual_chain_instructions: None,
                    warnings: vec![],
                },
                DetectedGate {
                    gate_type: GateType::Lefthook,
                    source_path: PathBuf::from("lefthook.yml"),
                    proposed_checks: vec![ProposedCheck {
                        name: "lint".to_string(), // same name — should get suffix
                        triggers: vec![TriggerKind::Commit],
                        timeout_secs: 60,
                        source: ProposedCheckSource::Shell {
                            command: "pnpm lint".to_string(),
                        },
                    }],
                    chain_support: ChainSupport::ManualOnly,
                    manual_chain_instructions: None,
                    warnings: vec![],
                },
            ],
        };

        let toml_str = generate_toml(&plan, None);

        // First occurrence: bare name.
        assert!(
            toml_str.contains("name = \"lint\"\n"),
            "first 'lint' should keep bare name:\n{toml_str}"
        );
        // Second occurrence: suffixed.
        assert!(
            toml_str.contains("name = \"lint-lefthook\"\n"),
            "second 'lint' (from Lefthook) should be 'lint-lefthook':\n{toml_str}"
        );

        // Verify round-trip parse.
        let tmp = tempfile::TempDir::new().unwrap();
        let written = write_klasp_toml(tmp.path(), &plan, false, None).unwrap();
        let config = klasp_core::ConfigV1::parse(&std::fs::read_to_string(&written).unwrap())
            .expect("collision-resolved TOML should parse cleanly");
        let names: Vec<&str> = config.checks.iter().map(|c| c.name.as_str()).collect();
        assert_eq!(names, vec!["lint", "lint-lefthook"]);
    }

    /// AC: first occurrence of a name is always kept bare — suffix only kicks
    /// in on collision, never preemptively.
    #[test]
    fn first_occurrence_keeps_bare_name() {
        let plan = AdoptionPlan {
            findings: vec![DetectedGate {
                gate_type: GateType::Husky {
                    hook: HookStage::PreCommit,
                },
                source_path: PathBuf::from(".husky/pre-commit"),
                proposed_checks: vec![ProposedCheck {
                    name: "lint".to_string(),
                    triggers: vec![TriggerKind::Commit],
                    timeout_secs: 60,
                    source: ProposedCheckSource::Shell {
                        command: "pnpm lint".to_string(),
                    },
                }],
                chain_support: ChainSupport::ManualOnly,
                manual_chain_instructions: None,
                warnings: vec![],
            }],
        };

        let toml_str = generate_toml(&plan, None);
        assert!(
            toml_str.contains("name = \"lint\"\n"),
            "single 'lint' must stay bare:\n{toml_str}"
        );
        assert!(
            !toml_str.contains("lint-husky"),
            "no suffix unless collision:\n{toml_str}"
        );
    }
}