choreo-daemon 0.2.0

Agentic coding assistant — daemon, TUI, and bridges
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
use crate::tools::ToolGroup;
use choreo_proto::ContextConfig;
use itertools::Itertools;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

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

pub struct ContextBundle {
    pub files: Vec<DiscoveredFile>,
    pub fingerprint: u64,
}

#[derive(Debug, Clone, Deserialize)]
struct SkillFrontmatter {
    name: String,
    description: String,
}

#[derive(Debug, Clone)]
pub struct SkillMeta {
    pub name: String,
    pub description: String,
    pub path: PathBuf,
}

#[derive(Debug, Clone)]
pub struct LoadedSkill {
    pub name: String,
    pub body: String,
}

pub fn discover_context(working_dir: &Path, config: &ContextConfig) -> io::Result<ContextBundle> {
    let mut files = Vec::new();
    load_global_files(&mut files, config)?;
    load_project_files(working_dir, &mut files, config)?;
    let fingerprint = compute_fingerprint(&files);
    Ok(ContextBundle { files, fingerprint })
}

fn load_global_files(files: &mut Vec<DiscoveredFile>, config: &ContextConfig) -> io::Result<()> {
    if let Some(config_dir) = dirs::config_dir() {
        let path = config_dir.join("choreographr").join("AGENTS.md");
        if let Some(df) = try_load_file(&path) {
            files.push(df);
        }
    }

    if !config.disable_claude_code_prompt
        && let Some(home) = dirs::home_dir()
    {
        let path = home.join(".claude").join("CLAUDE.md");
        if let Some(df) = try_load_file(&path) {
            files.push(df);
        }
    }

    if let Some(home) = dirs::home_dir() {
        let path = home.join(".agents").join("AGENTS.md");
        if let Some(df) = try_load_file(&path) {
            files.push(df);
        }
    }

    Ok(())
}

fn load_project_files(
    working_dir: &Path,
    files: &mut Vec<DiscoveredFile>,
    config: &ContextConfig,
) -> io::Result<()> {
    let git_root = find_git_root(working_dir);
    let boundary = git_root.as_deref().unwrap_or_else(|| Path::new("/"));

    let mut seen = HashSet::new();
    let mut found = Vec::new();
    let mut current = Some(working_dir.to_path_buf());

    while let Some(dir) = current {
        for name in &config.context_file_names {
            let path = dir.join(name);
            if let Some(df) = try_load_file(&path)
                && seen.insert(df.path.clone())
            {
                found.push(df);
                break;
            }
        }

        if dir == boundary {
            break;
        }
        current = dir.parent().map(|p| p.to_path_buf());
    }

    found.reverse();
    files.append(&mut found);

    Ok(())
}

fn find_git_root(working_dir: &Path) -> Option<PathBuf> {
    let mut current = Some(working_dir.to_path_buf());
    while let Some(ref dir) = current {
        let git_path = dir.join(".git");
        if git_path.exists() {
            return Some(dir.clone());
        }
        let parent = dir.parent().map(|p| p.to_path_buf());
        if parent == current {
            break;
        }
        current = parent;
    }
    None
}

fn try_load_file(path: &Path) -> Option<DiscoveredFile> {
    let metadata = fs::metadata(path).ok()?;
    if !metadata.is_file() || metadata.len() == 0 {
        return None;
    }
    let mtime = metadata.modified().ok()?;
    let content = fs::read_to_string(path).ok()?;
    let content = content.trim().to_string();
    if content.is_empty() {
        return None;
    }
    Some(DiscoveredFile {
        path: path.to_path_buf(),
        mtime,
        content,
    })
}

