mind-cli 0.7.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
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
//! End-to-end tests for item-level lifecycle hooks: the `[[items.hooks]]` array
//! (HOOK-86), nested teardown ordering at `unmeld` (HOOK-87), and the
//! prefix-gated `init-source` unguarded-reference advisory (INIT-9).
//!
//! These drive the real `mind` binary against a hermetic, network-free fixture
//! (a local git repo melded by filesystem path, with MIND_HOME/CLAUDE_HOME
//! pointed at temp dirs), exactly as `tests/cli.rs` does. Where a non-TTY test
//! needs the hooks to actually run, it passes
//! `--dangerously-skip-install-hook-check` (HOOK-23/83).

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU32, Ordering};

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

/// A throwaway environment: a source git repo plus isolated MIND_HOME/CLAUDE_HOME.
struct Sandbox {
    base: PathBuf,
    source: PathBuf,
    mind_home: PathBuf,
    claude_home: PathBuf,
}

struct Run {
    stdout: String,
    stderr: String,
    success: bool,
}

impl Sandbox {
    /// A source repo named `name` with no committed items yet (the test seeds
    /// its own files and `mind.toml`).
    fn new(name: &str) -> Sandbox {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-itlc-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let source = base.join(name);
        let sb = Sandbox {
            base: base.clone(),
            source: source.clone(),
            mind_home: base.join("mind"),
            claude_home: base.join("claude"),
        };
        write(&source.join("README.md"), "# fixture\n");
        git(&source, &["-c", "init.defaultBranch=main", "init", "-q"]);
        git(&source, &["config", "user.email", "t@t"]);
        git(&source, &["config", "user.name", "t"]);
        git(&source, &["add", "-A"]);
        git(&source, &["commit", "-qm", "initial"]);
        sb
    }

    fn mind(&self, args: &[&str]) -> Run {
        let out = Command::new(env!("CARGO_BIN_EXE_mind"))
            .args(args)
            .env("MIND_HOME", &self.mind_home)
            .env("CLAUDE_HOME", &self.claude_home)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::null())
            .output()
            .expect("run mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    }

    /// Run `mind` with its working directory set to `cwd` (for `init-source .`).
    fn mind_cwd(&self, args: &[&str], cwd: &Path) -> Run {
        let out = Command::new(env!("CARGO_BIN_EXE_mind"))
            .args(args)
            .current_dir(cwd)
            .env("MIND_HOME", &self.mind_home)
            .env("CLAUDE_HOME", &self.claude_home)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::null())
            .output()
            .expect("run mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    }

    fn write_and_commit(&self, rel: &str, contents: &str) {
        write(&self.source.join(rel), contents);
        git(&self.source, &["add", "-A"]);
        git(&self.source, &["commit", "-qm", "fixture"]);
    }

    fn source_spec(&self) -> String {
        self.source.to_string_lossy().into_owned()
    }
}

impl Drop for Sandbox {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.base);
    }
}

fn write(path: &Path, contents: &str) {
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, contents).unwrap();
}

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .args(args)
        .current_dir(dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("run git");
    assert!(status.success(), "git {args:?} failed in {dir:?}");
}

/// Read a log file the hooks append to, returning its non-empty lines in order.
fn read_log(path: &Path) -> Vec<String> {
    std::fs::read_to_string(path)
        .unwrap_or_default()
        .lines()
        .map(str::to_owned)
        .filter(|l| !l.is_empty())
        .collect()
}

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

