agent-kit 0.4.0

Toolkit for CLI tools integrating with AI agent loops
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
//! Shared audit primitives for cross-cutting validation.
//!
//! These functions apply to all content types and domain crates,
//! not just instruction files. Moved from `instruction-files` to
//! enable reuse across the agent toolkit.

use once_cell::sync::Lazy;
use regex::Regex;
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Configuration for instruction file discovery and auditing.
///
/// Different projects can customize behavior by providing different configs.
#[derive(Debug, Clone)]
pub struct AuditConfig {
    /// Project root marker files, checked in order.
    /// agent-doc uses many (Cargo.toml, package.json, etc.); corky uses only Cargo.toml.
    pub root_markers: Vec<&'static str>,

    /// Whether to include CLAUDE.md in root-level discovery and agent file checks.
    /// agent-doc: true, corky: false.
    pub include_claude_md: bool,

    /// Source file extensions to check for staleness comparison.
    /// agent-doc: broad (rs, ts, py, etc.); corky: just "rs".
    pub source_extensions: Vec<&'static str>,

    /// Source directories to scan for staleness.
    /// agent-doc: ["src", "lib", "app", ...]; corky: just ["src"].
    pub source_dirs: Vec<&'static str>,

    /// Directories to skip when scanning for source files.
    pub skip_dirs: Vec<&'static str>,
}

impl AuditConfig {
    /// Config matching agent-doc's current behavior: broad project detection,
    /// includes CLAUDE.md, scans many source extensions.
    pub fn agent_doc() -> Self {
        Self {
            root_markers: vec![
                "Cargo.toml",
                "package.json",
                "pyproject.toml",
                "setup.py",
                "go.mod",
                "Gemfile",
                "pom.xml",
                "build.gradle",
                "CMakeLists.txt",
                "Makefile",
                "flake.nix",
                "deno.json",
                "composer.json",
            ],
            include_claude_md: true,
            source_extensions: vec![
                "rs", "ts", "tsx", "js", "jsx", "py", "go", "rb", "java", "kt", "c", "cpp", "h",
                "hpp", "cs", "swift", "zig", "hs", "ml", "ex", "exs", "clj", "scala", "lua",
                "php", "sh", "bash", "zsh",
            ],
            source_dirs: vec!["src", "lib", "app", "pkg", "cmd", "internal"],
            skip_dirs: vec![
                "node_modules",
                "target",
                "build",
                "dist",
                ".git",
                "__pycache__",
                ".venv",
                "vendor",
                ".next",
                "out",
            ],
        }
    }

    /// Config matching corky's current behavior: Cargo.toml-only root detection,
    /// excludes CLAUDE.md from audit, scans only .rs files.
    pub fn corky() -> Self {
        Self {
            root_markers: vec!["Cargo.toml"],
            include_claude_md: false,
            source_extensions: vec!["rs"],
            source_dirs: vec!["src"],
            skip_dirs: vec!["target", ".git"],
        }
    }
}

/// An issue found during auditing.
pub struct Issue {
    pub file: String,
    pub line: usize,
    pub end_line: usize,
    pub message: String,
    pub warning: bool,
}

/// Check if a file path refers to an agent instruction file.
pub fn is_agent_file(rel: &str, config: &AuditConfig) -> bool {
    let name = Path::new(rel)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("");
    if name == "AGENTS.md" || name == "SKILL.md" {
        return true;
    }
    if config.include_claude_md && name == "CLAUDE.md" {
        return true;
    }
    false
}

// ---------------------------------------------------------------------------
// Checks
// ---------------------------------------------------------------------------

/// Default line budget for combined instruction files.
pub const LINE_BUDGET: usize = 1000;

static MACHINE_LOCAL_RE: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"(?m)(?:~/|/home/\w+|/Users/\w+|/root/|/tmp/|C:\\Users\\)").unwrap()
});

/// Check instruction files for machine-local path references.
///
/// Flags paths like `~/`, `/home/user/`, `/Users/user/`, `/tmp/` that won't
/// resolve on other machines. These should use repo-relative paths or
/// declared dependency references instead.
pub fn check_context_invariant(rel: &str, content: &str, config: &AuditConfig) -> Vec<Issue> {
    if !is_agent_file(rel, config) {
        return vec![];
    }

    let mut issues = Vec::new();
    let mut in_code_fence = false;

    for (i, line) in content.lines().enumerate() {
        let trimmed = line.trim();

        // Track code fences -- skip content inside them
        if trimmed.starts_with("```") {
            in_code_fence = !in_code_fence;
            continue;
        }
        if in_code_fence {
            continue;
        }

        // Check for machine-local paths
        if let Some(m) = MACHINE_LOCAL_RE.find(line) {
            issues.push(Issue {
                file: rel.to_string(),
                line: i + 1,
                end_line: 0,
                message: format!(
                    "Machine-local path \"{}\" \u{2014} use repo-relative path instead",
                    m.as_str()
                ),
                warning: true,
            });
        }
    }

    issues
}

