hematite-cli 0.11.0

Senior SysAdmin, Network Admin, Data Analyst, and Software Engineer living in your terminal. A high-precision local AI agent harness for LM Studio, Ollama, and other local OpenAI-compatible runtimes that runs 100% on your own silicon. Reads repos, edits files, runs builds, inspects full network state and workstation telemetry, and runs real Python/JS for data analysis.
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};

use serde::Deserialize;

use crate::agent::config::WorkspaceTrustConfig;
use crate::agent::truncation::safe_head;
use crate::agent::trust_resolver::{resolve_workspace_trust, WorkspaceTrustPolicy};

pub const PROJECT_GUIDANCE_FILES: &[&str] = &[
    "AGENTS.md",
    "agents.md",
    "CLAUDE.md",
    ".claude.md",
    "CLAUDE.local.md",
    "HEMATITE.md",
    "HEMATITE.local.md",
    ".hematite/rules.md",
    ".hematite/rules.local.md",
    "SKILLS.md",
    "SKILL.md",
    ".hematite/instructions.md",
];

pub const AGENT_SKILL_DIRS: &[&str] = &[".agents/skills", ".hematite/skills"];

#[derive(Debug, Clone)]
pub struct InstructionFile {
    pub path: PathBuf,
    pub content: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SkillScope {
    User,
    Project,
}

impl SkillScope {
    pub fn label(self) -> &'static str {
        match self {
            SkillScope::User => "user",
            SkillScope::Project => "project",
        }
    }
}

#[derive(Debug, Clone)]
pub struct AgentSkill {
    pub name: String,
    pub description: String,
    pub compatibility: Option<String>,
    /// Glob patterns that auto-activate this skill based on file context.
    /// Examples: `["*.py"]`, `["*.rs"]`, `["Cargo.toml"]`
    pub triggers: Vec<String>,
    pub skill_md_path: PathBuf,
    pub scope: SkillScope,
    pub body: String,
}

#[derive(Debug, Clone)]
pub struct SkillDiscovery {
    pub skills: Vec<AgentSkill>,
    pub project_skills_loaded: bool,
    pub project_skills_note: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct SkillFrontmatter {
    name: Option<String>,
    description: Option<String>,
    compatibility: Option<String>,
    // Comma-separated glob patterns, e.g. "*.py, *.pyx" or "Cargo.toml"
    triggers: Option<String>,
}

pub fn resolve_guidance_path(dir: &Path, candidate_name: &str) -> PathBuf {
    candidate_name
        .split('/')
        .fold(dir.to_path_buf(), |acc, part| acc.join(part))
}

pub fn guidance_section_title(candidate_name: &str) -> &'static str {
    match candidate_name {
        "SKILLS.md" | "SKILL.md" => "PROJECT GUIDANCE",
        _ => "PROJECT RULES",
    }
}

pub fn guidance_status_label(candidate_name: &str) -> &'static str {
    match candidate_name {
        "SKILLS.md" | "SKILL.md" => "(workspace guidance)",
        _ if candidate_name.contains(".local") || candidate_name.ends_with(".local.md") => {
            "(local override)"
        }
        _ => "(shared asset)",
    }
}

pub fn discover_agent_skills(
    workspace_root: &Path,
    trust_config: &WorkspaceTrustConfig,
) -> SkillDiscovery {
    let mut discovered: Vec<AgentSkill> = Vec::new();

    if let Some(home) = dirs::home_dir() {
        let user_roots = AGENT_SKILL_DIRS
            .iter()
            .map(|relative| resolve_guidance_path(&home, relative))
            .collect::<Vec<_>>();
        load_skills_from_roots(&mut discovered, &user_roots, SkillScope::User);
    }

    let trust = resolve_workspace_trust(workspace_root, trust_config);
    let (project_skills_loaded, project_skills_note) = match trust.policy {
        WorkspaceTrustPolicy::Trusted => {
            let project_roots = AGENT_SKILL_DIRS
                .iter()
                .map(|relative| resolve_guidance_path(workspace_root, relative))
                .collect::<Vec<_>>();
            load_skills_from_roots(&mut discovered, &project_roots, SkillScope::Project);
            (true, None)
        }
        WorkspaceTrustPolicy::RequireApproval => (
            false,
            Some(format!(
                "Project skill directories were skipped because `{}` is not trust-allowlisted.",
                trust.workspace_display
            )),
        ),
        WorkspaceTrustPolicy::Denied => (
            false,
            Some(format!(
                "Project skill directories were skipped because `{}` is denied by trust policy.",
                trust.workspace_display
            )),
        ),
    };

    SkillDiscovery {
        skills: dedupe_skills(discovered),
        project_skills_loaded,
        project_skills_note,
    }
}

