agentlint-cli 0.1.0

A fast, local-first linter for AI coding-agent configuration
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
use std::path::Path;
use std::sync::LazyLock;

use regex::Regex;

use crate::analysis::{line_column, push};
use crate::project::{PackageManager, ProjectFacts};
use crate::scanner::SourceFile;
use crate::{Diagnostic, Severity};

static FENCE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?ms)^```(?:bash|sh|shell|zsh|fish|console)\s*\n(.*?)^```\s*$")
        .expect("valid shell fence regex")
});
static RUN_INLINE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?im)\b(?:run|execute|command)\s*:?[ \t]+`([^`\n]+)`")
        .expect("valid inline command regex")
});
static RUN_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?im)^\s*(?:run|execute)\s+((?:npm|pnpm|yarn|bun|cargo|pytest|python|go|git|docker|make|just|scripts/|\./)[^`\n.]*)",
    )
    .expect("valid prose command regex")
});
static PACKAGE_MANAGER_PROSE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)\b(?:always\s+|must\s+)?use\s+(npm|pnpm|yarn|bun)\b")
        .expect("valid package-manager instruction regex")
});
static DESTRUCTIVE_RM_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?:^|\s)(?:sudo\s+)?rm\s+-[^\n]*r[^\n]*f[^\n]*(?:/|\$home|~)")
        .expect("valid destructive rm regex")
});
static CURL_PIPE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"curl\b[^\n|]*\|\s*(?:sudo\s+)?(?:sh|bash)\b").expect("valid curl pipe regex")
});

#[derive(Debug)]
struct Command<'a> {
    text: &'a str,
    offset: usize,
}

pub fn check(
    root: &Path,
    file: &SourceFile,
    project: &ProjectFacts,
    diagnostics: &mut Vec<Diagnostic>,
) {
    check_package_manager_prose(file, project, diagnostics);
    for command in extract(&file.content) {
        check_danger(file, &command, diagnostics);
        check_package_manager(file, &command, project, diagnostics);
        check_package_script(file, &command, project, diagnostics);
        check_binary(root, file, &command, diagnostics);
        check_tooling(file, &command, project, diagnostics);
    }
}

fn check_package_manager_prose(
    file: &SourceFile,
    project: &ProjectFacts,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some(expected) = project.package_manager else {
        return;
    };
    for capture in PACKAGE_MANAGER_PROSE_RE.captures_iter(&file.content) {
        let Some(manager) = capture.get(1) else {
            continue;
        };
        if manager.as_str().eq_ignore_ascii_case(expected.command()) {
            continue;
        }
        let (line, column) = line_column(&file.content, manager.start());
        push(
            diagnostics,
            Diagnostic::new(
                "AGL601",
                Severity::Warning,
                &file.relative_path,
                format!(
                    "Repository uses {}, but this instruction requires {}.",
                    expected.command(),
                    manager.as_str().to_ascii_lowercase()
                ),
            )
            .at(line, column)
            .suggest(format!(
                "Use `{}` consistently with repository metadata.",
                expected.command()
            )),
        );
    }
}

fn extract(text: &str) -> Vec<Command<'_>> {
    let mut commands = Vec::new();
    for capture in FENCE_RE.captures_iter(text) {
        let Some(block) = capture.get(1) else {
            continue;
        };
        let mut offset = block.start();
        for line in block.as_str().lines() {
            let command = line.trim();
            let leading = line.len().saturating_sub(line.trim_start().len());
            if !command.is_empty() && !command.starts_with('#') && !command.starts_with('$') {
                commands.push(Command {
                    text: command,
                    offset: offset + leading,
                });
            } else if let Some(command) = command.strip_prefix("$ ") {
                commands.push(Command {
                    text: command,
                    offset: offset + leading + 2,
                });
            }
            offset += line.len() + 1;
        }
    }
    for capture in RUN_INLINE_RE.captures_iter(text) {
        if let Some(command) = capture.get(1) {
            commands.push(Command {
                text: command.as_str(),
                offset: command.start(),
            });
        }
    }
    for capture in RUN_LINE_RE.captures_iter(text) {
        if let Some(command) = capture.get(1) {
            commands.push(Command {
                text: command.as_str().trim(),
                offset: command.start(),
            });
        }
    }
    commands.sort_by_key(|command| command.offset);
    commands.dedup_by_key(|command| command.offset);
    commands
}

