mind-cli 0.8.0

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
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
//! Installing items into the store and linking them into `~/.claude`.
//!
//! Installs are transactional and preserve the previous version until the new
//! one is fully built and validated:
//!
//! 1. Build the new copy in a staging dir and expand its `{{ns:}}` references
//!    there. The likeliest failure (a bad reference) happens here, while the
//!    live install is untouched.
//! 2. Move any existing store copy aside to a backup, then move staging into
//!    place and ensure the symlink.
//! 3. On any failure during the swap, restore from the backup. On success,
//!    drop the backup.
//!
//! Uninstall is driven by the per-item file registry recorded in the manifest
//! (`store` + `links`), so it removes exactly what was installed.

use std::path::Path;

use crate::catalog::CatalogItem;
use crate::error::{MindError, Result};
use crate::hash::hash_path;
use crate::manifest::InstalledItem;
use crate::namespace;
use crate::paths::{Paths, mkdir_p};

/// Install (or upgrade in place) one catalog item, returning its manifest record.
///
/// `commit` is the source's current commit; `siblings` is every catalog item in
/// the same source (including `item` itself), used to validate `{{ns:}}` name
/// tokens and to resolve the `{{self}}` / `{{tools:}}` / `{{path:}}` path tokens
/// to store paths. The recorded hash is of the *source* content so drift
/// detection compares like with like.
pub fn install(
    paths: &Paths,
    item: &CatalogItem,
    commit: &str,
    siblings: &[CatalogItem],
    force: bool,
) -> Result<InstalledItem> {
    let kind = item.kind;
    let name = item.effective_name();
    let store = paths.store_item(kind, &name);
    let staging = paths.staging_path(kind, &name);
    let backup = paths.backup_path(kind, &name);

    // 0. Resolve where this item will link, and refuse up front to overwrite any
    //    target that is not mind's own symlink (a user's file/dir/foreign link).
    //    This runs before staging, so a clobber aborts touching nothing. With
    //    `force`, the guard is skipped and step 3 overwrites the conflicting
    //    target (LIFE-41).
    // A tool with no explicit `link` is store-only: no link target, so no agent
    // home symlink (the harness does not discover it; items reach it by token).
    let link_rel = item
        .link_rel
        .clone()
        .or_else(|| paths.default_link_rel(kind, &name));
    let store_root = paths.store_dir();
    let planned_links: Vec<std::path::PathBuf> = match &link_rel {
        Some(rel) => paths
            .agent_homes()?
            .iter()
            .map(|home| home.join(rel))
            .collect(),
        None => Vec::new(),
    };
    if !force {
        for link in &planned_links {
            ensure_unoccupied(&store_root, link)?;
        }
    }

    // 1. Stage and validate the new copy. Live install is untouched until step 2.
    remove_path(&staging)?;
    if let Some(parent) = staging.parent() {
        mkdir_p(parent)?;
    }
    copy_recursive(&item.path, &staging)?;
    if let Err(e) = expand_references(&staging, item, siblings, &store_root) {
        let _ = remove_path(&staging);
        return Err(e);
    }

    // 1b. Per-item build hook: build the item's tooling inside staging, before
    //     the swap, so a failed build is rolled back with staging and never
    //     touches the live install (HOOK-70..73). It is arbitrary code, so it is
    //     disclosed and prompted on a TTY; a non-TTY context skips it (the item
    //     installs unbuilt, HOOK-72).
    if let Some(build) = &item.build
        && let Err(e) = run_build_hook(item, build, &staging, commit)
    {
        let _ = remove_path(&staging);
        return Err(e);
    }

    // 2. Swap staging into the store, holding any prior copy in backup.
    if let Some(parent) = store.parent() {
        mkdir_p(parent)?;
    }
    let had_backup = store.exists();
    if had_backup {
        remove_path(&backup)?;
        if let Some(parent) = backup.parent() {
            mkdir_p(parent)?;
        }
        rename(&store, &backup)?;
    }
    if let Err(e) = rename(&staging, &store) {
        if had_backup {
            let _ = rename(&backup, &store); // restore previous version
        }
        return Err(e);
    }

    // 3. Link the store copy into every agent home (targets were checked free in
    //    step 0). On any failure, undo the links made so far and roll the store
    //    back.
    let mut links: Vec<std::path::PathBuf> = Vec::new();
    for link in planned_links {
        if let Err(e) = ensure_link(&store, &link) {
            for made in &links {
                let _ = remove_path(made);
            }
            let _ = remove_path(&store);
            if had_backup {
                let _ = rename(&backup, &store);
            }
            return Err(e);
        }
        links.push(link);
    }

    // 4. Success: drop the backup.
    if had_backup {
        let _ = remove_path(&backup);
    }

    Ok(InstalledItem {
        kind,
        name,
        bare_name: item.name.clone(),
        source: item.source.clone(),
        commit: commit.to_string(),
        hash: hash_path(&item.path)?,
        store: paths.store_rel(kind, &item.effective_name()),
        links: links
            .iter()
            .map(|p| p.to_string_lossy().into_owned())
            .collect(),
        description: item.description.clone(),
    })
}