pub fn render_skill_catalog(discovery: &SkillDiscovery, max_chars: usize) -> Option<String> {
    if discovery.skills.is_empty() && discovery.project_skills_note.is_none() {
        return None;
    }

    let mut output = Vec::with_capacity(discovery.skills.len() + 2);
    output.push("# Agent Skills Catalog".to_string());
    output.push(
        "These skills use progressive disclosure. Read a skill's SKILL.md before following it; only load scripts, references, or assets when the skill calls for them.".to_string(),
    );
    if let Some(note) = &discovery.project_skills_note {
        output.push(format!("- {}", note));
    }

    let mut remaining = max_chars;
    for skill in &discovery.skills {
        if remaining < 150 {
            output.push("\n... [further skills omitted due to context limit]".to_string());
            break;
        }
        let mut line = format!(
            "- {} [{}] — {} | SKILL.md: {}",
            skill.name,
            skill.scope.label(),
            skill.description,
            skill.skill_md_path.display()
        );
        if !skill.triggers.is_empty() {
            let _ = write!(line, " | auto-activates: {}", skill.triggers.join(", "));
        }
        if let Some(compatibility) = &skill.compatibility {
            let _ = write!(line, " | compatibility: {}", compatibility);
        }
        remaining = remaining.saturating_sub(line.len());
        output.push(line);
    }

    Some(output.join("\n"))
}

/// Returns skills whose names (or hyphenated name parts) appear in `query`,
/// or whose `triggers` glob patterns match files referenced in the query or
/// the active workspace stack.
pub fn activate_matching_skills<'a>(
    discovery: &'a SkillDiscovery,
    query: &str,
) -> Vec<&'a AgentSkill> {
    let q = query.to_lowercase();
    let workspace_root = crate::tools::file_ops::workspace_root();
    let ws_exts = workspace_stack_extensions(&workspace_root);
    let query_paths = extract_query_paths(query);

    let mut matched = Vec::with_capacity(discovery.skills.len());
    for skill in &discovery.skills {
        // 1. Direct name match (e.g. "use the pdf-processing skill")
        let name_lower = skill.name.to_lowercase();
        if q.contains(&name_lower) {
            matched.push(skill);
            continue;
        }

        // 2. All significant hyphen/underscore parts appear in query.
        // Split the already-lowercased name to avoid a per-part allocation.
        let parts: Vec<&str> = name_lower
            .split(['-', '_', ' '])
            .filter(|p| p.len() > 3)
            .collect();
        if parts.len() >= 2 && parts.iter().all(|p| q.contains(*p)) {
            matched.push(skill);
            continue;
        }

        // 3. Trigger glob matches a file path mentioned in the query
        if !skill.triggers.is_empty() {
            let trigger_hit = skill
                .triggers
                .iter()
                .any(|pattern| query_paths.iter().any(|path| glob_matches(pattern, path)));
            if trigger_hit {
                matched.push(skill);
                continue;
            }

            // 4. Trigger glob matches the workspace stack (e.g. "*.rs" when Cargo.toml exists)
            let ws_hit = skill
                .triggers
                .iter()
                .any(|pattern| ws_exts.iter().any(|ext| glob_matches(pattern, ext)));
            if ws_hit {
                matched.push(skill);
            }
        }
    }
    matched
}

/// Simple glob matcher supporting `*.ext`, `prefix*`, and exact-name patterns.
fn glob_matches(pattern: &str, name: &str) -> bool {
    if let Some(ext_pattern) = pattern.strip_prefix("*.") {
        // *.ext — match the file extension
        name.ends_with(&format!(".{}", ext_pattern)) || name == ext_pattern
    } else if let Some(prefix) = pattern.strip_suffix('*') {
        name.starts_with(prefix)
    } else if pattern.contains('*') {
        // mid-pattern wildcard: split on first * and check prefix + suffix
        let (pre, suf) = pattern.split_once('*').unwrap();
        name.starts_with(pre) && name.ends_with(suf)
    } else {
        // exact match (e.g. "Cargo.toml")
        name == pattern
    }
}