pub fn compute_fingerprint(files: &[DiscoveredFile]) -> u64 {
    let mut hasher = Sha256::new();
    let mut entries: Vec<(&Path, SystemTime)> =
        files.iter().map(|f| (f.path.as_path(), f.mtime)).collect();
    entries.sort_by(|a, b| a.0.cmp(b.0));

    for (path, mtime) in &entries {
        hasher.update(path.as_os_str().as_encoded_bytes());
        if let Ok(dur) = mtime.duration_since(std::time::UNIX_EPOCH) {
            hasher.update(dur.as_secs().to_le_bytes());
            hasher.update(dur.subsec_nanos().to_le_bytes());
        }
    }

    let hash = hasher.finalize();
    // Fixed-size 32-byte sha256 digest; the range is always in bounds so the
    // fallback is unreachable.
    let mut bytes = [0u8; 8];
    bytes.copy_from_slice(hash.get(..8).unwrap_or(&[0u8; 8]));
    u64::from_le_bytes(bytes)
}

pub fn assemble_context(bundle: &ContextBundle) -> String {
    if bundle.files.is_empty() {
        return String::new();
    }

    let mut out = String::new();
    for file in &bundle.files {
        let path_display = file.path.display();
        out.push_str(&format!(
            "<agent_instructions path=\"{path_display}\">\n{}\n</agent_instructions>\n",
            file.content
        ));
    }
    out
}

pub fn build_base_prompt(
    skills: &[SkillMeta],
    groups: &[ToolGroup],
    loaded_skills: &[LoadedSkill],
) -> String {
    let user_prompt = load_user_system_prompt();
    let mut base = user_prompt.unwrap_or_else(default_system_prompt);

    // Tool group listing (always shown)
    base.push_str("\n\n## Tool groups\n");
    base.push_str("Tools are organized into groups. Only **core**, **git**, and **shell** are active by default. Use the `load_tools` tool to activate additional groups and `unload_tools` to deactivate them.\n\n");
    for g in groups {
        base.push_str(&format!("- **{}**: {}\n", g.name, g.description));
    }

    if !skills.is_empty() {
        base.push_str("\n## Available skills\n");
        base.push_str("Use the `load_skill` tool to load a skill's full instructions when a task matches its description:\n\n");
        for skill in skills {
            base.push_str(&format!("- **{}**: {}\n", skill.name, skill.description));
        }
    }

    if !loaded_skills.is_empty() {
        base.push_str(
            "\n## Loaded skills\nThe following skills have been loaded and are active:\n\n",
        );
        for ls in loaded_skills {
            base.push_str(&format!(
                "<skill name=\"{name}\">\n{body}\n</skill>\n\n",
                name = ls.name,
                body = ls.body
            ));
        }
    }
    base
}

fn load_user_system_prompt() -> Option<String> {
    let config_dir = dirs::config_dir()?;
    let path = config_dir.join("choreographr").join("system.md");
    let content = fs::read_to_string(&path).ok()?;
    let content = content.trim().to_string();
    if content.is_empty() {
        None
    } else {
        Some(content)
    }
}

fn default_system_prompt() -> String {
    include_str!("../system.md").to_string()
}

/// The two filesystem scopes skill discovery reads. Named (rather than two
/// positional `Option<&Path>`s) so `global_home` and `working_dir` cannot be
/// swapped by mistake — they are both optional paths of the same type.
#[derive(Debug, Clone, Copy, Default)]
pub struct SkillScopes<'a> {
    /// Base of the always-on global scope: `<global_home>/.agents/skills`.
    pub global_home: Option<&'a Path>,
    /// Session working directory scoping the project-local walk (most-local wins).
    pub working_dir: Option<&'a Path>,
}