/// Remove an installed item using its recorded file registry (absolute link
/// paths across every agent home, then the store copy).
pub fn uninstall(paths: &Paths, item: &InstalledItem) -> Result<()> {
    for link in &item.links {
        remove_path(Path::new(link))?;
    }
    remove_path(&paths.mind_home.join(&item.store))?;
    Ok(())
}

/// Recreate any missing links for an installed item, pointing at its existing
/// store copy. Returns the number of links repaired. Used by `introspect --fix`.
/// If the store copy itself is gone there is nothing to link to, so it repairs
/// nothing (that is drift for `upgrade`/`learn` to resolve, not a re-link).
pub fn relink(paths: &Paths, item: &InstalledItem) -> Result<usize> {
    let store = paths.mind_home.join(&item.store);
    if !store.exists() {
        return Ok(0);
    }
    let mut fixed = 0;
    for link in &item.links {
        let link = Path::new(link);
        if std::fs::symlink_metadata(link).is_err() {
            ensure_link(&store, link)?;
            fixed += 1;
        }
    }
    Ok(fixed)
}

/// Refuse to install over a link target that mind does not own. A target is
/// "ours" only if it is a symlink pointing into the store root; a regular file,
/// a directory, or a symlink elsewhere is the user's and is left untouched
/// (`LinkOccupied`). A missing target is free.
fn ensure_unoccupied(store_root: &Path, link: &Path) -> Result<()> {
    match std::fs::symlink_metadata(link) {
        Ok(meta) => {
            let ours = meta.file_type().is_symlink()
                && std::fs::read_link(link).is_ok_and(|t| t.starts_with(store_root));
            if ours {
                Ok(())
            } else {
                Err(MindError::LinkOccupied {
                    path: link.display().to_string(),
                })
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(MindError::io(link, e)),
    }
}

/// Create (or refresh) a symlink at `link` pointing to `store`.
fn ensure_link(store: &Path, link: &Path) -> Result<()> {
    if let Some(parent) = link.parent() {
        mkdir_p(parent)?;
    }
    remove_path(link)?;
    symlink(store, link)
}

/// Rewrite reference tokens in every text file under the staged copy: the
/// `{{ns:name}}` name tokens, then the `{{self}}` / `{{tools:name}}` /
/// `{{path:ref}}` path tokens. Both resolve against `siblings` (every item in the
/// same source) and a bad reference in either pass aborts the staged install.
/// Also validates the `requires` frontmatter entries (DEP-6): each must resolve
/// to exactly one sibling (not source-qualified, not ambiguous, not missing).
fn expand_references(
    root: &Path,
    item: &CatalogItem,
    siblings: &[CatalogItem],
    store_root: &Path,
) -> Result<()> {
    let names: std::collections::HashSet<String> =
        siblings.iter().map(|s| s.name.clone()).collect();
    let path_siblings: Vec<namespace::PathSibling> =
        siblings.iter().map(CatalogItem::as_path_sibling).collect();
    // TOOL-16: render store paths with a leading `~` when the store is under
    // home, so a token expands to a value a Claude permission glob can match.
    let home = dirs::home_dir();
    let ctx = namespace::PathCtx {
        store_root,
        home: home.as_deref(),
        prefix: &item.prefix,
        self_kind: item.kind,
        self_name: &item.name,
        siblings: &path_siblings,
    };

    // DEP-6: validate every `requires` entry before touching any file. A bad
    // entry here aborts the staged install (the live copy is still untouched).
    let bad_ref = |referent: String| MindError::BadReference {
        item: item.key(),
        referent,
        in_source: item.source.clone(),
    };
    for entry in &item.requires {
        // spec: DEP-6
        let r = crate::resolve::parse_item_ref(entry)
            .map_err(|_| bad_ref(format!("requires: {entry}")))?;
        // Source-qualified entries cross sources, which is forbidden (DEP-5).
        if r.source.is_some() {
            return Err(bad_ref(format!("requires: {entry}")));
        }
        // Resolve against siblings by bare name, narrowing by kind (DEP-5).
        let matches: Vec<&CatalogItem> = siblings
            .iter()
            .filter(|s| s.name == r.name && r.kind.is_none_or(|k| s.kind == k))
            .collect();
        if matches.is_empty() || matches.len() > 1 && r.kind.is_none() {
            // Zero matches (typo/unknown) or ambiguous bare name (DEP-6).
            return Err(bad_ref(format!("requires: {entry}")));
        }
    }

    let mut files = Vec::new();
    if root.is_dir() {
        collect_files(root, &mut files)?;
    } else {
        files.push(root.to_path_buf());
    }
    for file in files {
        // Skip anything that is not valid UTF-8 text.
        let Ok(content) = std::fs::read_to_string(&file) else {
            continue;
        };
        if !content.contains("{{") {
            continue;
        }
        let expanded = namespace::expand(&content, &item.prefix, &names)
            .map_err(|name| bad_ref(format!("{{{{ns:{name}}}}}")))?;
        let expanded = namespace::expand_paths(&expanded, &ctx).map_err(&bad_ref)?;
        std::fs::write(&file, expanded).map_err(|e| MindError::io(&file, e))?;
    }
    Ok(())
}

/// Run an item's build hook in its staging directory. Disclosed and prompted on
/// a TTY (two-way: run, or skip and install unbuilt); a non-TTY context skips it
/// (HOOK-72). A non-zero exit is a hard stop (HOOK-71) the caller rolls back.
fn run_build_hook(item: &CatalogItem, build: &str, staging: &Path, commit: &str) -> Result<()> {
    let run = if !crate::hook::is_tty() {
        println!(
            "note: skipped build hook for {} in a non-interactive context; its tooling is not built",
            item.key()
        );
        false
    } else {
        let disclosure = crate::hook::disclosure_text(
            &item.source,
            "(per-item build)",
            commit,
            &staging.to_string_lossy(),
            build,
            None,
        );
        matches!(
            crate::hook::prompt_choice_optional(&disclosure)?,
            crate::hook::OptionalChoice::Run
        )
    };
    if run {
        println!("running build hook for {}", item.key());
        crate::hook::run_hook(build, staging, &item.source, "build")?;
    } else if crate::hook::is_tty() {
        println!(
            "note: skipped build hook for {}; its tooling is not built",
            item.key()
        );
    }
    Ok(())
}

/// The working directory for an item lifecycle hook: the item's store path when
/// it is a directory (a skill or tool), else its parent (an agent/rule store is a
/// single file, so the kind directory is the working dir).
fn hook_cwd(store: &Path) -> std::path::PathBuf {
    if store.is_dir() {
        store.to_path_buf()
    } else {
        store
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| store.to_path_buf())
    }
}

/// Run a per-item lifecycle hook (`event` is "install", HOOK-81, or "uninstall",
/// HOOK-82) in the item's store directory: the final step of an install, or the
/// step before a removal. Disclosed and prompted two-way (run / skip) on a TTY; a
/// non-TTY context skips it; `dangerously_skip` runs it unattended (HOOK-83). A
/// non-zero exit is a `HookFailed` hard stop the caller acts on (install rolls
/// back; uninstall leaves the item installed).
fn run_item_hook(
    event: &str,
    key: &str,
    source: &str,
    cmd: &str,
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> Result<()> {
    // The noun for the side effect the hook applies, per event.
    let effect = if event == "install" {
        "its side effect is not applied"
    } else {
        "its cleanup is not run"
    };
    let cwd = hook_cwd(store);
    let run = if dangerously_skip {
        true
    } else if !crate::hook::is_tty() {
        println!("note: skipped {event} hook for {key} in a non-interactive context; {effect}");
        false
    } else {
        let disclosure = crate::hook::disclosure_text(
            source,
            &format!("(per-item {event})"),
            commit,
            &cwd.to_string_lossy(),
            cmd,
            None,
        );
        matches!(
            crate::hook::prompt_choice_optional(&disclosure)?,
            crate::hook::OptionalChoice::Run
        )
    };
    if run {
        println!("running {event} hook for {key}");
        crate::hook::run_hook(cmd, &cwd, source, event)?;
    } else if crate::hook::is_tty() && !dangerously_skip {
        println!("note: skipped {event} hook for {key}; {effect}");
    }
    Ok(())
}

/// Run an item's install hooks (HOOK-81, HOOK-86) as the final step of installing
/// it, in declaration order. Each entry is disclosed, prompted, and fails exactly
/// as the scalar shorthand does (HOOK-86): a non-zero exit aborts the loop and the
/// caller rolls the install back. An empty list is a no-op.
pub fn run_item_install_hooks(
    item: &CatalogItem,
    hooks: &[&crate::mindfile::ResolvedHook],
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> Result<()> {
    for hook in hooks {
        run_item_hook(
            "install",
            &item.key(),
            &item.source,
            &hook.run,
            store,
            commit,
            dangerously_skip,
        )?;
    }
    Ok(())
}

/// Run an item's uninstall hooks (HOOK-82, HOOK-86) before its store copy and
/// links go, in declaration order. A non-zero exit aborts the loop and the caller
/// leaves the item installed. An empty list is a no-op.
pub fn run_item_uninstall_hooks(
    item: &InstalledItem,
    hooks: &[&crate::mindfile::ResolvedHook],
    store: &Path,
    commit: &str,
    dangerously_skip: bool,
) -> Result<()> {
    for hook in hooks {
        run_item_hook(
            "uninstall",
            &item.key(),
            &item.source,
            &hook.run,
            store,
            commit,
            dangerously_skip,
        )?;
    }
    Ok(())
}

fn collect_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) -> Result<()> {
    let rd = std::fs::read_dir(dir).map_err(|e| MindError::io(dir, e))?;
    for entry in rd {
        let entry = entry.map_err(|e| MindError::io(dir, e))?;
        let path = entry.path();
        if path.is_dir() {
            collect_files(&path, out)?;
        } else {
            out.push(path);
        }
    }
    Ok(())
}

fn rename(from: &Path, to: &Path) -> Result<()> {
    std::fs::rename(from, to).map_err(|e| MindError::io(to, e))
}

/// Best-effort removal of a file, dir, or symlink; "not found" is success.
pub(crate) fn remove_path(path: &Path) -> Result<()> {
    let meta = match std::fs::symlink_metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => return Err(MindError::io(path, e)),
    };
    let res = if meta.is_dir() {
        std::fs::remove_dir_all(path)
    } else {
        std::fs::remove_file(path)
    };
    res.map_err(|e| MindError::io(path, e))
}

fn copy_recursive(src: &Path, dst: &Path) -> Result<()> {
    if src.is_dir() {
        mkdir_p(dst)?;
        let rd = std::fs::read_dir(src).map_err(|e| MindError::io(src, e))?;
        for entry in rd {
            let entry = entry.map_err(|e| MindError::io(src, e))?;
            let from = entry.path();
            let to = dst.join(entry.file_name());
            copy_recursive(&from, &to)?;
        }
    } else {
        if let Some(parent) = dst.parent() {
            mkdir_p(parent)?;
        }
        std::fs::copy(src, dst).map_err(|e| MindError::io(dst, e))?;
    }
    Ok(())
}

#[cfg(unix)]
fn symlink(target: &Path, link: &Path) -> Result<()> {
    std::os::unix::fs::symlink(target, link).map_err(|e| MindError::io(link, e))
}

#[cfg(not(unix))]
fn symlink(target: &Path, link: &Path) -> Result<()> {
    // On non-unix, fall back to a copy so the layout still works. Known
    // limitation: a copied link is not recognized as mind's own by the clobber
    // guard (`ensure_unoccupied` keys on "symlink into the store"), so reinstall
    // / upgrade over it reports `LinkOccupied`. mind is unix-first; see the
    // platform-limitation note in spec/lifecycle.md.
    copy_recursive(target, link)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ItemKind;
    use std::sync::atomic::{AtomicU32, Ordering};

    static N: AtomicU32 = AtomicU32::new(0);

    fn tool_item(build: &str, path: std::path::PathBuf) -> CatalogItem {
        CatalogItem {
            kind: ItemKind::Tool,
            name: "t".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path,
            description: None,
            link_rel: None,
            bin: None,
            build: Some(build.to_string()),
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        }
    }

    #[test]
    fn build_hook_is_skipped_without_a_tty() {
        // spec: HOOK-72
        // The test harness has no TTY, so the build hook must be skipped (the item
        // installs unbuilt): the command must not run, and the call still succeeds.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-build-skip-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        let marker = staging.join("built");
        let item = tool_item(
            &format!("touch {}", marker.display()),
            std::path::PathBuf::from("/src/tools/t"),
        );

        run_build_hook(&item, item.build.as_deref().unwrap(), &staging, "abc123").unwrap();
        assert!(
            !marker.exists(),
            "a non-TTY context must skip the build hook (HOOK-72)"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    // ---- DEP-6: `requires` validation in expand_references -----------------

    /// Build a minimal skill CatalogItem pointing at the given staging dir.
    fn skill_item_at(name: &str, path: std::path::PathBuf, requires: Vec<String>) -> CatalogItem {
        CatalogItem {
            kind: ItemKind::Skill,
            name: name.to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path,
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires,
            hooks: Vec::new(),
        }
    }

    fn agent_item_at(name: &str, path: std::path::PathBuf) -> CatalogItem {
        CatalogItem {
            kind: ItemKind::Agent,
            name: name.to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path,
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        }
    }

    #[test]
    fn requires_valid_entry_passes_validation() {
        // spec: DEP-6
        // A `requires: agent:test` entry that resolves to an existing sibling
        // must pass validation and allow expand_references to proceed.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging = std::env::temp_dir().join(format!("mind-req-ok-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        // A text file without any {{ so expand_references reaches the requires check
        // but skips file expansion.
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["agent:test".to_string()],
        );
        let test_agent = agent_item_at("test", std::path::PathBuf::from("/src/agents/test.md"));
        let siblings = vec![item.clone(), test_agent];

        let result = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"));
        assert!(
            result.is_ok(),
            "valid requires entry must not error: {result:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_typo_entry_is_bad_reference() {
        // spec: DEP-6
        // A `requires` entry naming a non-existent sibling is a BadReference.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-typo-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["agent:nonexistent".to_string()],
        );
        let siblings = vec![item.clone()]; // no "nonexistent" sibling

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { ref referent, .. }
                if referent.contains("agent:nonexistent")),
            "typo requires entry must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_source_qualified_entry_is_bad_reference() {
        // spec: DEP-6
        // A source-qualified `owner/repo#name` entry in `requires` is rejected as
        // a BadReference because `requires` is intra-source only (DEP-5).
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-cross-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["owner/repo#agent:test".to_string()],
        );
        let test_agent = agent_item_at("test", std::path::PathBuf::from("/src/agents/test.md"));
        let siblings = vec![item.clone(), test_agent];

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { .. }),
            "source-qualified requires entry must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_ambiguous_bare_name_is_bad_reference() {
        // spec: DEP-6
        // A bare `name` that matches siblings of two different kinds and no kind
        // qualifier is supplied is ambiguous and must be a BadReference.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-ambig-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["shared".to_string()], // bare name matches agent:shared AND rule:shared
        );
        let agent = CatalogItem {
            kind: ItemKind::Agent,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/agents/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        };
        let rule = CatalogItem {
            kind: ItemKind::Rule,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/rules/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        };
        let siblings = vec![item.clone(), agent, rule];

        let err = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"))
            .unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::BadReference { ref referent, .. }
                if referent.contains("shared")),
            "ambiguous bare-name requires entry must be BadReference: {err}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_kind_qualified_among_two_same_name_siblings_is_accepted() {
        // spec: DEP-5 DEP-6
        // The other side of the ambiguity boundary: when two siblings share a
        // bare name across kinds, a `kind:name` qualifier resolves to exactly one
        // and MUST pass validation (it is not falsely flagged ambiguous). This
        // pins that the `matches.len() > 1 && r.kind.is_none()` guard does NOT
        // fire once the kind narrows the candidate set to one.
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-kindok-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        // `agent:shared` uniquely picks the agent, even though a rule:shared also
        // exists; the bare name alone would be ambiguous.
        let item = skill_item_at(
            "review",
            std::path::PathBuf::from("/src/skills/review"),
            vec!["agent:shared".to_string()],
        );
        let agent = CatalogItem {
            kind: ItemKind::Agent,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/agents/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        };
        let rule = CatalogItem {
            kind: ItemKind::Rule,
            name: "shared".to_string(),
            source: "local/test/repo".to_string(),
            prefix: None,
            path: std::path::PathBuf::from("/src/rules/shared.md"),
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        };
        let siblings = vec![item.clone(), agent, rule];

        let result = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"));
        assert!(
            result.is_ok(),
            "a kind-qualified ref that uniquely matches one of two same-name \
             siblings must pass validation, not be flagged ambiguous: {result:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }

    #[test]
    fn requires_self_reference_resolves_and_is_accepted() {
        // spec: DEP-6
        // An item whose `requires` names its own bare name resolves to itself (it
        // is a sibling of itself in the passed list) and must NOT error: the
        // validation only rejects zero matches or an ambiguous bare name, and a
        // self-reference is a single, unambiguous match. (The pure resolver in
        // deps.rs separately drops the trivial self-edge.)
        let n = N.fetch_add(1, Ordering::SeqCst);
        let staging =
            std::env::temp_dir().join(format!("mind-req-self-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&staging);
        std::fs::create_dir_all(&staging).unwrap();
        std::fs::write(staging.join("SKILL.md"), "# hello\n").unwrap();

        let item = skill_item_at(
            "solo",
            std::path::PathBuf::from("/src/skills/solo"),
            vec!["skill:solo".to_string()],
        );
        let siblings = vec![item.clone()];

        let result = expand_references(&staging, &item, &siblings, std::path::Path::new("/store"));
        assert!(
            result.is_ok(),
            "a self-requires must resolve to the item itself and not error: {result:?}"
        );
        let _ = std::fs::remove_dir_all(&staging);
    }
}