/// Returns synthetic "file extension" strings that represent the active workspace stack,
/// derived from presence of stack marker files. Used to match trigger patterns like `*.rs`.
fn workspace_stack_extensions(root: &std::path::Path) -> Vec<String> {
    let mut exts: Vec<String> = Vec::with_capacity(8);
    let markers: &[(&str, &[&str])] = &[
        ("Cargo.toml", &["x.rs"]),
        ("go.mod", &["x.go"]),
        ("CMakeLists.txt", &["x.cpp", "x.c", "x.h"]),
        ("package.json", &["x.ts", "x.js", "x.tsx", "x.jsx"]),
        ("tsconfig.json", &["x.ts", "x.tsx"]),
        ("pyproject.toml", &["x.py"]),
        ("setup.py", &["x.py"]),
        ("requirements.txt", &["x.py"]),
        ("Gemfile", &["x.rb"]),
        ("pom.xml", &["x.java"]),
        ("build.gradle", &["x.java", "x.kt"]),
        ("composer.json", &["x.php"]),
    ];
    for (marker, file_exts) in markers {
        if root.join(marker).exists() {
            exts.extend(file_exts.iter().map(|s| s.to_string()));
        }
    }
    exts
}

/// Extracts token-like file paths from the query (words containing a `.` and a known extension,
/// plus `@mention` paths).
fn extract_query_paths(query: &str) -> Vec<String> {
    let known_exts = [
        "rs", "py", "ts", "js", "tsx", "jsx", "go", "cpp", "c", "h", "java", "kt", "rb", "php",
        "swift", "cs", "md", "toml", "yaml", "yml", "json", "html", "css", "scss", "sh", "pdf",
        "txt",
    ];
    let mut paths = Vec::new();
    for token in query.split_whitespace() {
        let token = token.trim_matches(|c: char| {
            !c.is_alphanumeric() && c != '.' && c != '/' && c != '_' && c != '-' && c != '@'
        });
        let effective = token.strip_prefix('@').unwrap_or(token);
        if let Some(ext) = effective.rsplit('.').next() {
            if known_exts.contains(&ext.to_lowercase().as_str()) {
                paths.push(effective.to_string());
            }
        }
    }
    paths
}

/// Renders the full body text of every skill that matches `query`.
/// Returns `None` when no skills are activated or all bodies are empty.
pub fn render_active_skill_bodies(
    discovery: &SkillDiscovery,
    query: &str,
    max_chars: usize,
) -> Option<String> {
    let matches = activate_matching_skills(discovery, query);
    if matches.is_empty() {
        return None;
    }
    let mut sections: Vec<String> = vec!["# Active Skill Instructions".to_string()];
    let mut remaining = max_chars;
    for skill in matches {
        if remaining < 200 {
            sections.push("... [further skill bodies omitted — context limit]".to_string());
            break;
        }
        let body = skill.body.trim();
        if body.is_empty() {
            continue;
        }
        let section = format!("## Skill: {}\n{}", skill.name, body);
        let entry = if section.len() > remaining {
            format!(
                "{}\n... [skill body truncated]",
                &section[..remaining.saturating_sub(30)]
            )
        } else {
            section
        };
        remaining = remaining.saturating_sub(entry.len());
        sections.push(entry);
    }
    if sections.len() <= 1 {
        return None;
    }
    Some(sections.join("\n\n"))
}