/// Discover skills from the global scope and an optional project scope.
///
/// `scopes.global_home` is the base of the always-on global scope —
/// `<global_home>/.agents/skills` is scanned unconditionally. Production
/// passes `dirs::home_dir()` (see [`discover_skills_ambient`]); it is a
/// parameter so tests can inject a temp directory instead of reading the
/// developer's real home, which makes global discovery deterministic.
///
/// `scopes.working_dir` scopes the project-local walk; when `None` only the
/// global scope is read (a dir-less session still gets global skills).
///
/// Precedence: the PROJECT walk is scanned first and the global scope LAST, so
/// a project-local skill **shadows** a same-named global skill (dedup is by
/// frontmatter `name`, the identity `load_skill` resolves by). Within the
/// project walk the most-local directory is scanned first, so a skill beats a
/// same-named one higher up the tree.
pub fn discover_skills(scopes: SkillScopes<'_>) -> Vec<SkillMeta> {
    let mut skills = Vec::new();
    // Dedup by frontmatter name: the first occurrence wins. Because the
    // project walk below runs before the global scope, this gives project
    // skills precedence over global ones of the same name.
    let mut seen_names = HashSet::new();

    // Project-local skills first (most-local wins), scoped up to the git-root
    // (or filesystem) boundary. Needs a working directory; a dir-less session
    // simply has no project scope.
    if let Some(working_dir) = scopes.working_dir {
        let git_root = find_git_root(working_dir);
        let boundary = git_root.as_deref().unwrap_or_else(|| Path::new("/"));
        let mut current = Some(working_dir.to_path_buf());
        while let Some(dir) = current {
            scan_skills_dir(
                &dir.join(".agents").join("skills"),
                &mut skills,
                &mut seen_names,
            );
            if dir == boundary {
                break;
            }
            current = dir.parent().map(|p| p.to_path_buf());
        }
    }

    // Global scope LAST: the lowest-precedence fallback, so a global skill only
    // lands here when no project skill shares its name. Independent of the
    // working directory, so a dir-less session still discovers global skills.
    if let Some(global_home) = scopes.global_home {
        scan_skills_dir(
            &global_home.join(".agents").join("skills"),
            &mut skills,
            &mut seen_names,
        );
    }

    skills
}

/// [`discover_skills`] with the real home directory (`dirs::home_dir()`) as the
/// global scope. Production call sites use this; tests call [`discover_skills`]
/// directly to inject a temp home so global discovery is deterministic.
pub fn discover_skills_ambient(working_dir: Option<&Path>) -> Vec<SkillMeta> {
    discover_skills(SkillScopes {
        global_home: dirs::home_dir().as_deref(),
        working_dir,
    })
}

fn scan_skills_dir(dir: &Path, skills: &mut Vec<SkillMeta>, seen_names: &mut HashSet<String>) {
    let entries = match fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };

    // Collect the candidate skill directories and sort them by path before
    // parsing: `fs::read_dir` iteration order is unspecified, so two skill
    // dirs within the SAME scope declaring the same frontmatter `name` would
    // otherwise have an arbitrary winner. Sorting makes the within-scope
    // shadowing deterministic (the lexicographically-first path wins).
    let dirs: Vec<PathBuf> = entries
        .filter_map(|e| e.ok())
        .map(|e| e.path())
        .filter(|path| path.is_dir())
        .sorted()
        .collect();

    for path in dirs {
        let skill_md = path.join("SKILL.md");
        // Dedup on the frontmatter name: a project skill shadows a same-named
        // global skill because the project walk runs first.
        if let Some(meta) = parse_skill_metadata(&skill_md)
            && seen_names.insert(meta.name.clone())
        {
            skills.push(meta);
        }
    }
}

fn parse_skill_metadata(path: &Path) -> Option<SkillMeta> {
    let content = fs::read_to_string(path).ok()?;
    let frontmatter = extract_yaml_frontmatter(&content)?;
    let fm: SkillFrontmatter = yaml_serde::from_str(&frontmatter).ok()?;
    Some(SkillMeta {
        name: fm.name,
        description: fm.description,
        path: path.to_path_buf(),
    })
}

fn extract_yaml_frontmatter(content: &str) -> Option<String> {
    let content = content.trim_start();
    if !content.starts_with("---") {
        return None;
    }
    let rest = content
        .strip_prefix("---")?
        .strip_prefix('\n')
        .unwrap_or(content.strip_prefix("---")?);
    let end = rest.find("\n---")?;
    // `end` comes from `find`, so it is a char boundary; fallback preserves behavior.
    Some(rest.get(..end).unwrap_or("").trim().to_string())
}

