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
//! `klasp doctor` — diagnose the local install.
//!
//! Runs four sequential check groups, prints `OK`/`WARN`/`FAIL`/`INFO`
//! lines on stdout (6-char prefix gutter), prints an aggregate summary
//! to stderr, and exits 0 iff zero `FAIL`. `WARN` is non-fatal. References
//! [docs/design.md §5] and [`klasp_core::AgentSurface`].
//!
//! Check order:
//!   1. **Config** — `klasp.toml` exists and parses as `version = 1`.
//!   2. **Hook script** — for each surface declared in `[gate].agents`,
//!      the file at `surface.hook_path()` is byte-equal to a fresh
//!      `surface.render_hook_script()` at the binary's current
//!      `GATE_SCHEMA_VERSION`. Catches schema drift between binary and
//!      installed hook (the exact case the gate runtime fail-opens on).
//!   3. **Settings** — for each surface declared in `[gate].agents`,
//!      `surface.settings_path()` exists, parses as JSON, and contains
//!      klasp's `PreToolUse[Bash]` hook entry.
//!   4. **PATH** — for each `config.checks[*].source.Shell { command }`,
//!      the leading executable resolves via `which::which`. WARN-only —
//!      missing dev tools shouldn't fail doctor.
//!
//! Surfaces NOT listed in `[gate].agents` are skipped with an INFO line.
//! If `AGENTS.md` is present but `"codex"` is not in `[gate].agents`, an
//! INFO suggestion is emitted (not a FAIL) so the user knows they can
//! opt in with `klasp install --agent codex`.

use std::path::Path;
use std::process::ExitCode;

use klasp_core::{
    AgentSurface, CheckSourceConfig, ConfigV1, InstallContext, KlaspError, GATE_SCHEMA_VERSION,
};
use serde_json::Value;

use crate::cli::DoctorArgs;
use crate::cmd::install::resolve_repo_root;
use crate::registry::SurfaceRegistry;

/// FAIL/WARN counters for the aggregate summary. `INFO` lines do not count.
pub(crate) struct Counters {
    pub(crate) fails: usize,
    pub(crate) warns: usize,
}

impl Counters {
    pub(crate) fn new() -> Self {
        Self { fails: 0, warns: 0 }
    }

    pub(crate) fn ok(&self, msg: &str) {
        println!("OK    {msg}");
    }

    pub(crate) fn warn(&mut self, msg: &str) {
        self.warns += 1;
        println!("WARN  {msg}");
    }

    pub(crate) fn fail(&mut self, msg: &str) {
        self.fails += 1;
        println!("FAIL  {msg}");
    }

    pub(crate) fn info(msg: &str) {
        println!("INFO  {msg}");
    }
}

