mind-cli 0.6.1

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
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
//! The optional `mind.toml` a source repo may place at its root to declare its
//! inventory explicitly, instead of relying on convention scanning.
//!
//! Everything is optional. A repo with no `mind.toml` is scanned by convention.
//! A repo with only `[source]` metadata still gets convention scanning. A repo
//! that declares `[[items]]` or `[discover]` opts out of convention scanning and
//! becomes authoritative for its own inventory.

use std::path::Path;

use serde::Deserialize;

use crate::error::{MindError, Result};
use crate::source::Pin;

/// The lifecycle event a hook is bound to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookEvent {
    Install,
    Uninstall,
}

/// One raw `[[hooks]]` entry as deserialized from `mind.toml`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Hook {
    pub run: String,
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub optional: bool,
    /// Raw event string; validated by `resolved_hooks` ("install" | "uninstall",
    /// default "install"). Kept as a string so an unknown value is a clear
    /// mind.toml schema error rather than an opaque serde failure.
    #[serde(default)]
    pub event: Option<String>,
}

/// A validated, normalized hook ready for execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedHook {
    pub run: String,
    pub name: Option<String>,
    pub optional: bool,
    pub event: HookEvent,
}

impl ResolvedHook {
    /// The label shown in disclosures: the name if non-empty, else the command.
    /// An empty or whitespace-only name is treated as absent (HOOK-51).
    pub fn label(&self) -> &str {
        match self.name.as_deref() {
            Some(n) if !n.trim().is_empty() => n,
            _ => &self.run,
        }
    }
}

/// The parsed `mind.toml`.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MindToml {
    #[serde(default)]
    pub source: SourceMeta,
    /// Explicit inventory; authoritative when non-empty.
    #[serde(default)]
    pub items: Vec<ItemDecl>,
    /// Glob-based discovery; authoritative when present.
    pub discover: Option<Discover>,
    /// Declared hooks in declaration order (HOOK-51).
    #[serde(default)]
    pub hooks: Vec<Hook>,
}

/// Repo-level metadata.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceMeta {
    pub description: Option<String>,
    /// An install hook (HOOK-1): a shell command the maintainer declares to build
    /// or install the tooling this source's items rely on. Run on `meld` after
    /// checkout, gated by a safety prompt (see spec/install-hooks.md). `None` when
    /// the source declares no hook.
    pub install: Option<String>,
    /// Namespace prefix applied to every item from this source (see
    /// [`crate::namespace`]). A consumer `meld --as` overrides it.
    pub prefix: Option<String>,
    /// The minimum `mind` version this repo expects. Enforced at scan/meld time:
    /// a source requiring a newer `mind` than the one running is rejected (see
    /// [`version_at_least`] and `catalog::scan`).
    #[serde(rename = "min-mind-version")]
    pub min_mind_version: Option<String>,
    /// Pin directive: track a named branch (DSC-41).
    #[serde(rename = "follow-branch")]
    pub follow_branch: Option<String>,
    /// Pin directive: fix to a tag (DSC-41).
    #[serde(rename = "pin-tag")]
    pub pin_tag: Option<String>,
    /// Pin directive: fix to a specific commit (DSC-41).
    #[serde(rename = "pin-ref")]
    pub pin_ref: Option<String>,
    /// Convention scan roots (DSC-50). When set, convention discovery scans
    /// under each listed repo-root-relative directory instead of the repo root.
    #[serde(default)]
    pub roots: Option<Vec<String>>,
}