#[test]
fn item_hooks_array_runs_install_then_uninstall_in_declaration_order() {
    // spec: HOOK-86
    // An item declaring multiple [[items.hooks]] (two install, two uninstall)
    // runs each in declaration order at install (learn) and removal (forget).
    // Each hook appends a tagged line to a shared log; the order is asserted.
    let sb = Sandbox::new("arr");
    let log = sb.base.join("order.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    // Two install hooks and two uninstall hooks, plus a named one, interleaved so
    // declaration order (not event grouping) is what we observe per event.
    let toml = format!(
        concat!(
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "\n",
            "[[items.hooks]]\n",
            "run = \"echo i1 >> {lg}\"\n",
            "name = \"first install\"\n",
            "event = \"install\"\n",
            "\n",
            "[[items.hooks]]\n",
            "run = \"echo u1 >> {lg}\"\n",
            "event = \"uninstall\"\n",
            "\n",
            "[[items.hooks]]\n",
            "run = \"echo i2 >> {lg}\"\n",
            "event = \"install\"\n",
            "\n",
            "[[items.hooks]]\n",
            "run = \"echo u2 >> {lg}\"\n",
            "event = \"uninstall\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);
    let learn = sb.mind(&[
        "learn",
        "skill:greet",
        "--dangerously-skip-install-hook-check",
    ]);
    assert!(
        learn.success,
        "learn should run both install hooks: {} {}",
        learn.stdout, learn.stderr
    );
    // Only the install hooks ran, in declaration order (i1 before i2).
    assert_eq!(read_log(&log), vec!["i1", "i2"], "install hooks in order");

    let forget = sb.mind(&[
        "forget",
        "skill:greet",
        "--dangerously-skip-install-hook-check",
    ]);
    assert!(
        forget.success,
        "forget should run both uninstall hooks: {} {}",
        forget.stdout, forget.stderr
    );
    // The uninstall hooks appended after the install ones, in declaration order.
    assert_eq!(
        read_log(&log),
        vec!["i1", "i2", "u1", "u2"],
        "uninstall hooks run in declaration order after install"
    );
    assert!(
        !sb.mind_home.join("store/skill/greet").exists(),
        "item removed after its uninstall hooks"
    );
}

#[test]
fn scalar_install_uninstall_still_work_as_one_required_hook_each() {
    // spec: HOOK-86
    // The scalar install/uninstall keys remain the one-required-hook shorthand:
    // an item declaring only the scalars runs each at the matching lifecycle step.
    let sb = Sandbox::new("scal");
    let log = sb.base.join("scalar.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    let toml = format!(
        concat!(
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "install = \"echo SCALAR-INSTALL >> {lg}\"\n",
            "uninstall = \"echo SCALAR-UNINSTALL >> {lg}\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);
    assert!(
        sb.mind(&[
            "learn",
            "skill:greet",
            "--dangerously-skip-install-hook-check"
        ])
        .success
    );
    assert_eq!(read_log(&log), vec!["SCALAR-INSTALL"], "scalar install ran");

    assert!(
        sb.mind(&[
            "forget",
            "skill:greet",
            "--dangerously-skip-install-hook-check"
        ])
        .success
    );
    assert_eq!(
        read_log(&log),
        vec!["SCALAR-INSTALL", "SCALAR-UNINSTALL"],
        "scalar uninstall ran on forget"
    );
}

// ---------------------------------------------------------------------------
// HOOK-87: nested teardown order (item uninstall before source uninstall)
// ---------------------------------------------------------------------------

#[test]
fn unmeld_runs_item_uninstall_hooks_before_source_uninstall_hooks() {
    // spec: HOOK-87
    // Teardown reverses install: at unmeld each installed item's uninstall hooks
    // run BEFORE the source's uninstall hooks. Each hook appends a tagged line to
    // a shared log; the item line must precede the source line.
    let sb = Sandbox::new("nest");
    let log = sb.base.join("teardown.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    // One item with an uninstall hook, plus a source-level uninstall hook.
    let toml = format!(
        concat!(
            "[[hooks]]\n",
            "run = \"echo SOURCE-UNINSTALL >> {lg}\"\n",
            "event = \"uninstall\"\n",
            "\n",
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "uninstall = \"echo ITEM-UNINSTALL >> {lg}\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    // Register and install the item (link-only meld so the source hook does not
    // run at meld; the item install needs no hook here).
    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);
    assert!(
        sb.mind(&[
            "learn",
            "skill:greet",
            "--dangerously-skip-install-hook-check"
        ])
        .success,
        "item must install before unmeld"
    );
    assert!(read_log(&log).is_empty(), "no teardown hooks at meld/learn");

    // unmeld: the item's uninstall hook then the source's uninstall hook.
    let unmeld = sb.mind(&["unmeld", "nest", "--dangerously-skip-install-hook-check"]);
    assert!(
        unmeld.success,
        "unmeld should succeed: {} {}",
        unmeld.stdout, unmeld.stderr
    );
    assert_eq!(
        read_log(&log),
        vec!["ITEM-UNINSTALL", "SOURCE-UNINSTALL"],
        "item uninstall hook must fire before the source uninstall hook"
    );

    // The source is gone.
    let sources = sb.mind(&["recall", "--sources"]).stdout;
    assert!(
        !sources.contains("nest"),
        "source must be removed after unmeld: {sources}"
    );
}

#[test]
fn unmeld_non_tty_skips_hooks_but_still_removes_source_and_items() {
    // spec: HOOK-87
    // A non-TTY `unmeld` WITHOUT --dangerously-skip-install-hook-check takes the
    // HOOK-22 skip path for every hook (item AND source uninstall), yet the source
    // is still removed and the item is still torn down. No hook side effect lands.
    let sb = Sandbox::new("ntty");
    let log = sb.base.join("skip.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    let toml = format!(
        concat!(
            "[[hooks]]\n",
            "run = \"echo SOURCE-UNINSTALL >> {lg}\"\n",
            "event = \"uninstall\"\n",
            "\n",
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "uninstall = \"echo ITEM-UNINSTALL >> {lg}\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);
    assert!(
        sb.mind(&[
            "learn",
            "skill:greet",
            "--dangerously-skip-install-hook-check"
        ])
        .success
    );
    assert!(
        sb.mind_home.join("store/skill/greet").exists(),
        "item installed before unmeld"
    );

    // No --dangerously-skip flag: non-TTY (stdin is /dev/null) skips every hook.
    let unmeld = sb.mind(&["unmeld", "ntty"]);
    assert!(
        unmeld.success,
        "non-TTY unmeld still succeeds: {} {}",
        unmeld.stdout, unmeld.stderr
    );
    // HOOK-22: every hook was skipped, so NOTHING was appended to the log.
    assert!(
        read_log(&log).is_empty(),
        "non-TTY must skip both item and source uninstall hooks: {:?}",
        read_log(&log)
    );
    // But the teardown still happened: item removed, source gone.
    assert!(
        !sb.mind_home.join("store/skill/greet").exists(),
        "item must still be removed even though its uninstall hook was skipped"
    );
    let sources = sb.mind(&["recall", "--sources"]).stdout;
    assert!(
        !sources.contains("ntty"),
        "source must still be removed: {sources}"
    );
}

#[test]
fn unmeld_yes_runs_item_uninstall_hooks_for_multiple_items_before_source() {
    // spec: HOOK-87
    // A multi-item `unmeld --yes` (bypassing the CLI-42 confirm) runs EACH item's
    // uninstall hooks before the source's uninstall hook. Two items each append a
    // tagged line; both must precede the source line.
    let sb = Sandbox::new("multi");
    let log = sb.base.join("multi.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/alpha/SKILL.md"),
        "---\ndescription: alpha\n---\n# alpha\n",
    );
    write(
        &sb.source.join("skills/beta/SKILL.md"),
        "---\ndescription: beta\n---\n# beta\n",
    );
    let toml = format!(
        concat!(
            "[[hooks]]\n",
            "run = \"echo SOURCE-UNINSTALL >> {lg}\"\n",
            "event = \"uninstall\"\n",
            "\n",
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"alpha\"\n",
            "path = \"skills/alpha\"\n",
            "uninstall = \"echo ITEM-ALPHA >> {lg}\"\n",
            "\n",
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"beta\"\n",
            "path = \"skills/beta\"\n",
            "uninstall = \"echo ITEM-BETA >> {lg}\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);
    assert!(
        sb.mind(&[
            "learn",
            "skill:alpha",
            "--dangerously-skip-install-hook-check"
        ])
        .success
    );
    assert!(
        sb.mind(&[
            "learn",
            "skill:beta",
            "--dangerously-skip-install-hook-check"
        ])
        .success
    );

    // --yes bypasses the multi-item CLI-42 confirm; --dangerously-skip runs hooks.
    let unmeld = sb.mind(&[
        "unmeld",
        "multi",
        "--yes",
        "--dangerously-skip-install-hook-check",
    ]);
    assert!(
        unmeld.success,
        "multi-item unmeld --yes should succeed: {} {}",
        unmeld.stdout, unmeld.stderr
    );
    let lines = read_log(&log);
    // Both item hooks must run before the source hook (HOOK-87 inner-to-outer).
    let src_pos = lines
        .iter()
        .position(|l| l == "SOURCE-UNINSTALL")
        .expect("source uninstall hook must run");
    let alpha_pos = lines
        .iter()
        .position(|l| l == "ITEM-ALPHA")
        .expect("alpha uninstall hook must run");
    let beta_pos = lines
        .iter()
        .position(|l| l == "ITEM-BETA")
        .expect("beta uninstall hook must run");
    assert!(
        alpha_pos < src_pos && beta_pos < src_pos,
        "both item uninstall hooks must precede the source uninstall hook: {lines:?}"
    );
    assert!(
        !sb.mind_home.join("store/skill/alpha").exists()
            && !sb.mind_home.join("store/skill/beta").exists(),
        "both items removed after unmeld"
    );
}

// spec: HOOK-87
// Install half of the nested order: source install hook runs BEFORE item
// install hooks. At `meld` (without --link-only), the source's `[[hooks]]`
// install entry runs first (in meld_recursive), and item install hooks run
// later (in install_melded_source -> learn). Both happen in a single
// `mind meld --yes --dangerously-skip-install-hook-check` invocation.
// The log therefore records SOURCE-INSTALL first, then ITEM-INSTALL.
#[test]
fn meld_runs_source_install_hook_before_item_install_hooks() {
    // spec: HOOK-87
    let sb = Sandbox::new("instord");
    let log = sb.base.join("install_order.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    // Source-level install hook (appends SOURCE-INSTALL) plus an item-level
    // install hook (appends ITEM-INSTALL). Under HOOK-87 the source hook must
    // appear before the item hook.
    let toml = format!(
        concat!(
            "[[hooks]]\n",
            "run = \"echo SOURCE-INSTALL >> {lg}\"\n",
            "event = \"install\"\n",
            "\n",
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "install = \"echo ITEM-INSTALL >> {lg}\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    // --yes: install items immediately after meld (no interactive prompt).
    // --dangerously-skip-install-hook-check: run all hooks unattended (HOOK-23).
    // Without --link-only so both the source and item install hooks fire.
    let meld = sb.mind(&[
        "meld",
        &spec,
        "--yes",
        "--dangerously-skip-install-hook-check",
    ]);
    assert!(
        meld.success,
        "meld --yes --dangerously-skip should succeed: {} {}",
        meld.stdout, meld.stderr
    );

    let lines = read_log(&log);
    // Both hooks must have run.
    assert!(
        lines.contains(&"SOURCE-INSTALL".to_string()),
        "source install hook must run: {lines:?}"
    );
    assert!(
        lines.contains(&"ITEM-INSTALL".to_string()),
        "item install hook must run: {lines:?}"
    );
    // HOOK-87: source install runs BEFORE item install (outer-to-inner).
    let src_pos = lines
        .iter()
        .position(|l| l == "SOURCE-INSTALL")
        .expect("SOURCE-INSTALL must appear in the log");
    let item_pos = lines
        .iter()
        .position(|l| l == "ITEM-INSTALL")
        .expect("ITEM-INSTALL must appear in the log");
    assert!(
        src_pos < item_pos,
        "source install hook (pos {src_pos}) must precede item install hook (pos {item_pos}): {lines:?}"
    );
    // Confirm the item was actually installed.
    assert!(
        sb.mind_home.join("store/skill/greet").exists(),
        "item must be in the store after a successful meld --yes"
    );
}

#[test]
fn unmeld_item_uninstall_hook_failure_leaves_source_melded() {
    // spec: HOOK-87
    // A non-zero exit from an item's uninstall hook is a hard stop (HOOK-53/82):
    // the unmeld stops, the failing item stays installed, and the source stays
    // melded. The source's own uninstall hook (which runs LAST) must NOT have run.
    let sb = Sandbox::new("failun");
    let log = sb.base.join("fail.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    // Item uninstall hook exits non-zero; the source uninstall hook would append
    // a line we assert never appears (it runs only after items succeed).
    let toml = format!(
        concat!(
            "[[hooks]]\n",
            "run = \"echo SOURCE-UNINSTALL >> {lg}\"\n",
            "event = \"uninstall\"\n",
            "\n",
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "uninstall = \"exit 7\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);
    assert!(
        sb.mind(&[
            "learn",
            "skill:greet",
            "--dangerously-skip-install-hook-check"
        ])
        .success
    );

    let unmeld = sb.mind(&["unmeld", "failun", "--dangerously-skip-install-hook-check"]);
    assert!(
        !unmeld.success,
        "an item uninstall-hook failure must fail the unmeld: {} {}",
        unmeld.stdout, unmeld.stderr
    );
    // HOOK-82: the failing item is left installed.
    assert!(
        sb.mind_home.join("store/skill/greet").exists(),
        "item must remain installed after its uninstall hook failed"
    );
    // The source's uninstall hook (runs last) must not have fired.
    assert!(
        !read_log(&log).contains(&"SOURCE-UNINSTALL".to_string()),
        "source uninstall hook must NOT run when an item uninstall hook failed: {:?}",
        read_log(&log)
    );
    // HOOK-53: the source remains melded.
    let sources = sb.mind(&["recall", "--sources"]).stdout;
    assert!(
        sources.contains("failun"),
        "source must remain melded after a failed item uninstall hook: {sources}"
    );

    // M3: tie the abort to the FAILING item uninstall hook.
    // The unmeld must have exited non-zero (already asserted above) AND its
    // output must surface the hook failure: either the "running uninstall hook
    // for skill:greet" indication (stdout) or the "failed (exit 7)" error text
    // (stderr, via MindError::HookFailed). Both together give the clearest
    // signal, but either suffices -- what matters is that the exit code came
    // from THIS hook, not from something else.
    let combined = format!("{}{}", unmeld.stdout, unmeld.stderr);
    assert!(
        combined.contains("greet"),
        "the failure output must reference the failing item 'greet': {combined}"
    );
    assert!(
        combined.contains("exit 7")
            || combined.contains("HookFailed")
            || combined.contains("failed"),
        "the failure output must surface the hook exit code or error: {combined}"
    );
}

#[test]
fn item_install_hook_failure_rolls_back_the_item_install() {
    // spec: HOOK-81
    // A non-zero exit from an item's install hook is a hard stop that rolls back
    // that item's install: its store copy and links are removed, leaving it not
    // installed. With TWO install hooks, a failure of the SECOND must still roll
    // back the whole item (the first hook's host side effect is not undone, but
    // the item itself is gone).
    let sb = Sandbox::new("failin");
    let log = sb.base.join("failin.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    let toml = format!(
        concat!(
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "\n",
            "[[items.hooks]]\n",
            "run = \"echo FIRST-RAN >> {lg}\"\n",
            "event = \"install\"\n",
            "\n",
            "[[items.hooks]]\n",
            "run = \"exit 3\"\n",
            "event = \"install\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);
    let learn = sb.mind(&[
        "learn",
        "skill:greet",
        "--dangerously-skip-install-hook-check",
    ]);
    assert!(
        !learn.success,
        "a failing item install hook must fail the learn: {} {}",
        learn.stdout, learn.stderr
    );
    // The first hook ran (declaration order), proving the second one is what failed.
    assert_eq!(
        read_log(&log),
        vec!["FIRST-RAN"],
        "install hooks run in order; the first ran before the second failed"
    );
    // HOOK-81 rollback: the item's store copy is gone (not installed).
    assert!(
        !sb.mind_home.join("store/skill/greet").exists(),
        "the failed item install must be rolled back (store copy removed)"
    );
    // It is not recorded in the installed manifest (keyed `kind:name`).
    let manifest = std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap_or_default();
    assert!(
        !manifest.contains("skill:greet"),
        "the rolled-back item must not be recorded in the manifest: {manifest}"
    );
}

#[test]
fn optional_item_hook_parses_and_runs_two_way_without_abort() {
    // spec: HOOK-86
    // Per HOOK-83, item hooks are always two-way (run/skip) regardless of
    // `optional`. Confirm `optional = true` parses and the hook runs unattended
    // under --dangerously-skip-install-hook-check (which runs optional and
    // required alike), and that a non-TTY install simply SKIPS it (no abort, the
    // item still installs).
    let sb = Sandbox::new("opt");
    let log = sb.base.join("opt.log");
    let lg = log.display();
    write(
        &sb.source.join("skills/greet/SKILL.md"),
        "---\ndescription: greet\n---\n# greet\n",
    );
    let toml = format!(
        concat!(
            "[[items]]\n",
            "kind = \"skill\"\n",
            "name = \"greet\"\n",
            "path = \"skills/greet\"\n",
            "\n",
            "[[items.hooks]]\n",
            "run = \"echo OPT-RAN >> {lg}\"\n",
            "optional = true\n",
            "event = \"install\"\n",
        ),
        lg = lg,
    );
    sb.write_and_commit(
        "skills/greet/SKILL.md",
        "---\ndescription: greet\n---\n# greet\n",
    );
    sb.write_and_commit("mind.toml", &toml);
    let spec = sb.source_spec();

    assert!(sb.mind(&["meld", &spec, "--link-only"]).success);

    // Non-TTY without the flag: the optional hook is SKIPPED, item still installs.
    let learn_skip = sb.mind(&["learn", "skill:greet"]);
    assert!(
        learn_skip.success,
        "non-TTY install with an optional hook still installs the item: {} {}",
        learn_skip.stdout, learn_skip.stderr
    );
    assert!(
        sb.mind_home.join("store/skill/greet").exists(),
        "item installs even though its optional hook was skipped"
    );
    assert!(
        read_log(&log).is_empty(),
        "non-TTY skip: the optional hook must not have run: {:?}",
        read_log(&log)
    );

    // Forget it, then re-learn with the dangerous flag: the optional hook runs.
    assert!(sb.mind(&["forget", "skill:greet"]).success);
    let learn_run = sb.mind(&[
        "learn",
        "skill:greet",
        "--dangerously-skip-install-hook-check",
    ]);
    assert!(
        learn_run.success,
        "optional hook runs unattended under the dangerous flag: {} {}",
        learn_run.stdout, learn_run.stderr
    );
    assert_eq!(
        read_log(&log),
        vec!["OPT-RAN"],
        "the optional install hook ran unattended"
    );
}

// ---------------------------------------------------------------------------
// INIT-9: prefix-gated unguarded-reference advisory
// ---------------------------------------------------------------------------

/// Seed a source with two agents where one mentions the other's bare name in
/// prose. `prefix` (when Some) is written as `[source].prefix` in `mind.toml`.
fn init_fixture(name: &str, prefix: Option<&str>) -> Sandbox {
    let sb = Sandbox::new(name);
    // `dev` mentions sibling `review` in bare prose (an unguarded reference).
    write(
        &sb.source.join("agents/dev.md"),
        "---\ndescription: dev agent\n---\n# dev\nHand off to review when done.\n",
    );
    write(
        &sb.source.join("agents/review.md"),
        "---\ndescription: review agent\n---\n# review\n",
    );
    if let Some(p) = prefix {
        write(
            &sb.source.join("mind.toml"),
            &format!("[source]\nprefix = \"{p}\"\n"),
        );
    }
    sb
}

#[test]
fn init_source_without_prefix_emits_no_unguarded_reference_advisory() {
    // spec: INIT-9
    // With no effective prefix, a sibling named in bare prose is NOT flagged: an
    // unprefixed source's bare references resolve as written.
    let sb = init_fixture("noprefix", None);
    let r = sb.mind_cwd(&["init-source", "."], &sb.source);
    assert!(
        r.success,
        "init-source should succeed: {} {}",
        r.stdout, r.stderr
    );
    let combined = format!("{}{}", r.stdout, r.stderr);
    assert!(
        !combined.contains("unguarded-reference"),
        "no prefix => no unguarded-reference advisory: {combined}"
    );
}

#[test]
fn init_source_with_prefix_emits_the_unguarded_reference_advisory() {
    // spec: INIT-9
    // With an effective prefix in force ([source].prefix), the same bare-prose
    // sibling mention IS flagged as an unguarded-reference advisory.
    let sb = init_fixture("prefixed", Some("jk"));
    let r = sb.mind_cwd(&["init-source", "."], &sb.source);
    assert!(
        r.success,
        "init-source should succeed: {} {}",
        r.stdout, r.stderr
    );
    let combined = format!("{}{}", r.stdout, r.stderr);
    assert!(
        combined.contains("unguarded-reference"),
        "a prefix in force must flag the bare reference: {combined}"
    );
    // The advisory names the referencing item AND the sibling it mentions,
    // both on the same line that carries the "unguarded-reference" kind token.
    // Format (from print_findings): "advisory [unguarded-reference]: agent:dev:
    // references sibling(s) in prose: review; ..."
    // Anchoring on the kind token plus the sibling name on a single line prevents
    // a spurious match if "review" appears in unrelated output chrome.
    let advisory_line = combined.lines().find(|l| l.contains("unguarded-reference"));
    assert!(
        advisory_line.is_some(),
        "must have a line containing 'unguarded-reference': {combined}"
    );
    let advisory_line = advisory_line.unwrap();
    assert!(
        advisory_line.contains("review"),
        "the unguarded-reference advisory line must name the sibling 'review': {advisory_line}"
    );
    assert!(
        advisory_line.contains("dev"),
        "the unguarded-reference advisory line must name the referencing item 'dev': {advisory_line}"
    );
}