fn check_danger(file: &SourceFile, command: &Command<'_>, diagnostics: &mut Vec<Diagnostic>) {
    let lower = command.text.to_ascii_lowercase();
    let reason = if lower.contains("sudo rm -rf") || DESTRUCTIVE_RM_RE.is_match(&lower) {
        Some("Recursive forced deletion may permanently remove files outside the intended scope.")
    } else if lower.contains("git reset --hard") {
        Some("`git reset --hard` permanently discards uncommitted tracked changes.")
    } else if lower.contains("git clean -fdx") || lower.contains("git clean -xdf") {
        Some("`git clean -fdx` permanently deletes ignored and untracked files.")
    } else if CURL_PIPE_RE.is_match(&lower) {
        Some("Piping downloaded code directly to a shell bypasses review and integrity checks.")
    } else {
        None
    };
    if let Some(reason) = reason {
        let (line, column) = line_column(&file.content, command.offset);
        push(
            diagnostics,
            Diagnostic::new("AGL501", Severity::Warning, &file.relative_path, reason)
                .at(line, column)
                .reference(short_command(command.text))
                .suggest("Require explicit review or replace this with a narrowly scoped, recoverable command."),
        );
    }
}

fn check_package_manager(
    file: &SourceFile,
    command: &Command<'_>,
    project: &ProjectFacts,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let Some(expected) = project.package_manager else {
        return;
    };
    let Some(actual) = command_manager(command.text) else {
        return;
    };
    if actual == expected {
        return;
    }
    let (line, column) = line_column(&file.content, command.offset);
    push(
        diagnostics,
        Diagnostic::new(
            "AGL601",
            Severity::Warning,
            &file.relative_path,
            format!(
                "Repository uses {}, but this instruction invokes {}.",
                expected.command(),
                actual.command()
            ),
        )
        .at(line, column)
        .suggest(format!(
            "Use `{}` consistently with the repository lockfile and packageManager metadata.",
            expected.command()
        )),
    );
}

fn check_package_script(
    file: &SourceFile,
    command: &Command<'_>,
    project: &ProjectFacts,
    diagnostics: &mut Vec<Diagnostic>,
) {
    if project.package_scripts.is_empty() {
        return;
    }
    let Ok(words) = shell_words::split(command.text) else {
        return;
    };
    let script = match words.as_slice() {
        [manager, run, script, ..]
            if matches!(manager.as_str(), "npm" | "pnpm" | "yarn" | "bun") && run == "run" =>
        {
            Some(script)
        }
        [manager, script, ..]
            if matches!(manager.as_str(), "pnpm" | "yarn" | "bun") && !known_subcommand(script) =>
        {
            Some(script)
        }
        _ => None,
    };
    let Some(script) = script else { return };
    if project.package_scripts.contains(script) {
        return;
    }
    let (line, column) = line_column(&file.content, command.offset);
    let suggestion = project
        .package_scripts
        .iter()
        .filter_map(|candidate| {
            let distance = strsim::levenshtein(script, candidate);
            (distance <= 2).then_some((candidate, distance))
        })
        .min_by_key(|(_, distance)| *distance)
        .map(|(candidate, _)| format!("Did you mean script `{candidate}`?"));
    let mut diagnostic = Diagnostic::new(
        "AGL503",
        Severity::Error,
        &file.relative_path,
        format!("Package script `{script}` is not defined in package.json."),
    )
    .at(line, column)
    .reference(script);
    if let Some(suggestion) = suggestion {
        diagnostic = diagnostic.suggest(suggestion);
    }
    push(diagnostics, diagnostic);
}