/// Read a skill's body from an already-resolved [`SkillMeta`] list.
///
/// Callers that hold a discovered/cached skill set — notably
/// `persist_loaded_skill` reusing `SessionState::discovered_skills` — use this
/// to avoid re-walking the filesystem.
pub fn load_skill_body_from(skills: &[SkillMeta], name: &str) -> Option<String> {
    let meta = skills.iter().find(|s| s.name == name)?;
    let content = fs::read_to_string(&meta.path).ok()?;
    extract_skill_body(&content)
}

/// Discover then read a skill's body. Convenience for callers without a cached
/// skill set (the `load_skill` tool); the persistence path uses
/// [`load_skill_body_from`] with the session's cached skills instead.
pub fn load_skill_body(name: &str, working_dir: Option<&Path>) -> Option<String> {
    let skills = discover_skills_ambient(working_dir);
    load_skill_body_from(&skills, name)
}

fn extract_skill_body(content: &str) -> Option<String> {
    let content = content.trim_start();
    if !content.starts_with("---") {
        return None;
    }
    let rest = content
        .strip_prefix("---")?
        .strip_prefix('\n')
        .unwrap_or(content.strip_prefix("---")?);
    let end = rest.find("\n---")?;
    // `end` comes from `find`, so `end + 4` is a char boundary; fallback preserves behavior.
    let body = rest.get(end + 4..).unwrap_or("").trim().to_string();
    if body.is_empty() { None } else { Some(body) }
}

pub fn recheck_context(
    working_dir: &Path,
    config: &ContextConfig,
    old_fingerprint: u64,
) -> io::Result<Option<ContextBundle>> {
    let bundle = discover_context(working_dir, config)?;
    if bundle.fingerprint == old_fingerprint {
        Ok(None)
    } else {
        Ok(Some(bundle))
    }
}

pub fn subdirectory_hints(
    tool_name: &str,
    arguments_json: &str,
    working_dir: Option<&Path>,
    known_paths: &[PathBuf],
) -> Option<(String, Vec<PathBuf>)> {
    let target_path = extract_tool_path(tool_name, arguments_json)?;
    // Resolve the tool's target path against the session working directory.
    // No in-process confinement check here — the OS-level sandbox (Landlock /
    // Seatbelt) is the boundary; resolution simply determines where the hint
    // walk should start.
    let resolved = crate::tools::resolve_path(&target_path, working_dir);
    let parent = resolved.parent()?;
    let working_dir_canonical = working_dir
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| PathBuf::from("."));
    let working_dir_canonical = working_dir_canonical
        .canonicalize()
        .unwrap_or_else(|_| working_dir_canonical.clone());

    let mut hints = Vec::new();
    let mut new_paths = Vec::new();
    let mut current = Some(parent.to_path_buf());
    while let Some(dir) = current {
        // Perform the containment check in canonical space: the tool's
        // resolved path may carry a raw `/var` prefix while the working dir is
        // symlink-resolved, and on macOS `/var` → `/private/var`. Comparing
        // raw paths here would wrongly break out of the loop before reaching
        // any hints. We canonicalize only for the comparison — the returned
        // paths stay raw so they round-trip consistently through the caller's
        // `known_hint_paths` tracking.
        let dir_canonical = dir.canonicalize().unwrap_or_else(|_| dir.clone());
        if !dir_canonical.starts_with(&working_dir_canonical)
            || dir_canonical == working_dir_canonical
        {
            break;
        }

        for name in &["AGENTS.md", "CLAUDE.md"] {
            let path = dir.join(name);
            if known_paths.iter().any(|kp| kp == &path) {
                continue;
            }
            if let Some(content) = read_hint_file(&path) {
                hints.push((path.clone(), content));
                new_paths.push(path);
                break;
            }
        }

        current = dir.parent().map(|p| p.to_path_buf());
    }

    if hints.is_empty() {
        return None;
    }

    let mut out = String::from("Context from subdirectory:\n\n");
    for (path, content) in hints.iter().rev() {
        out.push_str(&format!(
            "<agent_instructions path=\"{}\">\n{}\n</agent_instructions>\n",
            path.display(),
            content
        ));
    }
    Some((out, new_paths))
}