pub fn render_skills_report(discovery: &SkillDiscovery) -> String {
    let mut report = String::from("## Agent Skills\n\n");
    let _ = write!(
        report,
        "Project skill directories: {}\n\n",
        if discovery.project_skills_loaded {
            "loaded"
        } else {
            "skipped"
        }
    );
    if let Some(note) = &discovery.project_skills_note {
        report.push_str(note);
        report.push_str("\n\n");
    }
    if discovery.skills.is_empty() {
        report.push_str("No Agent Skills were discovered.\n\n");
        report.push_str("Scanned locations:\n");
        report.push_str("- `<project>/.agents/skills/`\n");
        report.push_str("- `<project>/.hematite/skills/`\n");
        report.push_str("- `~/.agents/skills/`\n");
        report.push_str("- `~/.hematite/skills/`\n");
        report.push_str(
            "\nAgent Skills are directory-based and require a `SKILL.md` file at the skill root.",
        );
        return report;
    }

    report.push_str("Discovered skills:\n");
    for skill in &discovery.skills {
        let _ = write!(
            report,
            "- `{}` [{}] — {}\n  SKILL.md: {}\n",
            skill.name,
            skill.scope.label(),
            skill.description,
            skill.skill_md_path.display()
        );
        if !skill.triggers.is_empty() {
            let _ = writeln!(report, "  auto-activates: {}", skill.triggers.join(", "));
        }
        if let Some(compatibility) = &skill.compatibility {
            let _ = writeln!(report, "  compatibility: {}", compatibility);
        }
    }
    report
}

/// Discovers project guidance files from the current directory up to the root.
pub fn discover_instruction_files(cwd: &Path) -> Vec<InstructionFile> {
    let mut directories = Vec::new();
    let mut cursor = Some(cwd);
    while let Some(dir) = cursor {
        directories.push(dir.to_path_buf());
        cursor = dir.parent();
    }
    directories.reverse();

    let mut files = Vec::new();
    let mut seen_hashes = HashSet::new();

    for dir in directories {
        for candidate_name in PROJECT_GUIDANCE_FILES {
            let candidate_path = resolve_guidance_path(&dir, candidate_name);

            if let Ok(content) = fs::read_to_string(&candidate_path) {
                let trimmed = content.trim();
                if !trimmed.is_empty() {
                    // Simple hash/dedupe based on content to ignore shadowed files.
                    let hash = stable_hash(trimmed);
                    if seen_hashes.contains(&hash) {
                        continue;
                    }
                    seen_hashes.insert(hash);
                    files.push(InstructionFile {
                        path: candidate_path,
                        content: trimmed.to_string(),
                    });
                }
            }
        }
    }
    files
}

fn stable_hash(s: &str) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};
    let mut hasher = DefaultHasher::new();
    s.hash(&mut hasher);
    hasher.finish()
}

/// Renders instruction files into a prompt section with a limit on characters.
pub fn render_instructions(files: &[InstructionFile], max_chars: usize) -> Option<String> {
    if files.is_empty() {
        return None;
    }

    let mut output = Vec::with_capacity(files.len() + 2);
    output.push("# Project Instructions And Skills".to_string());
    output.push(
        "These guidance files were discovered in the directory tree for the current repository:"
            .to_string(),
    );

    let mut remaining = max_chars;
    for file in files {
        if remaining < 100 {
            output.push("\n... [further instructions omitted due to context limit]".to_string());
            break;
        }

        let content = if file.content.len() > remaining {
            format!(
                "{}\n... [truncated]",
                safe_head(&file.content, remaining.saturating_sub(20))
            )
        } else {
            file.content.clone()
        };

        remaining = remaining.saturating_sub(content.len());
        output.push(format!("\n## Source: {}\n{}", file.path.display(), content));
    }

    Some(output.join("\n"))
}

fn load_skills_from_roots(into: &mut Vec<AgentSkill>, roots: &[PathBuf], scope: SkillScope) {
    for root in roots {
        if !root.exists() || !root.is_dir() {
            continue;
        }
        for skill_md in discover_skill_markdown_files(root) {
            if let Some(skill) = parse_agent_skill(&skill_md, scope) {
                into.push(skill);
            }
        }
    }
}

fn discover_skill_markdown_files(root: &Path) -> Vec<PathBuf> {
    let mut files = Vec::new();
    for entry in walkdir::WalkDir::new(root)
        .min_depth(2)
        .max_depth(4)
        .into_iter()
        .filter_map(Result::ok)
    {
        if !entry.file_type().is_file() {
            continue;
        }
        if entry.file_name() != "SKILL.md" {
            continue;
        }
        files.push(entry.into_path());
    }
    files
}