impl SourceMeta {
    /// Return the single pin declared by this `[source]` section, or `None`
    /// if none is declared. More than one declared pin is a `MindToml` error
    /// (DSC-41).
    pub fn pin_directive(&self, toml_path: &Path) -> Result<Option<Pin>> {
        // Collect which directives are set so we can detect conflicts and give
        // a useful error message naming both conflicting keys.
        let mut set: Vec<(&str, Pin)> = Vec::new();
        if let Some(b) = &self.follow_branch {
            set.push(("follow-branch", Pin::FollowBranch(b.clone())));
        }
        if let Some(t) = &self.pin_tag {
            set.push(("pin-tag", Pin::Tag(t.clone())));
        }
        if let Some(r) = &self.pin_ref {
            set.push(("pin-ref", Pin::Ref(r.clone())));
        }
        match set.len() {
            0 => Ok(None),
            1 => Ok(Some(set.remove(0).1)),
            _ => {
                let names: Vec<&str> = set.iter().map(|(k, _)| *k).collect();
                Err(MindError::MindToml {
                    path: toml_path.to_path_buf(),
                    msg: format!(
                        "conflicting pin directives: {}; declare at most one of follow-branch, pin-tag, pin-ref",
                        names.join(", ")
                    ),
                })
            }
        }
    }
}

/// One explicitly declared item.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ItemDecl {
    /// `skill`, `agent`, `rule`, or `tool`.
    pub kind: String,
    pub name: String,
    /// Path to the item, relative to the repo root (a dir for skills/tools).
    pub path: String,
    /// Optional override for where to link it under `~/.claude`
    /// (relative to the claude home, e.g. `rules/style.md`).
    pub link: Option<String>,
    /// Optional description override (else taken from frontmatter).
    pub description: Option<String>,
    /// A tool's entrypoint, relative to its dir (what `{{tools:name}}` resolves
    /// to). Tool items only; else a `mind.toml` schema error.
    pub bin: Option<String>,
    /// A tool's per-item build command, run in staging at install. Tool items
    /// only; else a `mind.toml` schema error.
    pub build: Option<String>,
    /// An item install hook (HOOK-80): a shell command run on the host as the
    /// final step of installing this item (after the store swap and links), for
    /// side effects (set up a venv, register a helper). Valid on any kind. `None`
    /// means no install hook.
    pub install: Option<String>,
    /// An item uninstall hook (HOOK-80): a shell command run when this item is
    /// removed (at `forget`/`unmeld`/rename-on-upgrade), before its store copy
    /// and links are removed. Valid on any kind. `None` means no uninstall hook.
    pub uninstall: Option<String>,
    /// Item lifecycle hooks declared as an array (HOOK-86), the per-item analog
    /// of the source `[[hooks]]` array (HOOK-50): the field is `[[items.hooks]]`
    /// in `mind.toml`. Same fields/semantics as a source hook. The scalar
    /// `install`/`uninstall` above are folded in ahead of these (see
    /// [`ItemDecl::resolved_item_hooks`]).
    #[serde(default)]
    pub hooks: Vec<Hook>,
}

impl ItemDecl {
    /// Resolve this item's lifecycle hooks (HOOK-86) in execution order.
    ///
    /// Mirrors [`MindToml::resolved_hooks`]: the scalar `install` folds in as the
    /// first required install hook and the scalar `uninstall` as the first
    /// required uninstall hook (HOOK-80 shorthand), both ahead of the
    /// `[[items.hooks]]` entries, which are then validated and appended in
    /// declaration order. An empty/whitespace `run` is dropped (HOOK-3) and an
    /// unknown `event` is a `mind.toml` schema error.
    pub fn resolved_item_hooks(&self, toml_path: &std::path::Path) -> Result<Vec<ResolvedHook>> {
        let mut out: Vec<ResolvedHook> = Vec::new();

        // HOOK-86: fold the scalar install/uninstall shorthand in first, each as
        // a required hook of its event.
        for (scalar, event) in [
            (&self.install, HookEvent::Install),
            (&self.uninstall, HookEvent::Uninstall),
        ] {
            if let Some(cmd) = scalar {
                let trimmed = cmd.trim();
                if !trimmed.is_empty() {
                    out.push(ResolvedHook {
                        run: trimmed.to_owned(),
                        name: None,
                        optional: false,
                        event,
                    });
                }
            }
        }

        // HOOK-86: [[items.hooks]] entries in declaration order, validated the
        // same way as a source's [[hooks]].
        out.extend(self.resolved_item_array_hooks(toml_path)?);

        Ok(out)
    }