pub fn run(_args: &DoctorArgs) -> ExitCode {
    let repo_root = match resolve_repo_root(None) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("klasp doctor: {e:#}");
            return ExitCode::FAILURE;
        }
    };

    let mut c = Counters::new();

    let config = check_config(&repo_root, &mut c);
    check_surfaces(&repo_root, config.as_ref(), &mut c);
    if let Some(cfg) = config {
        check_paths(&cfg, &mut c);
    }

    if c.fails > 0 || c.warns > 0 {
        eprintln!("doctor: {} FAIL, {} WARN", c.fails, c.warns);
    } else {
        eprintln!("doctor: all checks passed");
    }

    if c.fails > 0 {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// Check 1 — load `klasp.toml`. Returns the parsed config so check 4 can
/// iterate `config.checks`. `None` on any load failure (the corresponding
/// FAIL line has already been emitted).
pub(crate) fn check_config(repo_root: &Path, c: &mut Counters) -> Option<ConfigV1> {
    match ConfigV1::load(repo_root) {
        Ok(cfg) => {
            c.ok("config: klasp.toml loaded OK");
            Some(cfg)
        }
        Err(KlaspError::ConfigNotFound { searched }) => {
            let paths: Vec<String> = searched.iter().map(|p| p.display().to_string()).collect();
            c.fail(&format!(
                "config: klasp.toml not found (searched: {})",
                paths.join(", ")
            ));
            None
        }
        Err(KlaspError::ConfigVersion { found, supported }) => {
            c.fail(&format!(
                "config: version mismatch — file declares version = {found}, but this klasp understands version = {supported}"
            ));
            None
        }
        Err(KlaspError::ConfigParse(e)) => {
            c.fail(&format!("config: klasp.toml parse error: {e}"));
            None
        }
        Err(KlaspError::Io { path, source }) => {
            c.fail(&format!(
                "config: I/O error reading {}: {source}",
                path.display()
            ));
            None
        }
        Err(
            e @ (KlaspError::Protocol(_) | KlaspError::Install(_) | KlaspError::CheckSource(_)),
        ) => {
            c.fail(&format!("config: unexpected error: {e}"));
            None
        }
    }
}

/// Checks 2 & 3 — for each surface declared in `[gate].agents`, run hook +
/// settings checks. Surfaces not in the declared list are skipped with an
/// INFO line. If `config` is `None` (config load failed), falls back to the
/// detect-based path so surfaces still produce actionable output.
///
/// Additionally, if `AGENTS.md` is present but `"codex"` is not declared in
/// `[gate].agents`, emit an INFO suggestion (non-fatal) so users learn they
/// can enable codex gate coverage.
pub(crate) fn check_surfaces(repo_root: &Path, config: Option<&ConfigV1>, c: &mut Counters) {
    let registry = SurfaceRegistry::default();
    let mut active = 0usize;

    let declared: Option<&[String]> = config.map(|cfg| cfg.gate.agents.as_slice());

    for surface in registry.iter() {
        let agent_id = surface.agent_id();
        let is_declared = match declared {
            // Config loaded: honour [gate].agents exclusively.
            Some(agents) => agents.iter().any(|a| a == agent_id),
            // Config failed to load: fall back to filesystem detection so
            // the user still gets actionable output for installed surfaces.
            None => surface.detect(repo_root),
        };

        if !is_declared {
            Counters::info(&format!("{agent_id}: not in [gate].agents, skipping"));
            continue;
        }
        active += 1;
        check_hook(repo_root, surface, c);
        check_settings(repo_root, surface, c);
    }

    if active == 0 {
        c.warn(
            "no agent surfaces declared in [gate].agents; run `klasp install --force` if needed",
        );
    }

    // Advisory: AGENTS.md present but codex not declared → INFO suggestion.
    let codex_declared = declared
        .map(|agents| agents.iter().any(|a| a == "codex"))
        .unwrap_or(false);
    if !codex_declared && repo_root.join("AGENTS.md").is_file() {
        Counters::info(
            "AGENTS.md present but \"codex\" not in [gate].agents \
             — run `klasp install --agent codex` to enable codex gate coverage",
        );
    }
}

/// Check 2 — byte-equality of the on-disk hook against a fresh re-render at
/// the binary's `GATE_SCHEMA_VERSION`. A mismatch means the binary was
/// upgraded since the last `klasp install` (the gate runtime would
/// fail-open in this state).
fn check_hook(repo_root: &Path, surface: &dyn AgentSurface, c: &mut Counters) {
    let agent_id = surface.agent_id();
    let hook_path = surface.hook_path(repo_root);

    let actual = match std::fs::read_to_string(&hook_path) {
        Ok(s) => s,
        Err(_) => {
            c.fail(&format!(
                "hook[{agent_id}]: {} not found; re-run `klasp install`",
                hook_path.display()
            ));
            return;
        }
    };

    let ctx = InstallContext {
        repo_root: repo_root.to_path_buf(),
        dry_run: false,
        force: false,
        schema_version: GATE_SCHEMA_VERSION,
    };
    let expected = surface.render_hook_script(&ctx);

    if actual == expected {
        c.ok(&format!(
            "hook[{agent_id}]: current (schema v{GATE_SCHEMA_VERSION})"
        ));
    } else {
        c.fail(&format!(
            "hook[{agent_id}]: schema drift detected (re-run `klasp install`)"
        ));
    }
}

/// Check 3 — settings JSON exists, parses, and contains klasp's
/// `PreToolUse[Bash]` entry.
///
/// JSON-shaped only — the Codex surface's `settings_path` points at an
/// `AGENTS.md` markdown file with no JSON inside. Doctor's W3 contract is
/// "don't FAIL on a healthy Codex install"; v0.3 will add a typed
/// per-surface health check on the trait so this special-case can go away.
fn check_settings(repo_root: &Path, surface: &dyn AgentSurface, c: &mut Counters) {
    let agent_id = surface.agent_id();
    if agent_id != klasp_agents_claude::ClaudeCodeSurface::AGENT_ID {
        // Non-Claude surfaces have their own format (e.g. AGENTS.md
        // managed-block for Codex). The hook-script byte-equality check
        // run by `check_hook` is the surface-agnostic health signal; the
        // settings-parse logic below is Claude-specific.
        return;
    }
    let settings_path = surface.settings_path(repo_root);

    let raw = match std::fs::read_to_string(&settings_path) {
        Ok(s) => s,
        Err(_) => {
            c.fail(&format!(
                "settings[{agent_id}]: {} not found; re-run `klasp install`",
                settings_path.display()
            ));
            return;
        }
    };

    let root: Value = match serde_json::from_str(&raw) {
        Ok(v) => v,
        Err(e) => {
            c.fail(&format!(
                "settings[{agent_id}]: failed to parse {} as JSON: {e}",
                settings_path.display()
            ));
            return;
        }
    };

    let hook_command = klasp_agents_claude::ClaudeCodeSurface::HOOK_COMMAND;
    let has_entry = root
        .get("hooks")
        .and_then(|h| h.get("PreToolUse"))
        .and_then(Value::as_array)
        .is_some_and(|arr| {
            arr.iter().any(|matcher_entry| {
                matcher_entry.get("matcher").and_then(Value::as_str) == Some("Bash")
                    && matcher_entry
                        .get("hooks")
                        .and_then(Value::as_array)
                        .is_some_and(|inner| {
                            inner.iter().any(|hook| {
                                hook.get("command").and_then(Value::as_str) == Some(hook_command)
                            })
                        })
            })
        });

    if has_entry {
        c.ok(&format!("settings[{agent_id}]: hook entry present"));
    } else {
        c.fail(&format!(
            "settings[{agent_id}]: klasp hook entry missing; re-run `klasp install`"
        ));
    }
}

/// Check 4 — for each shell-flavoured check, resolve its leading executable
/// on PATH. WARN-only: a missing dev tool isn't an install bug, but the user
/// should know the gate will fail at runtime if invoked.
///
/// Recipe sources (v0.2 W4: `pre_commit`, W5: `fallow`) advertise a known
/// argv0 directly — the recipe knows which binary it shells out to even
/// before the gate renders the full command.
///
/// Covers issue #97 acceptance criterion #9: adopted `type = "pre_commit"`
/// checks surface a helpful WARN when `pre-commit` is missing from PATH,
/// including install guidance.
pub(crate) fn check_paths(config: &ConfigV1, c: &mut Counters) {
    if config.checks.is_empty() {
        Counters::info("no checks declared in klasp.toml — add [[checks]] blocks to gate agents");
        return;
    }

    for check in &config.checks {
        match &check.source {
            CheckSourceConfig::Shell { command } => match extract_argv0(command) {
                Some(argv0) => match which::which(argv0) {
                    Ok(_) => c.ok(&format!("path[{}]: `{argv0}` found in PATH", check.name)),
                    Err(_) => c.warn(&format!(
                        "path[{}]: `{argv0}` not found in PATH (command: `{command}`)",
                        check.name
                    )),
                },
                None => c.warn(&format!(
                    "path[{}]: could not determine executable from command `{command}`",
                    check.name
                )),
            },
            // Adopted `type = "pre_commit"` checks from `klasp init --adopt --mode mirror`
            // surface a detailed WARN with install guidance so users know exactly what to fix.
            CheckSourceConfig::PreCommit { .. } => match which::which("pre-commit") {
                Ok(_) => c.ok(&format!("path[{}]: `pre-commit` found in PATH", check.name)),
                Err(_) => c.warn(&format!(
                    "path[{}]: `pre-commit` not on PATH; check `{}` will fail to run \
                         — install with `pip install pre-commit` or via your package manager",
                    check.name, check.name
                )),
            },
            CheckSourceConfig::Fallow { .. } => check_recipe_argv0(c, &check.name, "fallow"),
            CheckSourceConfig::Pytest { .. } => check_recipe_argv0(c, &check.name, "pytest"),
            CheckSourceConfig::Cargo { .. } => check_recipe_argv0(c, &check.name, "cargo"),
            // Plugin sources: probe for `klasp-plugin-<name>` on PATH.
            CheckSourceConfig::Plugin { name, .. } => {
                let binary = format!("{}{}", klasp_core::KLASP_PLUGIN_BIN_PREFIX, name);
                match which::which(&binary) {
                    Ok(_) => c.ok(&format!("path[{}]: `{binary}` found in PATH", check.name)),
                    Err(_) => c.warn(&format!(
                        "path[{}]: plugin binary `{binary}` not found in PATH \
                         (install it to enable this check)",
                        check.name
                    )),
                }
            }
        }
    }
}

/// Per-recipe PATH probe. Centralised so a new recipe gets PATH coverage
/// in one line and the OK/WARN message format stays consistent.
fn check_recipe_argv0(c: &mut Counters, check_name: &str, argv0: &str) {
    match which::which(argv0) {
        Ok(_) => c.ok(&format!("path[{check_name}]: `{argv0}` found in PATH")),
        Err(_) => c.warn(&format!(
            "path[{check_name}]: `{argv0}` not found in PATH (recipe: {argv0})"
        )),
    }
}

/// Return the first non-`KEY=VALUE` whitespace-separated token from
/// `command`. Shell prefixes like `PYTHONPATH=. pytest` should resolve
/// `pytest`, not `PYTHONPATH=.`.
pub(crate) fn extract_argv0(command: &str) -> Option<&str> {
    command
        .split_ascii_whitespace()
        .find(|token| !token.contains('='))
}

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

    #[test]
    fn extract_argv0_simple_command() {
        assert_eq!(extract_argv0("ruff check ."), Some("ruff"));
    }

    #[test]
    fn extract_argv0_skips_env_prefix() {
        assert_eq!(extract_argv0("PYTHONPATH=. pytest -q"), Some("pytest"));
    }

    #[test]
    fn extract_argv0_skips_multiple_env_prefixes() {
        assert_eq!(
            extract_argv0("FOO=1 BAR=2 cargo test --workspace"),
            Some("cargo")
        );
    }

    #[test]
    fn extract_argv0_empty_command() {
        assert_eq!(extract_argv0(""), None);
    }

    #[test]
    fn extract_argv0_only_env_assignments() {
        assert_eq!(extract_argv0("FOO=1 BAR=2"), None);
    }
}