fn parse_agent_skill(skill_md_path: &Path, scope: SkillScope) -> Option<AgentSkill> {
    let content = fs::read_to_string(skill_md_path).ok()?;
    let (frontmatter, body) = split_frontmatter(&content)?;
    let parsed = parse_frontmatter(&frontmatter)?;
    let name = parsed.name?.trim().to_string();
    let description = parsed.description?.trim().to_string();
    if name.is_empty() || description.is_empty() {
        return None;
    }
    let triggers = parsed
        .triggers
        .map(|t| {
            t.split(',')
                .map(|p| p.trim().to_string())
                .filter(|p| !p.is_empty())
                .collect()
        })
        .unwrap_or_default();
    Some(AgentSkill {
        name,
        description,
        compatibility: parsed
            .compatibility
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty()),
        triggers,
        skill_md_path: skill_md_path.to_path_buf(),
        scope,
        body: body.trim().to_string(),
    })
}

fn split_frontmatter(content: &str) -> Option<(String, String)> {
    let mut lines = content.lines();
    if lines.next()?.trim() != "---" {
        return None;
    }
    let mut frontmatter = Vec::new();
    let mut body = Vec::new();
    let mut in_frontmatter = true;
    for line in lines {
        if in_frontmatter && line.trim() == "---" {
            in_frontmatter = false;
            continue;
        }
        if in_frontmatter {
            frontmatter.push(line);
        } else {
            body.push(line);
        }
    }
    if in_frontmatter {
        return None;
    }
    Some((frontmatter.join("\n"), body.join("\n")))
}

fn parse_frontmatter(frontmatter: &str) -> Option<SkillFrontmatter> {
    serde_yaml::from_str::<SkillFrontmatter>(frontmatter)
        .ok()
        .or_else(|| parse_frontmatter_fallback(frontmatter))
}

fn parse_frontmatter_fallback(frontmatter: &str) -> Option<SkillFrontmatter> {
    let mut parsed = SkillFrontmatter::default();
    for line in frontmatter.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let Some((key, value)) = trimmed.split_once(':') else {
            continue;
        };
        let value = value.trim();
        let value = strip_matching_quotes(value);
        match key.trim() {
            "name" => parsed.name = Some(value.to_string()),
            "description" => parsed.description = Some(value.to_string()),
            "compatibility" => parsed.compatibility = Some(value.to_string()),
            "triggers" => parsed.triggers = Some(value.to_string()),
            _ => {}
        }
    }
    (parsed.name.is_some() || parsed.description.is_some()).then_some(parsed)
}

fn strip_matching_quotes(value: &str) -> &str {
    if value.len() >= 2 {
        let bytes = value.as_bytes();
        let first = bytes[0] as char;
        let last = bytes[value.len() - 1] as char;
        if (first == '"' && last == '"') || (first == '\'' && last == '\'') {
            return &value[1..value.len() - 1];
        }
    }
    value
}