fn extract_tool_path(tool_name: &str, arguments_json: &str) -> Option<String> {
    let v: serde_json::Value = serde_json::from_str(arguments_json).ok()?;
    match tool_name {
        "read_file" | "read_file_range" | "write_file" | "edit_file" => {
            v.get("path")?.as_str().map(|s| s.to_string())
        }
        "list_files" => v
            .get("path")
            .or_else(|| v.get("directory"))
            .and_then(|p| p.as_str())
            .map(|s| s.to_string()),
        "grep" => v
            .get("path")
            .and_then(|p| p.as_str())
            .map(|s| s.to_string()),
        "find" => v
            .get("path")
            .and_then(|p| p.as_str())
            .map(|s| s.to_string()),
        _ => None,
    }
}

fn read_hint_file(path: &Path) -> Option<String> {
    let content = fs::read_to_string(path).ok()?;
    let content = content.trim().to_string();
    if content.is_empty() {
        None
    } else {
        Some(content)
    }
}

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

    fn write_file(dir: &Path, name: &str, content: &str) {
        let path = dir.join(name);
        fs::create_dir_all(dir).unwrap();
        let mut f = fs::File::create(&path).unwrap();
        f.write_all(content.as_bytes()).unwrap();
    }

    #[test]
    fn test_extract_yaml_frontmatter() {
        let content = "---\nname: test-skill\ndescription: A test skill\n---\n\n# Body";
        let fm = extract_yaml_frontmatter(content).unwrap();
        assert!(fm.contains("name: test-skill"));
        assert!(fm.contains("description: A test skill"));
    }

    #[test]
    fn test_extract_skill_body() {
        let content =
            "---\nname: test\ndescription: desc\n---\n\nThis is the body.\nMultiple lines.";
        let body = extract_skill_body(content).unwrap();
        assert_eq!(body, "This is the body.\nMultiple lines.");
    }

    #[test]
    fn test_extract_tool_path() {
        let path = extract_tool_path("read_file", r#"{"path": "src/main.rs"}"#).unwrap();
        assert_eq!(path, "src/main.rs");

        let path = extract_tool_path("list_files", r#"{"directory": "/tmp"}"#).unwrap();
        assert_eq!(path, "/tmp");

        assert!(extract_tool_path("git_status", r#"{}"#).is_none());
    }

    #[test]
    fn test_fingerprint_deterministic() {
        let tmp = TempDir::new().unwrap();
        write_file(tmp.path(), "AGENTS.md", "Test content");

        let bundle1 = discover_context(tmp.path(), &ContextConfig::default()).unwrap();
        let bundle2 = discover_context(tmp.path(), &ContextConfig::default()).unwrap();

        assert_eq!(bundle1.fingerprint, bundle2.fingerprint);
    }

    #[test]
    fn test_discover_context_from_tempdir() {
        let tmp = TempDir::new().unwrap();
        write_file(tmp.path(), "AGENTS.md", "Project rules");

        let bundle = discover_context(tmp.path(), &ContextConfig::default()).unwrap();
        assert!(!bundle.files.is_empty());
        assert!(
            bundle
                .files
                .iter()
                .any(|f| f.content.contains("Project rules"))
        );
    }

    #[test]
    fn test_recheck_unchanged() {
        let tmp = TempDir::new().unwrap();
        write_file(tmp.path(), "AGENTS.md", "unchanging");

        let config = ContextConfig::default();
        let bundle = discover_context(tmp.path(), &config).unwrap();
        let result = recheck_context(tmp.path(), &config, bundle.fingerprint).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_recheck_changed() {
        let tmp = TempDir::new().unwrap();
        write_file(tmp.path(), "AGENTS.md", "version 1");

        filetime::set_file_mtime(
            tmp.path().join("AGENTS.md"),
            filetime::FileTime::from_unix_time(0, 0),
        )
        .unwrap();

        let config = ContextConfig::default();
        let bundle = discover_context(tmp.path(), &config).unwrap();
        let fp = bundle.fingerprint;

        write_file(tmp.path(), "AGENTS.md", "version 2");

        let result = recheck_context(tmp.path(), &config, fp).unwrap();
        assert!(result.is_some());
        assert_ne!(result.unwrap().fingerprint, fp);
    }

    #[test]
    fn test_assemble_context_format() {
        let tmp = TempDir::new().unwrap();
        write_file(tmp.path(), "AGENTS.md", "test content");

        let bundle = discover_context(tmp.path(), &ContextConfig::default()).unwrap();
        let assembled = assemble_context(&bundle);

        assert!(assembled.contains("<agent_instructions"));
        assert!(assembled.contains("test content"));
        assert!(assembled.contains("</agent_instructions>"));
    }

    #[test]
    fn test_subdirectory_hints() {
        let tmp = TempDir::new().unwrap();
        let sub = tmp.path().join("subdir");
        fs::create_dir_all(&sub).unwrap();
        write_file(&sub, "AGENTS.md", "subdir hints");
        write_file(&sub, "file.txt", "hello");

        let file_path = sub.join("file.txt");
        let args = serde_json::json!({"path": file_path.to_str().unwrap()}).to_string();
        let hints = subdirectory_hints("read_file", &args, Some(tmp.path()), &[]);

        assert!(hints.is_some());
        let (hint_text, new_paths) = hints.unwrap();
        assert!(hint_text.contains("subdir hints"));
        assert!(new_paths.contains(&sub.join("AGENTS.md")));
    }

    #[test]
    fn test_subdirectory_hints_skips_known() {
        let tmp = TempDir::new().unwrap();
        let sub = tmp.path().join("subdir");
        fs::create_dir_all(&sub).unwrap();
        let agents_path = sub.join("AGENTS.md");
        write_file(&sub, "AGENTS.md", "already known");
        write_file(&sub, "file.txt", "hello");

        let file_path = sub.join("file.txt");
        let args = serde_json::json!({"path": file_path.to_str().unwrap()}).to_string();
        let hints = subdirectory_hints("read_file", &args, Some(tmp.path()), &[agents_path]);
        assert!(hints.is_none());
    }

    #[test]
    fn test_subdirectory_hints_tracks_multiple_new_paths() {
        let tmp = TempDir::new().unwrap();
        let sub0 = tmp.path().join("sub0");
        let sub1 = sub0.join("sub1");
        fs::create_dir_all(&sub1).unwrap();
        write_file(&sub0, "AGENTS.md", "outer hints");
        write_file(&sub1, "AGENTS.md", "inner hints");
        write_file(&sub1, "file.txt", "hello");

        let file_path = sub1.join("file.txt");
        let args = serde_json::json!({"path": file_path.to_str().unwrap()}).to_string();
        let hints = subdirectory_hints("read_file", &args, Some(tmp.path()), &[]);

        assert!(hints.is_some());
        let (hint_text, new_paths) = hints.unwrap();
        assert!(hint_text.contains("outer hints"));
        assert!(hint_text.contains("inner hints"));
        assert_eq!(new_paths.len(), 2);
    }

    #[test]
    fn test_skill_discovery() {
        let tmp = TempDir::new().unwrap();
        let skills_dir = tmp.path().join(".agents").join("skills").join("test-skill");
        fs::create_dir_all(&skills_dir).unwrap();
        write_file(
            &skills_dir,
            "SKILL.md",
            "---\nname: test-skill\ndescription: A test skill for testing\n---\n\n# Instructions",
        );

        let skills = discover_skills(SkillScopes {
            global_home: None,
            working_dir: Some(tmp.path()),
        });
        assert!(skills.iter().any(|s| s.name == "test-skill"));
        assert!(
            skills
                .iter()
                .any(|s| s.description == "A test skill for testing")
        );
    }

    #[test]
    fn discover_skills_global_only_without_working_dir() {
        // A dir-less session has no project scope but still discovers the
        // global scope. Injecting a temp home makes this deterministic — no
        // dependence on the developer's ambient ~/.agents/skills.
        let home = TempDir::new().unwrap();
        let skill_dir = home
            .path()
            .join(".agents")
            .join("skills")
            .join("global-skill");
        write_file(
            &skill_dir,
            "SKILL.md",
            "---\nname: global-skill\ndescription: A global skill\n---\n\n# Body",
        );

        let skills = discover_skills(SkillScopes {
            global_home: Some(home.path()),
            working_dir: None,
        });
        assert!(
            skills.iter().any(|s| s.name == "global-skill"),
            "a dir-less session must still discover global skills"
        );
    }

    #[test]
    fn discover_skills_project_shadows_global_same_name() {
        // A project-local skill must win over a same-named global skill AND the
        // duplicate must be deduped (one entry, not two).
        let home = TempDir::new().unwrap();
        let global_dir = home.path().join(".agents").join("skills").join("shared");
        write_file(
            &global_dir,
            "SKILL.md",
            "---\nname: shared\ndescription: global description\n---\n\n# global body",
        );

        let project = TempDir::new().unwrap();
        let project_dir = project.path().join(".agents").join("skills").join("shared");
        write_file(
            &project_dir,
            "SKILL.md",
            "---\nname: shared\ndescription: project description\n---\n\n# project body",
        );

        let skills = discover_skills(SkillScopes {
            global_home: Some(home.path()),
            working_dir: Some(project.path()),
        });
        let shared: Vec<_> = skills.iter().filter(|s| s.name == "shared").collect();
        assert_eq!(shared.len(), 1, "same-named skills must be deduped by name");
        assert_eq!(
            shared[0].description, "project description",
            "the project-local skill must shadow the global one"
        );
        assert!(shared[0].path.starts_with(project.path()));
    }

    #[test]
    fn test_build_base_prompt_includes_skills() {
        let skills = vec![SkillMeta {
            name: "test-skill".to_string(),
            description: "A test skill".to_string(),
            path: PathBuf::from("/fake/SKILL.md"),
        }];

        let prompt = build_base_prompt(&skills, &[], &[]);
        assert!(prompt.contains("test-skill"));
        assert!(prompt.contains("A test skill"));
        assert!(prompt.contains("load_skill"));
    }

    #[test]
    fn test_build_base_prompt_includes_loaded_skills() {
        let loaded = vec![LoadedSkill {
            name: "loaded-skill".to_string(),
            body: "Loaded skill body content.".to_string(),
        }];

        let prompt = build_base_prompt(&[], &[], &loaded);
        assert!(prompt.contains("Loaded skills"));
        assert!(prompt.contains("loaded-skill"));
        assert!(prompt.contains("Loaded skill body content."));
        assert!(prompt.contains("<skill name=\"loaded-skill\">"));
    }

    #[test]
    fn test_load_skill_body() {
        let tmp = TempDir::new().unwrap();
        let skills_dir = tmp.path().join(".agents").join("skills").join("test-skill");
        fs::create_dir_all(&skills_dir).unwrap();
        write_file(
            &skills_dir,
            "SKILL.md",
            "---\nname: test-skill\ndescription: A test skill\n---\n\nThis is the skill body content.",
        );

        let body = load_skill_body("test-skill", Some(tmp.path())).unwrap();
        assert!(body.contains("skill body content"));
    }

    #[test]
    fn load_skill_body_from_reads_a_resolved_meta() {
        // The cached-skill path used by `persist_loaded_skill`: resolve once,
        // then read the body without re-walking the filesystem.
        let tmp = TempDir::new().unwrap();
        let skills_dir = tmp.path().join(".agents").join("skills").join("test-skill");
        write_file(
            &skills_dir,
            "SKILL.md",
            "---\nname: test-skill\ndescription: A test skill\n---\n\nThis is the skill body content.",
        );

        let skills = discover_skills(SkillScopes {
            global_home: None,
            working_dir: Some(tmp.path()),
        });
        let body = load_skill_body_from(&skills, "test-skill").unwrap();
        assert!(body.contains("skill body content"));
        assert!(load_skill_body_from(&skills, "absent").is_none());
    }
}