fn check_binary(
    root: &Path,
    file: &SourceFile,
    command: &Command<'_>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let first_segment = command
        .text
        .split(['|', ';'])
        .next()
        .unwrap_or(command.text)
        .trim();
    let Ok(words) = shell_words::split(first_segment) else {
        return;
    };
    let Some(binary) = words
        .iter()
        .find(|word| !word.contains('=') && !word.starts_with('-'))
    else {
        return;
    };
    if is_shell_builtin(binary) || command_manager(binary).is_some() {
        return;
    }
    let is_path = binary.contains('/');
    if is_path
        && binary.starts_with("scripts/")
        && matches!(
            Path::new(binary)
                .extension()
                .and_then(|value| value.to_str()),
            Some("sh" | "fish" | "py")
        )
    {
        // The reference analyzer emits the more specific AGL203 for script paths.
        return;
    }
    let exists = if is_path {
        let path = Path::new(binary);
        (if path.is_absolute() {
            path.to_path_buf()
        } else {
            root.join(path)
        })
        .is_file()
    } else {
        which::which(binary).is_ok()
    };
    if exists {
        return;
    }
    let common = [
        "cargo", "rustup", "git", "docker", "pytest", "python", "python3", "make", "just", "npx",
        "npm", "pnpm", "yarn", "bun", "go", "node",
    ];
    let close = common
        .iter()
        .filter_map(|candidate| {
            let distance = strsim::levenshtein(binary, candidate);
            (distance <= 2).then_some((*candidate, distance))
        })
        .min_by_key(|(_, distance)| *distance);
    let (line, column) = line_column(&file.content, command.offset);
    let mut diagnostic = Diagnostic::new(
        "AGL502",
        Severity::Warning,
        &file.relative_path,
        format!("Command executable `{binary}` is not available locally."),
    )
    .at(line, column)
    .reference(binary);
    if let Some((candidate, _)) = close {
        diagnostic = diagnostic.suggest(format!("Did you mean `{candidate}`?"));
    }
    push(diagnostics, diagnostic);
}

fn check_tooling(
    file: &SourceFile,
    command: &Command<'_>,
    project: &ProjectFacts,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let lower = command.text.to_ascii_lowercase();
    let mismatch = if (lower.starts_with("pytest") || lower.starts_with("python -m pytest"))
        && !project.has_python
    {
        Some("Instruction requires pytest, but no Python project metadata was found.")
    } else if lower.starts_with("cargo ") && !project.has_rust {
        Some("Instruction requires Cargo, but no Cargo.toml was found.")
    } else if lower.starts_with("go test") && !project.has_go {
        Some("Instruction requires Go tests, but no go.mod was found.")
    } else {
        None
    };
    if let Some(message) = mismatch {
        let (line, column) = line_column(&file.content, command.offset);
        push(
            diagnostics,
            Diagnostic::new("AGL603", Severity::Warning, &file.relative_path, message)
                .at(line, column)
                .suggest("Remove stale tooling guidance or add the missing project metadata."),
        );
    }
}

fn command_manager(command: &str) -> Option<PackageManager> {
    let first = command.split_whitespace().next()?;
    match first {
        "npm" | "npx" => Some(PackageManager::Npm),
        "pnpm" | "pnpx" => Some(PackageManager::Pnpm),
        "yarn" => Some(PackageManager::Yarn),
        "bun" | "bunx" => Some(PackageManager::Bun),
        _ => None,
    }
}

fn known_subcommand(value: &str) -> bool {
    [
        "add", "install", "remove", "exec", "dlx", "create", "init", "publish", "pack", "config",
        "help", "version",
    ]
    .contains(&value)
}

fn is_shell_builtin(value: &str) -> bool {
    [
        "cd", "export", "set", "source", ".", "test", "if", "for", "while", "echo", "printf",
        "read", "true", "false",
    ]
    .contains(&value)
}

fn short_command(value: &str) -> String {
    if value.chars().count() <= 100 {
        value.to_owned()
    } else {
        format!("{}…", value.chars().take(100).collect::<String>())
    }
}

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

    #[test]
    fn shell_fences_are_extracted() {
        let text = "Run this:\n```bash\ncargo test\n# comment\n```";
        let commands = extract(text);
        assert_eq!(commands.len(), 1);
        assert_eq!(commands[0].text, "cargo test");
    }

    #[test]
    fn manager_is_detected() {
        assert_eq!(command_manager("pnpm test"), Some(PackageManager::Pnpm));
        assert_eq!(command_manager("cargo test"), None);
    }
}