mind-cli 0.47.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
//! Integration tests for items new to a source installed whole: recording the
//! source as whole-tracked, `upgrade` installing what it gained, and the
//! `--skip-new` / `--ignore-new` opt-outs (spec/lifecycle.md, LIFE-53..56).
//!
//! Each test drives the real `mind` binary against a hermetic fixture: a local
//! git repo melded by filesystem path, with `MIND_HOME`/`CLAUDE_HOME` pointed
//! at temp dirs. A maintainer change is a new commit in the fixture repo. No
//! network.

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

use serde_json::Value;

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

struct Sandbox {
    base: PathBuf,
    source: PathBuf,
    mind_home: PathBuf,
    claude_home: PathBuf,
}

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

impl Run {
    fn all(&self) -> String {
        format!("{}\n{}", self.stdout, self.stderr)
    }
}

impl Sandbox {
    /// A source offering `skill:review`, `skill:test`, and `rule:style`, plus
    /// `mind_toml` at the root when it is not empty.
    fn with_toml(mind_toml: &str) -> Sandbox {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base =
            std::env::temp_dir().join(format!("mind-upgrade-new-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let source = base.join("lib");
        let sb = Sandbox {
            base: base.clone(),
            source: source.clone(),
            mind_home: base.join("mind"),
            claude_home: base.join("claude"),
        };
        for skill in ["review", "test"] {
            write_file(
                &source.join(format!("skills/{skill}/SKILL.md")),
                &format!("---\nname: {skill}\ndescription: {skill} skill\n---\n# {skill}\n"),
            );
        }
        write_file(
            &source.join("rules/style.md"),
            "---\ndescription: Style rule\n---\n# style\n",
        );
        if !mind_toml.is_empty() {
            write_file(&source.join("mind.toml"), mind_toml);
        }
        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 new() -> Sandbox {
        Sandbox::with_toml("")
    }

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

    /// A maintainer adds a skill and commits it.
    fn add_skill(&self, name: &str) {
        write_file(
            &self.source.join(format!("skills/{name}/SKILL.md")),
            &format!("---\nname: {name}\ndescription: {name} skill\n---\n# {name}\n"),
        );
        git(&self.source, &["add", "-A"]);
        git(&self.source, &["commit", "-qm", "add skill"]);
    }

    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)
            .env_remove("MIND_MAX_METADATA_SIZE")
            .env_remove("MIND_TTY")
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .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 ok(&self, args: &[&str]) -> Run {
        let r = self.mind(args);
        assert!(r.success, "mind {args:?}: {} {}", r.stdout, r.stderr);
        r
    }

    fn registry(&self) -> Value {
        let raw = std::fs::read_to_string(self.mind_home.join("sources.json")).unwrap();
        serde_json::from_str(&raw).expect("sources.json is JSON")
    }

    /// The fixture's one registry entry.
    fn source_entry(&self) -> Value {
        self.registry()["sources"][0].clone()
    }

    fn whole_snapshot(&self) -> Option<Vec<String>> {
        strings(&self.source_entry()["whole_snapshot"])
    }

    /// Drop the source's `whole_snapshot`, as a registry written before it
    /// existed has none.
    fn clear_whole_snapshot(&self) {
        let mut reg = self.registry();
        reg["sources"][0]
            .as_object_mut()
            .unwrap()
            .remove("whole_snapshot");
        std::fs::write(
            self.mind_home.join("sources.json"),
            serde_json::to_string_pretty(&reg).unwrap(),
        )
        .unwrap();
    }

    fn installed(&self) -> Vec<String> {
        let Ok(raw) = std::fs::read_to_string(self.mind_home.join("manifest.json")) else {
            return Vec::new();
        };
        let v: Value = serde_json::from_str(&raw).expect("manifest.json is JSON");
        let mut keys: Vec<String> = v["items"]
            .as_object()
            .map(|o| o.keys().cloned().collect())
            .unwrap_or_default();
        keys.sort();
        keys
    }
}

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

fn strings(v: &Value) -> Option<Vec<String>> {
    v.as_array().map(|a| {
        a.iter()
            .map(|s| s.as_str().unwrap_or_default().to_string())
            .collect()
    })
}

fn svec(items: &[&str]) -> Vec<String> {
    items.iter().map(|s| s.to_string()).collect()
}

fn write_file(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 st = Command::new("git")
        .args(args)
        .current_dir(dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("git");
    assert!(st.success(), "git {args:?} failed");
}

const ALL_THREE: [&str; 3] = ["rule:style", "skill:review", "skill:test"];

#[test]
fn installing_a_source_whole_records_its_catalog() {
    // spec: LIFE-53
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    assert_eq!(sb.whole_snapshot(), Some(svec(&ALL_THREE)));
}

#[test]
fn learning_the_last_missing_item_records_the_source() {
    // spec: LIFE-53 -- a cherry-picked source is not tracked until every item
    // in it is installed, by whatever route.
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--register-only"]);
    sb.ok(&["learn", "review", "--yes"]);
    assert_eq!(sb.whole_snapshot(), None);
    sb.ok(&["learn", "test", "--yes"]);
    assert_eq!(sb.whole_snapshot(), None);
    sb.ok(&["learn", "style", "--yes"]);
    assert_eq!(sb.whole_snapshot(), Some(svec(&ALL_THREE)));
}

#[test]
fn upgrade_installs_an_item_new_to_a_source_installed_whole() {
    // spec: LIFE-54
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    sb.add_skill("deploy");
    let r = sb.ok(&["upgrade", "--yes"]);
    assert!(
        r.stdout.contains("1 new item in sources installed whole"),
        "{}",
        r.all()
    );
    assert!(r.stdout.contains("skill:deploy"), "{}", r.all());
    assert!(sb.installed().contains(&"skill:deploy".to_string()));
    assert!(
        sb.whole_snapshot()
            .unwrap()
            .contains(&"skill:deploy".to_string())
    );
    let again = sb.ok(&["upgrade", "--yes"]);
    assert!(
        again.stdout.contains("everything is up to date"),
        "{}",
        again.all()
    );
}

#[test]
fn upgrade_leaves_a_cherry_picked_source_alone() {
    // spec: LIFE-53 LIFE-54
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--register-only"]);
    sb.ok(&["learn", "review", "--yes"]);
    sb.add_skill("deploy");
    sb.ok(&["upgrade", "--yes"]);
    assert_eq!(sb.installed(), svec(&["skill:review"]));
    assert_eq!(sb.whole_snapshot(), None);
}

#[test]
fn checking_for_a_whole_install_does_not_repeat_the_gone_source_warning() {
    // spec: LIFE-53 CLI-213 -- the whole-install check skips a source it cannot
    // scan quietly; the verb's own scan is the one that warns.
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--register-only"]);
    sb.ok(&["learn", "review", "--yes"]);
    std::fs::remove_dir_all(&sb.source).unwrap();
    for args in [
        &["recall"][..],
        &["upgrade", "--no-sync", "--yes"],
        &["sync"],
    ] {
        let r = sb.mind(args);
        assert!(
            r.stderr.matches("is gone").count() <= 1,
            "mind {args:?} warned more than once:\n{}",
            r.stderr
        );
    }
}

#[test]
fn a_source_with_every_item_forgotten_is_no_longer_tracked() {
    // spec: LIFE-54
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    for key in ALL_THREE {
        sb.ok(&["forget", key, "--yes"]);
    }
    sb.add_skill("deploy");
    sb.ok(&["upgrade", "--yes"]);
    assert!(sb.installed().is_empty(), "{:?}", sb.installed());
    assert_eq!(sb.whole_snapshot(), None);
}

#[test]
fn a_forgotten_item_is_not_offered_again() {
    // spec: LIFE-54
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    sb.ok(&["forget", "test", "--yes"]);
    sb.add_skill("deploy");
    sb.ok(&["upgrade", "--yes"]);
    let installed = sb.installed();
    assert!(
        installed.contains(&"skill:deploy".to_string()),
        "{installed:?}"
    );
    assert!(
        !installed.contains(&"skill:test".to_string()),
        "{installed:?}"
    );
}

#[test]
fn a_prune_frees_its_link_before_a_new_item_takes_it() {
    // spec: LIFE-57 LIFE-54 -- an agent links under its frontmatter name, so
    // renaming its file is a new item at the old link. The prune runs before
    // the addition, so the new item gets the link instead of colliding.
    let sb = Sandbox::with_toml("[source]\nprune = true\n");
    let agent = "---\nname: dev\ndescription: dev agent\n---\n# dev\n";
    write_file(&sb.source.join("agents/dev.md"), agent);
    git(&sb.source, &["add", "-A"]);
    git(&sb.source, &["commit", "-qm", "add agent"]);
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    assert!(sb.installed().contains(&"agent:dev".to_string()));

    std::fs::remove_file(sb.source.join("agents/dev.md")).unwrap();
    write_file(&sb.source.join("agents/developer.md"), agent);
    git(&sb.source, &["add", "-A"]);
    git(&sb.source, &["commit", "-qm", "rename agent file"]);
    let r = sb.ok(&["upgrade", "--yes"]);
    assert!(r.stdout.contains("pruned agent:dev"), "{}", r.all());

    let keys = sb.installed();
    assert!(keys.contains(&"agent:developer".to_string()), "{keys:?}");
    assert!(!keys.contains(&"agent:dev".to_string()), "{keys:?}");
    let link = sb.claude_home.join("agents/dev.md");
    let target = std::fs::read_link(&link).expect("the new item owns the link");
    assert!(
        target.to_string_lossy().contains("developer"),
        "{}",
        target.display()
    );
}

#[test]
fn an_item_removed_upstream_leaves_the_snapshot() {
    // spec: LIFE-54
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    std::fs::remove_dir_all(sb.source.join("skills/test")).unwrap();
    git(&sb.source, &["add", "-A"]);
    git(&sb.source, &["commit", "-qm", "drop test"]);
    sb.ok(&["upgrade", "--yes"]);
    assert_eq!(
        sb.whole_snapshot(),
        Some(svec(&["rule:style", "skill:review"]))
    );
}

#[test]
fn a_source_installed_whole_before_tracking_is_tracked_by_its_next_upgrade() {
    // spec: LIFE-53 LIFE-54 -- recorded from the pre-fetch catalog, so the
    // item the fetch brings in is new. The source is cloned (pinned to a
    // branch) so the fetch, not the working tree, carries the new item.
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--pin", "branch=main", "--yes"]);
    sb.clear_whole_snapshot();
    sb.add_skill("deploy");
    sb.ok(&["upgrade", "--yes"]);
    assert!(sb.installed().contains(&"skill:deploy".to_string()));
}

#[test]
fn skip_new_defers_new_items_to_the_next_upgrade() {
    // spec: LIFE-55
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    sb.add_skill("deploy");
    let r = sb.ok(&["upgrade", "--yes", "--skip-new"]);
    assert!(
        r.all().contains("skipped 1 new item(s) (--skip-new)"),
        "{}",
        r.all()
    );
    assert!(!sb.installed().contains(&"skill:deploy".to_string()));
    assert_eq!(sb.whole_snapshot(), Some(svec(&ALL_THREE)));
    sb.ok(&["upgrade", "--yes"]);
    assert!(sb.installed().contains(&"skill:deploy".to_string()));
}

#[test]
fn ignore_new_records_new_items_without_installing_them() {
    // spec: LIFE-55
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    sb.add_skill("deploy");
    let r = sb.ok(&["upgrade", "--yes", "--ignore-new"]);
    assert!(
        r.all().contains("ignored new item skill:deploy"),
        "{}",
        r.all()
    );
    assert!(r.all().contains("#skill:deploy'`"), "{}", r.all());
    assert!(!sb.installed().contains(&"skill:deploy".to_string()));
    sb.ok(&["upgrade", "--yes"]);
    assert!(!sb.installed().contains(&"skill:deploy".to_string()));
    sb.ok(&["learn", "deploy", "--yes"]);
    assert!(sb.installed().contains(&"skill:deploy".to_string()));
}

#[test]
fn the_ignore_note_names_a_command_that_installs_the_item() {
    // spec: LIFE-55 -- the suggested ref is source-qualified, so it resolves
    // under a prefix and beside a same-named item in another source.
    let sb = Sandbox::with_toml("[source]\nprefix = \"jk\"\n");
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    sb.add_skill("deploy");
    let r = sb.ok(&["upgrade", "--yes", "--ignore-new"]);
    let note = r
        .all()
        .lines()
        .find(|l| l.contains("--ignore-new"))
        .map(str::to_string)
        .unwrap_or_else(|| panic!("no ignore note: {}", r.all()));
    // `... run `mind learn '<ref>'` to install it`
    let quoted = note
        .split("`mind learn ")
        .nth(1)
        .and_then(|rest| rest.split('`').next())
        .unwrap_or_else(|| panic!("no learn command in: {note}"));
    let item_ref = quoted.trim_matches('\'');
    sb.ok(&["learn", item_ref, "--yes"]);
    assert!(
        sb.installed().contains(&"skill:jk:deploy".to_string()),
        "{:?}",
        sb.installed()
    );
}

#[test]
fn skip_new_and_ignore_new_conflict() {
    // spec: LIFE-55
    let sb = Sandbox::new();
    let r = sb.mind(&["upgrade", "--skip-new", "--ignore-new"]);
    assert!(!r.success, "{}", r.all());
    let r = sb.mind(&["sync", "--upgrade", "--skip-new", "--ignore-new"]);
    assert!(!r.success, "{}", r.all());
}

#[test]
fn sync_upgrade_takes_the_opt_outs() {
    // spec: LIFE-55
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    sb.add_skill("deploy");
    let r = sb.ok(&["sync", "--upgrade", "--yes", "--skip-new"]);
    assert!(
        r.all().contains("skipped 1 new item(s) (--skip-new)"),
        "{}",
        r.all()
    );
    assert!(!sb.installed().contains(&"skill:deploy".to_string()));
    sb.ok(&["sync", "--upgrade", "--yes", "--ignore-new"]);
    assert!(!sb.installed().contains(&"skill:deploy".to_string()));
    sb.ok(&["sync", "--upgrade", "--yes"]);
    assert!(!sb.installed().contains(&"skill:deploy".to_string()));
}

#[test]
fn sync_opt_outs_require_upgrade() {
    // spec: LIFE-55
    let sb = Sandbox::new();
    assert!(!sb.mind(&["sync", "--skip-new"]).success);
    assert!(!sb.mind(&["sync", "--ignore-new"]).success);
}

#[test]
fn json_result_carries_new_and_ignored_items() {
    // spec: LIFE-56
    let sb = Sandbox::new();
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    sb.add_skill("deploy");
    let r = sb.ok(&["--json", "upgrade", "--yes"]);
    let v: Value = serde_json::from_str(&r.stdout).expect("one JSON document");
    let data = if v.get("data").is_some() {
        &v["data"]
    } else {
        &v
    };
    assert_eq!(data["new_items"][0]["key"], "skill:deploy", "{v}");
    assert!(data.get("ignored_new_items").is_none(), "{v}");

    sb.add_skill("lint");
    let r = sb.ok(&["--json", "upgrade", "--yes", "--ignore-new"]);
    let v: Value = serde_json::from_str(&r.stdout).expect("one JSON document");
    let data = if v.get("data").is_some() {
        &v["data"]
    } else {
        &v
    };
    assert_eq!(data["ignored_new_items"][0]["key"], "skill:lint", "{v}");
    assert!(data.get("new_items").is_none(), "{v}");
}

#[test]
fn the_opt_outs_apply_to_profile_additions() {
    // spec: LIFE-55 PROF-21
    let toml = "[profiles]\ndefault = [\"skill:review\"]\n";
    let sb = Sandbox::with_toml(toml);
    sb.ok(&["meld", &sb.spec(), "--yes"]);
    assert_eq!(sb.installed(), svec(&["skill:review"]));
    sb.ok(&["upgrade", "--yes"]); // settle
    write_file(
        &sb.source.join("mind.toml"),
        "[profiles]\ndefault = [\"skill:review\", \"skill:test\"]\n",
    );
    git(&sb.source, &["add", "-A"]);
    git(&sb.source, &["commit", "-qm", "grow default"]);

    let r = sb.ok(&["upgrade", "--yes", "--skip-new"]);
    assert!(r.all().contains("skipped 1 new item(s)"), "{}", r.all());
    assert_eq!(sb.installed(), svec(&["skill:review"]));

    let r = sb.ok(&["upgrade", "--yes", "--ignore-new"]);
    assert!(
        r.all().contains("ignored new item skill:test"),
        "{}",
        r.all()
    );
    sb.ok(&["upgrade", "--yes"]);
    assert_eq!(sb.installed(), svec(&["skill:review"]));
}