/// Check if instruction files are older than source code.
pub fn check_staleness(files: &[PathBuf], root: &Path, config: &AuditConfig) -> Vec<Issue> {
    let mut newest_mtime = std::time::SystemTime::UNIX_EPOCH;
    let mut newest_src = PathBuf::new();

    fn scan_sources(
        dir: &Path,
        extensions: &[&str],
        skip_dirs: &[&str],
        newest: &mut std::time::SystemTime,
        newest_path: &mut PathBuf,
    ) {
        if let Ok(entries) = std::fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    if let Some(name) = path.file_name().and_then(|n| n.to_str())
                        && skip_dirs.contains(&name)
                    {
                        continue;
                    }
                    scan_sources(&path, extensions, skip_dirs, newest, newest_path);
                } else if let Some(ext) = path.extension().and_then(|e| e.to_str())
                    && extensions.contains(&ext)
                    && let Ok(meta) = path.metadata()
                    && let Ok(mtime) = meta.modified()
                    && mtime > *newest
                {
                    *newest = mtime;
                    *newest_path = path;
                }
            }
        }
    }

    let mut found_any = false;
    for source_dir in &config.source_dirs {
        let dir = root.join(source_dir);
        if dir.exists() {
            found_any = true;
            scan_sources(
                &dir,
                &config.source_extensions,
                &config.skip_dirs,
                &mut newest_mtime,
                &mut newest_src,
            );
        }
    }

    if !found_any {
        return vec![];
    }

    let mut issues = Vec::new();
    for doc in files {
        if let Ok(meta) = doc.metadata()
            && let Ok(doc_mtime) = meta.modified()
            && doc_mtime < newest_mtime
        {
            let rel = doc.strip_prefix(root).unwrap_or(doc).to_string_lossy().to_string();
            let src_rel = newest_src
                .strip_prefix(root)
                .unwrap_or(&newest_src)
                .to_string_lossy()
                .to_string();
            issues.push(Issue {
                file: rel,
                line: 0,
                end_line: 0,
                message: format!("Older than {} \u{2014} may be stale", src_rel),
                warning: false,
            });
        }
    }
    issues
}

/// Check combined line count against budget.
///
/// Only counts agent instruction files (AGENTS.md, SKILL.md, optionally CLAUDE.md).
/// Reference docs (README.md, SPEC.md) are listed but excluded from the budget.
pub fn check_line_budget(
    files: &[PathBuf],
    root: &Path,
    config: &AuditConfig,
) -> (Vec<Issue>, Vec<(String, usize)>, usize) {
    let mut counts = Vec::new();
    let mut total = 0;
    for f in files {
        if let Ok(content) = std::fs::read_to_string(f) {
            let n = content.lines().count();
            let rel = f.strip_prefix(root).unwrap_or(f).to_string_lossy().to_string();
            if is_agent_file(&rel, config) {
                total += n;
            }
            counts.push((rel, n));
        }
    }
    let mut issues = Vec::new();
    if total > LINE_BUDGET {
        issues.push(Issue {
            file: "(all)".to_string(),
            line: 0,
            end_line: 0,
            message: format!("Over line budget: {} lines (max {})", total, LINE_BUDGET),
            warning: false,
        });
    }
    (issues, counts, total)
}

// ---------------------------------------------------------------------------
// Discovery
// ---------------------------------------------------------------------------

/// Find the project root by walking up from CWD.
///
/// Strategy depends on config:
/// - Pass 1: Check `config.root_markers` in order
/// - Pass 2: Check for `.git` directory
/// - Pass 3: Fall back to CWD
pub fn find_root(config: &AuditConfig) -> PathBuf {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));

    // Pass 1: Look for project marker files
    let mut dir = cwd.as_path();
    loop {
        for marker in &config.root_markers {
            if dir.join(marker).exists() {
                return dir.to_path_buf();
            }
        }
        match dir.parent() {
            Some(p) if p != dir => dir = p,
            _ => break,
        }
    }

    // Pass 2: Look for .git directory
    dir = cwd.as_path();
    loop {
        if dir.join(".git").exists() {
            return dir.to_path_buf();
        }
        match dir.parent() {
            Some(p) if p != dir => dir = p,
            _ => break,
        }
    }

    // Pass 3: Fall back to CWD
    eprintln!("Warning: no project root marker found, using current directory");
    cwd
}