    /// Resolve the `[[items.hooks]]` array entries (HOOK-86), validated in
    /// declaration order. Returns only the array-declared hooks; the scalar
    /// `install`/`uninstall` fold-in is handled by the caller
    /// (`resolved_item_hooks`), which prepends those scalars ahead of this
    /// result.
    fn resolved_item_array_hooks(&self, toml_path: &std::path::Path) -> Result<Vec<ResolvedHook>> {
        let mut out: Vec<ResolvedHook> = Vec::new();
        for hook in &self.hooks {
            let run = hook.run.trim();
            if run.is_empty() {
                continue; // HOOK-3 generalized: skip blank run
            }
            let event = match hook.event.as_deref() {
                None | Some("install") => HookEvent::Install,
                Some("uninstall") => HookEvent::Uninstall,
                Some(e) => {
                    return Err(MindError::MindToml {
                        path: toml_path.to_path_buf(),
                        msg: format!("unknown hook event '{e}'; expected 'install' or 'uninstall'"),
                    });
                }
            };
            out.push(ResolvedHook {
                run: run.to_owned(),
                name: hook.name.clone(),
                optional: hook.optional,
                event,
            });
        }
        Ok(out)
    }
}

/// Glob-based discovery: per-kind include/exclude, plus nested sources.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Discover {
    #[serde(default)]
    pub skills: KindGlobs,
    #[serde(default)]
    pub agents: KindGlobs,
    #[serde(default)]
    pub rules: KindGlobs,
    /// Tool globs match the tool DIRECTORY (e.g. `packages/*/tool`), not an
    /// anchor file: the matched directory is the tool.
    #[serde(default)]
    pub tools: KindGlobs,
    /// Other sources this repo curates. Melding this repo recursively melds each
    /// (see commands::meld), so a `mind.toml` can act as a registry / super-source.
    #[serde(default)]
    pub sources: Vec<NestedSource>,
}

/// Include/exclude glob patterns for one kind, relative to the repo root. An
/// item matched by `include` is kept unless it is also matched by `exclude`.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct KindGlobs {
    #[serde(default)]
    pub include: Vec<String>,
    #[serde(default)]
    pub exclude: Vec<String>,
}

/// A source referenced by a curated super-source.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NestedSource {
    /// A repo spec, parsed exactly like a `meld` argument.
    pub source: String,
    /// Optional namespace to impose on the nested source (like `meld --as`).
    #[serde(rename = "as", default)]
    pub alias: Option<String>,
    /// When true, melding the super-source offers this nested source's items for
    /// install (the curator recommends installing it), instead of leaving them
    /// only registered and available. Default false (DSC-58).
    #[serde(default)]
    pub install: bool,
}

impl Discover {
    /// Whether this section declares item globs (as opposed to only nested
    /// sources). Item globs turn off convention discovery; a bare `sources` list
    /// does not.
    pub fn has_item_globs(&self) -> bool {
        !self.skills.include.is_empty()
            || !self.agents.include.is_empty()
            || !self.rules.include.is_empty()
            || !self.tools.include.is_empty()
    }
}

/// Whether `running` satisfies `>= required`, comparing dotted numeric version
/// components (a missing component counts as 0, so `0.2` == `0.2.0`). A
/// non-numeric component compares as 0, so a prerelease/build suffix is ignored.
pub fn version_at_least(running: &str, required: &str) -> bool {
    let parse = |v: &str| -> Vec<u64> {
        v.split('.')
            .map(|c| c.trim().parse::<u64>().unwrap_or(0))
            .collect()
    };
    let r = parse(running);
    let req = parse(required);
    for i in 0..r.len().max(req.len()) {
        let a = r.get(i).copied().unwrap_or(0);
        let b = req.get(i).copied().unwrap_or(0);
        if a != b {
            return a > b;
        }
    }
    true
}