fn dedupe_skills(skills: Vec<AgentSkill>) -> Vec<AgentSkill> {
    let mut deduped = Vec::with_capacity(skills.len());
    let mut indexes: HashMap<String, usize> = HashMap::with_capacity(skills.len());
    for skill in skills {
        if let Some(index) = indexes.get(&skill.name).copied() {
            deduped[index] = skill;
        } else {
            indexes.insert(skill.name.clone(), deduped.len());
            deduped.push(skill);
        }
    }
    deduped.sort_by(|left, right| left.name.cmp(&right.name));
    deduped
}

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

    #[test]
    fn fallback_frontmatter_handles_unquoted_colons() {
        let parsed = parse_frontmatter(
            "name: pdf-processing\ndescription: Use when: PDFs, forms, or extraction are involved\ncompatibility: Requires Python 3.11+: tested locally",
        )
        .unwrap();

        assert_eq!(parsed.name.as_deref(), Some("pdf-processing"));
        assert_eq!(
            parsed.description.as_deref(),
            Some("Use when: PDFs, forms, or extraction are involved")
        );
        assert_eq!(
            parsed.compatibility.as_deref(),
            Some("Requires Python 3.11+: tested locally")
        );
    }

    #[test]
    fn project_skill_overrides_user_skill_on_name_collision() {
        let temp = tempfile::tempdir().unwrap();
        let user_root = temp.path().join("user");
        let project_root = temp.path().join("project");

        fs::create_dir_all(user_root.join(".agents/skills/review")).unwrap();
        fs::create_dir_all(project_root.join(".agents/skills/review")).unwrap();

        fs::write(
            user_root.join(".agents/skills/review/SKILL.md"),
            "---\nname: review\ndescription: User skill.\n---\n",
        )
        .unwrap();
        fs::write(
            project_root.join(".agents/skills/review/SKILL.md"),
            "---\nname: review\ndescription: Project skill.\n---\n",
        )
        .unwrap();

        let mut discovered = Vec::new();
        load_skills_from_roots(
            &mut discovered,
            &[user_root.join(".agents/skills")],
            SkillScope::User,
        );
        load_skills_from_roots(
            &mut discovered,
            &[project_root.join(".agents/skills")],
            SkillScope::Project,
        );

        let deduped = dedupe_skills(discovered);
        assert_eq!(deduped.len(), 1);
        assert_eq!(deduped[0].description, "Project skill.");
        assert_eq!(deduped[0].scope, SkillScope::Project);
    }

    #[test]
    fn trusted_workspace_discovers_project_skill_dirs() {
        let temp = tempfile::tempdir().unwrap();
        let workspace = temp.path().join("workspace");
        let user_home = temp.path().join("home");

        fs::create_dir_all(workspace.join(".agents/skills/code-review")).unwrap();
        fs::create_dir_all(user_home.join(".agents/skills/global-review")).unwrap();
        fs::write(
            workspace.join(".agents/skills/code-review/SKILL.md"),
            "---\nname: code-review\ndescription: Review diffs.\n---\n",
        )
        .unwrap();
        fs::write(
            user_home.join(".agents/skills/global-review/SKILL.md"),
            "---\nname: global-review\ndescription: Global review skill.\n---\n",
        )
        .unwrap();

        let mut discovered = Vec::new();
        load_skills_from_roots(
            &mut discovered,
            &[user_home.join(".agents/skills")],
            SkillScope::User,
        );
        load_skills_from_roots(
            &mut discovered,
            &[workspace.join(".agents/skills")],
            SkillScope::Project,
        );
        let deduped = dedupe_skills(discovered);

        let names = deduped
            .into_iter()
            .map(|skill| skill.name)
            .collect::<Vec<_>>();
        assert_eq!(
            names,
            vec!["code-review".to_string(), "global-review".to_string()]
        );
    }

    #[test]
    fn activate_matching_skills_finds_by_name() {
        let discovery = SkillDiscovery {
            skills: vec![
                AgentSkill {
                    name: "pdf-processing".to_string(),
                    description: "Use when PDFs are involved.".to_string(),
                    compatibility: None,
                    triggers: vec![],
                    skill_md_path: PathBuf::from("/tmp/pdf-processing/SKILL.md"),
                    scope: SkillScope::User,
                    body: "Step 1: extract text.".to_string(),
                },
                AgentSkill {
                    name: "code-review".to_string(),
                    description: "Review diffs.".to_string(),
                    compatibility: None,
                    triggers: vec![],
                    skill_md_path: PathBuf::from("/tmp/code-review/SKILL.md"),
                    scope: SkillScope::Project,
                    body: "Review all changed files.".to_string(),
                },
            ],
            project_skills_loaded: true,
            project_skills_note: None,
        };

        // Direct name match
        let m = activate_matching_skills(&discovery, "please use the pdf-processing skill");
        assert_eq!(m.len(), 1);
        assert_eq!(m[0].name, "pdf-processing");

        // Part match (both "code" and "review" in query, each >3 chars)
        let m2 = activate_matching_skills(&discovery, "can you do a code review of this PR?");
        assert_eq!(m2.len(), 1);
        assert_eq!(m2[0].name, "code-review");

        // No match
        let m3 = activate_matching_skills(&discovery, "what is the weather today?");
        assert!(m3.is_empty());
    }

    #[test]
    fn activate_matching_skills_triggers_on_file_extension() {
        let discovery = SkillDiscovery {
            skills: vec![AgentSkill {
                name: "python-style".to_string(),
                description: "Python style guide.".to_string(),
                compatibility: None,
                triggers: vec!["*.py".to_string()],
                skill_md_path: PathBuf::from("/tmp/python-style/SKILL.md"),
                scope: SkillScope::User,
                body: "Use ruff for linting.".to_string(),
            }],
            project_skills_loaded: true,
            project_skills_note: None,
        };

        // File extension in query activates skill
        let m = activate_matching_skills(&discovery, "fix the type hints in src/parser.py");
        assert_eq!(m.len(), 1, "should activate via *.py trigger");

        // @mention path
        let m2 = activate_matching_skills(&discovery, "refactor @src/utils.py");
        assert_eq!(m2.len(), 1, "should activate via @mention .py path");

        // Unrelated query — no file extension match
        let m3 = activate_matching_skills(&discovery, "how does the network stack work?");
        assert!(m3.is_empty());
    }

    #[test]
    fn glob_matches_patterns() {
        assert!(glob_matches("*.rs", "main.rs"));
        assert!(glob_matches("*.rs", "src/lib.rs"));
        assert!(!glob_matches("*.rs", "main.py"));
        assert!(glob_matches("Cargo.toml", "Cargo.toml"));
        assert!(!glob_matches("Cargo.toml", "cargo.toml"));
        assert!(glob_matches("test*", "test_utils.rs"));
        assert!(!glob_matches("test*", "unit_test.rs"));
        assert!(glob_matches("*.py", "x.py")); // exact ext sentinel
    }

    #[test]
    fn triggers_parsed_from_frontmatter() {
        let temp = tempfile::tempdir().unwrap();
        fs::create_dir_all(temp.path().join("py-skill")).unwrap();
        fs::write(
            temp.path().join("py-skill/SKILL.md"),
            "---\nname: py-skill\ndescription: Python helper.\ntriggers: \"*.py, *.pyx\"\n---\n\nDo python things.\n",
        )
        .unwrap();

        let skill =
            parse_agent_skill(&temp.path().join("py-skill/SKILL.md"), SkillScope::User).unwrap();
        assert_eq!(skill.triggers, vec!["*.py", "*.pyx"]);
        assert!(skill.body.contains("Do python things."));
    }

    #[test]
    fn render_active_skill_bodies_injects_body() {
        let discovery = SkillDiscovery {
            skills: vec![AgentSkill {
                name: "pdf-processing".to_string(),
                description: "Use when PDFs are involved.".to_string(),
                compatibility: None,
                triggers: vec![],
                skill_md_path: PathBuf::from("/tmp/pdf-processing/SKILL.md"),
                scope: SkillScope::User,
                body: "## Instructions\nRun pdftotext first.".to_string(),
            }],
            project_skills_loaded: true,
            project_skills_note: None,
        };

        let rendered =
            render_active_skill_bodies(&discovery, "process this pdf-processing task", 8_000);
        assert!(rendered.is_some());
        let text = rendered.unwrap();
        assert!(text.contains("Active Skill Instructions"));
        assert!(text.contains("Skill: pdf-processing"));
        assert!(text.contains("pdftotext"));

        // No match → None
        let none = render_active_skill_bodies(&discovery, "unrelated query about network", 8_000);
        assert!(none.is_none());
    }

    #[test]
    fn skill_body_captured_from_skill_md() {
        let temp = tempfile::tempdir().unwrap();
        fs::create_dir_all(temp.path().join("my-skill")).unwrap();
        fs::write(
            temp.path().join("my-skill/SKILL.md"),
            "---\nname: my-skill\ndescription: A test skill.\n---\n\n## How to use\nDo the thing.\n",
        )
        .unwrap();

        let skill =
            parse_agent_skill(&temp.path().join("my-skill/SKILL.md"), SkillScope::User).unwrap();
        assert_eq!(skill.name, "my-skill");
        assert!(skill.body.contains("Do the thing."));
    }

    #[test]
    fn guidance_catalog_renders_skill_paths() {
        let discovery = SkillDiscovery {
            skills: vec![AgentSkill {
                name: "code-review".to_string(),
                description: "Review diffs.".to_string(),
                compatibility: Some("Requires git".to_string()),
                triggers: vec![],
                skill_md_path: PathBuf::from("/tmp/code-review/SKILL.md"),
                scope: SkillScope::Project,
                body: String::new(),
            }],
            project_skills_loaded: true,
            project_skills_note: None,
        };

        let rendered = render_skill_catalog(&discovery, 2_000).unwrap();
        assert!(rendered.contains("code-review"));
        assert!(rendered.contains("/tmp/code-review/SKILL.md"));
        assert!(rendered.contains("Requires git"));
    }
}