/// Discover all instruction files under the given root.
///
/// Searches for:
/// - Root-level: AGENTS.md, README.md, SPEC.md, and optionally CLAUDE.md
/// - Glob patterns: .claude/**/SKILL.md, .agents/**/SKILL.md, .agents/**/AGENTS.md, src/**/AGENTS.md
/// - If `config.include_claude_md`: also .claude/**/CLAUDE.md, src/**/CLAUDE.md
pub fn find_instruction_files(root: &Path, config: &AuditConfig) -> Vec<PathBuf> {
    let mut root_patterns = vec!["AGENTS.md", "README.md", "SPEC.md"];
    if config.include_claude_md {
        root_patterns.push("CLAUDE.md");
    }

    let mut found = std::collections::HashSet::new();

    for pattern in &root_patterns {
        let path = root.join(pattern);
        if path.exists() {
            found.insert(path);
        }
    }

    // Common glob patterns
    let mut glob_patterns = vec![
        ".claude/**/SKILL.md",
        ".agents/**/SKILL.md",
        ".agents/**/AGENTS.md",
        "src/**/AGENTS.md",
        ".agent/runbooks/*.md",
        ".claude/skills/**/runbooks/*.md",
    ];

    if config.include_claude_md {
        glob_patterns.push(".claude/**/CLAUDE.md");
        glob_patterns.push("src/**/CLAUDE.md");
    }

    for pattern in &glob_patterns {
        if let Ok(entries) = glob::glob(&root.join(pattern).to_string_lossy()) {
            for entry in entries.flatten() {
                found.insert(entry);
            }
        }
    }

    let mut result: Vec<PathBuf> = found.into_iter().collect();
    result.sort();
    result
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // --- is_agent_file ---

    #[test]
    fn is_agent_file_with_claude() {
        let config = AuditConfig::agent_doc();
        assert!(is_agent_file("AGENTS.md", &config));
        assert!(is_agent_file("SKILL.md", &config));
        assert!(is_agent_file("CLAUDE.md", &config));
        assert!(is_agent_file("src/AGENTS.md", &config));
        assert!(is_agent_file(".claude/skills/email/SKILL.md", &config));
        assert!(is_agent_file("nested/path/CLAUDE.md", &config));
    }

    #[test]
    fn is_agent_file_without_claude() {
        let config = AuditConfig::corky();
        assert!(is_agent_file("AGENTS.md", &config));
        assert!(is_agent_file("SKILL.md", &config));
        assert!(!is_agent_file("CLAUDE.md", &config));
    }

    #[test]
    fn is_agent_file_rejects() {
        let config = AuditConfig::agent_doc();
        assert!(!is_agent_file("README.md", &config));
        assert!(!is_agent_file("agents.md", &config));
        assert!(!is_agent_file("CHANGELOG.md", &config));
        assert!(!is_agent_file("src/main.rs", &config));
    }

    // --- check_context_invariant ---

    #[test]
    fn context_invariant_flags_home_tilde() {
        let config = AuditConfig::agent_doc();
        let content = "# Doc\n\nSee ~/some/path for config.\n";
        let issues = check_context_invariant("CLAUDE.md", content, &config);
        assert_eq!(issues.len(), 1);
        assert!(issues[0].message.contains("Machine-local path"));
        assert!(issues[0].warning);
    }

    #[test]
    fn context_invariant_flags_home_absolute() {
        let config = AuditConfig::agent_doc();
        let content = "# Doc\n\nConfig at /home/brian/.config/foo.\n";
        let issues = check_context_invariant("AGENTS.md", content, &config);
        assert_eq!(issues.len(), 1);
        assert!(issues[0].message.contains("/home/brian"));
    }

    #[test]
    fn context_invariant_flags_macos_users() {
        let config = AuditConfig::agent_doc();
        let content = "# Doc\n\nSee /Users/alice/project.\n";
        let issues = check_context_invariant("CLAUDE.md", content, &config);
        assert_eq!(issues.len(), 1);
        assert!(issues[0].message.contains("/Users/alice"));
    }

    #[test]
    fn context_invariant_skips_code_fences() {
        let config = AuditConfig::agent_doc();
        let content = "# Doc\n\n```bash\nexistence --ontology ~/path\n```\n";
        let issues = check_context_invariant("CLAUDE.md", content, &config);
        assert!(issues.is_empty());
    }

    #[test]
    fn context_invariant_clean_file() {
        let config = AuditConfig::agent_doc();
        let content = "# Doc\n\nUse `src/main.rs` for the entry point.\n";
        let issues = check_context_invariant("AGENTS.md", content, &config);
        assert!(issues.is_empty());
    }

    #[test]
    fn context_invariant_skips_non_agent_files() {
        let config = AuditConfig::agent_doc();
        let content = "# Doc\n\nSee ~/config.\n";
        let issues = check_context_invariant("README.md", content, &config);
        assert!(issues.is_empty());
    }

    // --- check_line_budget ---

    #[test]
    fn check_line_budget_under() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("AGENTS.md"), "line1\nline2\nline3\n").unwrap();

        let config = AuditConfig::corky();
        let files = vec![root.join("AGENTS.md")];
        let (issues, counts, total) = check_line_budget(&files, root, &config);
        assert!(issues.is_empty());
        assert_eq!(total, 3);
        assert_eq!(counts.len(), 1);
        assert_eq!(counts[0].0, "AGENTS.md");
        assert_eq!(counts[0].1, 3);
    }

    #[test]
    fn check_line_budget_over() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let content = "line\n".repeat(1001);
        fs::write(root.join("AGENTS.md"), &content).unwrap();

        let config = AuditConfig::corky();
        let files = vec![root.join("AGENTS.md")];
        let (issues, _, total) = check_line_budget(&files, root, &config);
        assert_eq!(total, 1001);
        assert_eq!(issues.len(), 1);
        assert!(issues[0].message.contains("Over line budget"));
    }

    #[test]
    fn check_line_budget_multiple_files() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("AGENTS.md"), "a\nb\n").unwrap();
        fs::write(root.join("SKILL.md"), "c\nd\ne\n").unwrap();

        let config = AuditConfig::corky();
        let files = vec![root.join("AGENTS.md"), root.join("SKILL.md")];
        let (_, counts, total) = check_line_budget(&files, root, &config);
        assert_eq!(total, 5);
        assert_eq!(counts.len(), 2);
    }

    #[test]
    fn check_line_budget_excludes_non_agent_files() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("AGENTS.md"), "a\nb\n").unwrap();
        let big_spec = "line\n".repeat(2000);
        fs::write(root.join("SPEC.md"), &big_spec).unwrap();
        fs::write(root.join("README.md"), "readme\n").unwrap();

        let config = AuditConfig::corky();
        let files = vec![
            root.join("AGENTS.md"),
            root.join("SPEC.md"),
            root.join("README.md"),
        ];
        let (issues, counts, total) = check_line_budget(&files, root, &config);
        // Only AGENTS.md counts toward budget (2 lines)
        assert_eq!(total, 2);
        assert!(issues.is_empty());
        // All files listed in counts
        assert_eq!(counts.len(), 3);
    }

    // --- check_staleness ---

    #[test]
    fn check_staleness_doc_newer_than_src() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let src = root.join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("main.rs"), "fn main() {}").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(50));
        fs::write(root.join("CLAUDE.md"), "# Doc").unwrap();

        let config = AuditConfig::agent_doc();
        let files = vec![root.join("CLAUDE.md")];
        let issues = check_staleness(&files, root, &config);
        assert!(issues.is_empty());
    }

    #[test]
    fn check_staleness_doc_older_than_src() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        let src = root.join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(root.join("CLAUDE.md"), "# Doc").unwrap();
        std::thread::sleep(std::time::Duration::from_millis(50));
        fs::write(src.join("main.rs"), "fn main() {}").unwrap();

        let config = AuditConfig::agent_doc();
        let files = vec![root.join("CLAUDE.md")];
        let issues = check_staleness(&files, root, &config);
        assert_eq!(issues.len(), 1);
        assert!(issues[0].message.contains("may be stale"));
    }

    #[test]
    fn check_staleness_no_src_dir() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("CLAUDE.md"), "# Doc").unwrap();

        let config = AuditConfig::agent_doc();
        let files = vec![root.join("CLAUDE.md")];
        let issues = check_staleness(&files, root, &config);
        assert!(issues.is_empty());
    }

    // --- find_instruction_files ---

    #[test]
    fn find_instruction_files_root_patterns_with_claude() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("CLAUDE.md"), "# Doc").unwrap();
        fs::write(root.join("README.md"), "# Readme").unwrap();
        fs::write(root.join("AGENTS.md"), "# Agents").unwrap();

        let config = AuditConfig::agent_doc();
        let files = find_instruction_files(root, &config);
        assert_eq!(files.len(), 3);
        assert!(files.iter().any(|f| f.ends_with("CLAUDE.md")));
        assert!(files.iter().any(|f| f.ends_with("README.md")));
        assert!(files.iter().any(|f| f.ends_with("AGENTS.md")));
    }

    #[test]
    fn find_instruction_files_root_patterns_without_claude() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("CLAUDE.md"), "# Doc").unwrap();
        fs::write(root.join("README.md"), "# Readme").unwrap();
        fs::write(root.join("AGENTS.md"), "# Agents").unwrap();

        let config = AuditConfig::corky();
        let files = find_instruction_files(root, &config);
        assert_eq!(files.len(), 2);
        assert!(!files.iter().any(|f| f.ends_with("CLAUDE.md")));
    }

    #[test]
    fn find_instruction_files_glob_patterns() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();

        fs::create_dir_all(root.join(".claude/skills/email")).unwrap();
        fs::write(root.join(".claude/skills/email/SKILL.md"), "# Skill").unwrap();

        fs::create_dir_all(root.join(".claude/settings")).unwrap();
        fs::write(root.join(".claude/settings/CLAUDE.md"), "# Claude").unwrap();

        fs::create_dir_all(root.join("src/agent")).unwrap();
        fs::write(root.join("src/agent/CLAUDE.md"), "# Agent").unwrap();
        fs::write(root.join("src/agent/AGENTS.md"), "# Agents").unwrap();

        let config = AuditConfig::agent_doc();
        let files = find_instruction_files(root, &config);
        assert_eq!(files.len(), 4);
    }

    #[test]
    fn find_instruction_files_empty() {
        let tmp = TempDir::new().unwrap();
        let config = AuditConfig::agent_doc();
        let files = find_instruction_files(tmp.path(), &config);
        assert!(files.is_empty());
    }

    #[test]
    fn find_instruction_files_sorted() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("README.md"), "# R").unwrap();
        fs::write(root.join("CLAUDE.md"), "# C").unwrap();
        fs::write(root.join("AGENTS.md"), "# A").unwrap();

        let config = AuditConfig::agent_doc();
        let files = find_instruction_files(root, &config);
        let names: Vec<_> = files.iter().map(|f| f.file_name().unwrap()).collect();
        assert!(names.windows(2).all(|w| w[0] <= w[1]));
    }

    #[test]
    fn find_instruction_files_discovers_spec_md() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("SPEC.md"), "# Spec").unwrap();
        fs::write(root.join("AGENTS.md"), "# Agents").unwrap();

        let config = AuditConfig::corky();
        let files = find_instruction_files(root, &config);
        assert!(files.iter().any(|f| f.ends_with("SPEC.md")));
        assert_eq!(files.len(), 2);
    }

    #[test]
    fn find_instruction_files_discovers_runbooks() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();

        fs::create_dir_all(root.join(".agent/runbooks")).unwrap();
        fs::write(root.join(".agent/runbooks/precommit.md"), "# Precommit").unwrap();
        fs::write(
            root.join(".agent/runbooks/prerelease.md"),
            "# Prerelease",
        )
        .unwrap();

        fs::create_dir_all(root.join(".claude/skills/email/runbooks")).unwrap();
        fs::write(
            root.join(".claude/skills/email/runbooks/send.md"),
            "# Send",
        )
        .unwrap();

        let config = AuditConfig::corky();
        let files = find_instruction_files(root, &config);
        assert_eq!(files.len(), 3);
        assert!(files.iter().any(|f| f.ends_with("precommit.md")));
        assert!(files.iter().any(|f| f.ends_with("prerelease.md")));
        assert!(files.iter().any(|f| f.ends_with("send.md")));
    }

    #[test]
    fn find_instruction_files_deduplicates() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        fs::write(root.join("CLAUDE.md"), "# Doc").unwrap();

        let config = AuditConfig::agent_doc();
        let files = find_instruction_files(root, &config);
        assert_eq!(files.len(), 1);
    }
}