impl MindToml {
    /// Load `mind.toml` from a repo root, returning `None` if absent.
    pub fn load(root: &Path) -> Result<Option<MindToml>> {
        let file = root.join("mind.toml");
        match std::fs::read_to_string(&file) {
            Ok(text) => {
                let parsed = toml::from_str(&text).map_err(|e| MindError::Toml {
                    path: file.clone(),
                    source: e,
                })?;
                Ok(Some(parsed))
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(e) => Err(MindError::io(&file, e)),
        }
    }

    /// Whether this file takes over item discovery (vs. leaving it to
    /// convention). Nested `[discover].sources` alone does not.
    pub fn is_authoritative(&self) -> bool {
        !self.items.is_empty() || self.discover.as_ref().is_some_and(|d| d.has_item_globs())
    }

    /// Return all hooks in resolved, normalized form.
    ///
    /// The legacy `[source].install` (HOOK-50 back-compat) folds in as the
    /// first required install hook when non-empty after trimming. Then each
    /// `[[hooks]]` entry is validated and appended in declaration order.
    /// Entries with an empty/whitespace `run` are silently dropped (HOOK-3).
    pub fn resolved_hooks(&self, toml_path: &std::path::Path) -> Result<Vec<ResolvedHook>> {
        let mut out: Vec<ResolvedHook> = Vec::new();

        // HOOK-50: fold legacy [source].install into a required install hook.
        if let Some(cmd) = &self.source.install {
            let trimmed = cmd.trim();
            if !trimmed.is_empty() {
                out.push(ResolvedHook {
                    run: trimmed.to_owned(),
                    name: None,
                    optional: false,
                    event: HookEvent::Install,
                });
            }
        }

        // HOOK-51: [[hooks]] entries in declaration order.
        for hook in &self.hooks {
            let run = hook.run.trim();
            if run.is_empty() {
                continue; // HOOK-3 generalized: skip blank run
            }
            let event = match hook.event.as_deref() {
                None | Some("install") => HookEvent::Install,
                Some("uninstall") => HookEvent::Uninstall,
                Some(e) => {
                    return Err(MindError::MindToml {
                        path: toml_path.to_path_buf(),
                        msg: format!("unknown hook event '{e}'; expected 'install' or 'uninstall'"),
                    });
                }
            };
            out.push(ResolvedHook {
                run: run.to_owned(),
                name: hook.name.clone(),
                optional: hook.optional,
                event,
            });
        }

        Ok(out)
    }
}

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

    #[test]
    fn version_comparison_orders_dotted_components() {
        // spec: DSC-40
        assert!(version_at_least("0.2.0", "0.2"));
        assert!(version_at_least("0.2", "0.2.0"));
        assert!(version_at_least("1.0.0", "0.9.9"));
        assert!(version_at_least("0.10.0", "0.9.0"));
        assert!(!version_at_least("0.1.0", "0.2"));
        assert!(!version_at_least("0.1.0", "0.1.1"));
        // Non-numeric / suffix components count as 0.
        assert!(version_at_least("0.2.0-rc1", "0.2"));
    }

    #[test]
    fn source_install_hook_parses() {
        // spec: HOOK-1
        let toml = r#"
            [source]
            description = "tools"
            install = "make build && make install"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        assert_eq!(
            parsed.source.install.as_deref(),
            Some("make build && make install")
        );

        // Absent install => None.
        let none: MindToml = toml::from_str("[source]\ndescription = \"x\"\n").unwrap();
        assert_eq!(none.source.install, None);
    }

    #[test]
    fn pin_directive_none_when_no_fields_set() {
        // spec: DSC-41
        let meta = SourceMeta::default();
        let pin = meta
            .pin_directive(Path::new("mind.toml"))
            .expect("should not error");
        assert!(pin.is_none(), "no directive set => None");
    }

    #[test]
    fn pin_directive_follow_branch() {
        // spec: DSC-41
        let meta = SourceMeta {
            follow_branch: Some("develop".into()),
            ..Default::default()
        };
        let pin = meta
            .pin_directive(Path::new("mind.toml"))
            .expect("no error");
        assert_eq!(pin, Some(Pin::FollowBranch("develop".into())));
    }

    #[test]
    fn pin_directive_tag() {
        // spec: DSC-41
        let meta = SourceMeta {
            pin_tag: Some("v2.0".into()),
            ..Default::default()
        };
        let pin = meta
            .pin_directive(Path::new("mind.toml"))
            .expect("no error");
        assert_eq!(pin, Some(Pin::Tag("v2.0".into())));
    }

    #[test]
    fn pin_directive_ref() {
        // spec: DSC-41
        let meta = SourceMeta {
            pin_ref: Some("abc123".into()),
            ..Default::default()
        };
        let pin = meta
            .pin_directive(Path::new("mind.toml"))
            .expect("no error");
        assert_eq!(pin, Some(Pin::Ref("abc123".into())));
    }

    #[test]
    fn pin_directive_conflict_is_an_error() {
        // spec: DSC-41 — more than one directive is a MindToml error
        let meta = SourceMeta {
            follow_branch: Some("main".into()),
            pin_tag: Some("v1.0".into()),
            ..Default::default()
        };
        let result = meta.pin_directive(Path::new("/repo/mind.toml"));
        assert!(result.is_err(), "conflicting directives must error");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("conflicting pin"),
            "expected 'conflicting pin' in: {err_msg}"
        );
    }

    // ----- HOOK-51: [[hooks]] multi-hook schema -----

    #[test]
    fn hooks_parse_fields_correctly() {
        // spec: HOOK-51
        let toml = r#"
            [[hooks]]
            run = "make build"
            name = "Build step"
            optional = true
            event = "install"

            [[hooks]]
            run = "make clean"
            event = "uninstall"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        assert_eq!(parsed.hooks.len(), 2);

        let h0 = &parsed.hooks[0];
        assert_eq!(h0.run, "make build");
        assert_eq!(h0.name.as_deref(), Some("Build step"));
        assert!(h0.optional);
        assert_eq!(h0.event.as_deref(), Some("install"));

        let h1 = &parsed.hooks[1];
        assert_eq!(h1.run, "make clean");
        assert_eq!(h1.name, None);
        assert!(!h1.optional);
        assert_eq!(h1.event.as_deref(), Some("uninstall"));
    }

    #[test]
    fn hooks_preserve_declaration_order() {
        // spec: HOOK-51
        let toml = r#"
            [[hooks]]
            run = "first"

            [[hooks]]
            run = "second"

            [[hooks]]
            run = "third"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        assert_eq!(resolved.len(), 3);
        assert_eq!(resolved[0].run, "first");
        assert_eq!(resolved[1].run, "second");
        assert_eq!(resolved[2].run, "third");
    }

    #[test]
    fn legacy_install_folds_in_as_first_required_install_hook() {
        // spec: HOOK-50
        let toml = r#"
            [source]
            install = "make legacy"

            [[hooks]]
            run = "npm install"
            event = "install"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        assert_eq!(resolved.len(), 2);

        // Legacy hook is first.
        assert_eq!(resolved[0].run, "make legacy");
        assert_eq!(resolved[0].event, HookEvent::Install);
        assert!(!resolved[0].optional);
        assert_eq!(resolved[0].name, None);

        // Declared hook follows.
        assert_eq!(resolved[1].run, "npm install");
        assert_eq!(resolved[1].event, HookEvent::Install);
    }

    #[test]
    fn legacy_install_only_no_hooks_table() {
        // spec: HOOK-50 — install field alone, no [[hooks]] section
        let toml = r#"
            [source]
            install = "make build && make install"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].run, "make build && make install");
        assert_eq!(resolved[0].event, HookEvent::Install);
        assert!(!resolved[0].optional);
    }

    #[test]
    fn default_event_is_install() {
        // spec: HOOK-51
        let toml = r#"
            [[hooks]]
            run = "setup.sh"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].event, HookEvent::Install);
    }

    #[test]
    fn explicit_uninstall_event_resolves() {
        // spec: HOOK-51
        let toml = r#"
            [[hooks]]
            run = "teardown.sh"
            event = "uninstall"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].event, HookEvent::Uninstall);
    }

    #[test]
    fn unknown_event_returns_mind_toml_error() {
        // spec: HOOK-51
        let toml = r#"
            [[hooks]]
            run = "do-something.sh"
            event = "build"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let toml_path = Path::new("/repo/mind.toml");
        let result = parsed.resolved_hooks(toml_path);
        assert!(result.is_err(), "unknown event must error");
        let err = result.unwrap_err();
        // Must be a MindToml variant.
        match err {
            MindError::MindToml { path, msg } => {
                assert_eq!(path, toml_path);
                assert!(
                    msg.contains("build"),
                    "error message should mention the bad value: {msg}"
                );
                assert!(
                    msg.contains("install") && msg.contains("uninstall"),
                    "error message should mention valid values: {msg}"
                );
            }
            other => panic!("expected MindError::MindToml, got: {other:?}"),
        }
    }

    #[test]
    fn empty_run_in_hooks_is_dropped() {
        // spec: HOOK-51 (HOOK-3 generalized): blank run entries are silently skipped
        let toml = r#"
            [[hooks]]
            run = ""

            [[hooks]]
            run = "   "

            [[hooks]]
            run = "real-command"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].run, "real-command");
    }

    #[test]
    fn whitespace_legacy_install_contributes_nothing() {
        // spec: HOOK-50 — whitespace-only install is ignored
        let toml = r#"
            [source]
            install = "   "

            [[hooks]]
            run = "npm ci"
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        // Whitespace install contributes nothing; only the declared hook remains.
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].run, "npm ci");
    }

    #[test]
    fn resolved_hook_label_returns_name_when_set() {
        // spec: HOOK-51
        let hook = ResolvedHook {
            run: "make build".into(),
            name: Some("Build step".into()),
            optional: false,
            event: HookEvent::Install,
        };
        assert_eq!(hook.label(), "Build step");
    }

    #[test]
    fn resolved_hook_label_falls_back_to_command() {
        // spec: HOOK-51
        let hook = ResolvedHook {
            run: "make build".into(),
            name: None,
            optional: false,
            event: HookEvent::Install,
        };
        assert_eq!(hook.label(), "make build");
    }

    #[test]
    fn label_treats_empty_and_whitespace_name_as_absent() {
        // spec: HOOK-51
        let make_hook = |name: Option<&str>| ResolvedHook {
            run: "make build".into(),
            name: name.map(str::to_owned),
            optional: false,
            event: HookEvent::Install,
        };

        // Non-empty name is used as-is.
        assert_eq!(make_hook(Some("Build")).label(), "Build");
        // Empty string falls back to run.
        assert_eq!(make_hook(Some("")).label(), "make build");
        // Whitespace-only falls back to run.
        assert_eq!(make_hook(Some("   ")).label(), "make build");
        // None falls back to run.
        assert_eq!(make_hook(None).label(), "make build");
    }

    #[test]
    fn hooks_whitespace_run_is_trimmed() {
        // spec: HOOK-51 — leading/trailing whitespace in run is trimmed
        let toml = r#"
            [[hooks]]
            run = "  npm install  "
        "#;
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let dummy = Path::new("mind.toml");
        let resolved = parsed.resolved_hooks(dummy).expect("resolve");
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].run, "npm install");
    }

    // ----- HOOK-86: [[items.hooks]] item-level array -----

    /// Parse a `mind.toml` and return its first item's resolved hooks.
    fn first_item_hooks(toml: &str) -> Result<Vec<ResolvedHook>> {
        let parsed: MindToml = toml::from_str(toml).expect("parse");
        let item = &parsed.items[0];
        item.resolved_item_hooks(Path::new("/repo/mind.toml"))
    }

    #[test]
    fn item_hooks_array_parses_and_preserves_order() {
        // spec: HOOK-86
        let toml = r#"
            [[items]]
            kind = "tool"
            name = "helper"
            path = "tools/helper"

            [[items.hooks]]
            run = "first"
            name = "Step one"

            [[items.hooks]]
            run = "second"
            optional = true
            event = "install"

            [[items.hooks]]
            run = "teardown"
            event = "uninstall"
        "#;
        let resolved = first_item_hooks(toml).expect("resolve");
        assert_eq!(resolved.len(), 3);
        assert_eq!(resolved[0].run, "first");
        assert_eq!(resolved[0].name.as_deref(), Some("Step one"));
        assert!(!resolved[0].optional);
        assert_eq!(resolved[0].event, HookEvent::Install);
        assert_eq!(resolved[1].run, "second");
        assert!(resolved[1].optional);
        assert_eq!(resolved[1].event, HookEvent::Install);
        assert_eq!(resolved[2].run, "teardown");
        assert_eq!(resolved[2].event, HookEvent::Uninstall);
    }

    #[test]
    fn item_scalar_install_uninstall_fold_in_ahead_of_array() {
        // spec: HOOK-86 — scalar install/uninstall are the one-required-hook
        // shorthand, folded in ahead of any [[items.hooks]] entries.
        let toml = r#"
            [[items]]
            kind = "tool"
            name = "helper"
            path = "tools/helper"
            install = "scalar-install"
            uninstall = "scalar-uninstall"

            [[items.hooks]]
            run = "array-install"
            event = "install"

            [[items.hooks]]
            run = "array-uninstall"
            event = "uninstall"
        "#;
        let resolved = first_item_hooks(toml).expect("resolve");
        assert_eq!(resolved.len(), 4);
        // Scalar install first, then scalar uninstall, then the array entries.
        assert_eq!(resolved[0].run, "scalar-install");
        assert_eq!(resolved[0].event, HookEvent::Install);
        assert!(!resolved[0].optional);
        assert_eq!(resolved[0].name, None);
        assert_eq!(resolved[1].run, "scalar-uninstall");
        assert_eq!(resolved[1].event, HookEvent::Uninstall);
        assert!(!resolved[1].optional);
        assert_eq!(resolved[2].run, "array-install");
        assert_eq!(resolved[3].run, "array-uninstall");
    }

    #[test]
    fn item_scalar_only_yields_one_required_hook_each() {
        // spec: HOOK-86 — with no array, the scalars alone resolve to one
        // required hook of each event.
        let toml = r#"
            [[items]]
            kind = "rule"
            name = "style"
            path = "guidelines/style.md"
            install = "set-up"
            uninstall = "tear-down"
        "#;
        let resolved = first_item_hooks(toml).expect("resolve");
        assert_eq!(resolved.len(), 2);
        assert_eq!(resolved[0].run, "set-up");
        assert_eq!(resolved[0].event, HookEvent::Install);
        assert_eq!(resolved[1].run, "tear-down");
        assert_eq!(resolved[1].event, HookEvent::Uninstall);
    }

    #[test]
    fn item_hooks_unknown_event_is_mind_toml_error() {
        // spec: HOOK-86 — same validation as a source [[hooks]] (HOOK-51).
        let toml = r#"
            [[items]]
            kind = "tool"
            name = "helper"
            path = "tools/helper"

            [[items.hooks]]
            run = "do-something"
            event = "build"
        "#;
        let err = first_item_hooks(toml).unwrap_err();
        match err {
            MindError::MindToml { path, msg } => {
                assert_eq!(path, Path::new("/repo/mind.toml"));
                assert!(msg.contains("build"), "names the bad value: {msg}");
                assert!(
                    msg.contains("install") && msg.contains("uninstall"),
                    "names the legal set: {msg}"
                );
            }
            other => panic!("expected MindError::MindToml, got: {other:?}"),
        }
    }

    #[test]
    fn item_hooks_empty_run_is_dropped() {
        // spec: HOOK-86 — empty/whitespace run entries are silently dropped
        // (HOOK-3), as for a source hook.
        let toml = r#"
            [[items]]
            kind = "tool"
            name = "helper"
            path = "tools/helper"

            [[items.hooks]]
            run = ""

            [[items.hooks]]
            run = "   "

            [[items.hooks]]
            run = "real-command"
        "#;
        let resolved = first_item_hooks(toml).expect("resolve");
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].run, "real-command");
    }

    #[test]
    fn item_scalar_whitespace_contributes_nothing() {
        // spec: HOOK-86 — a whitespace-only scalar install folds in nothing.
        let toml = r#"
            [[items]]
            kind = "tool"
            name = "helper"
            path = "tools/helper"
            install = "   "

            [[items.hooks]]
            run = "array-install"
        "#;
        let resolved = first_item_hooks(toml).expect("resolve");
        assert_eq!(resolved.len(), 1);
        assert_eq!(resolved[0].run, "array-install");
    }
}