mind-cli 0.44.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
//! Pure helpers for `init-source` scaffolding (INIT-10, INIT-11, INIT-12).
//!
//! Three public functions cover the three new behaviors; no filesystem I/O here.

// The same scaffold text written by INIT-3; kept here so `patch_source_meta`
// can start from it when no mind.toml exists yet. `{version}` is filled in by
// [`scaffold`] with the running release (INIT-13).
// The `[source]` table accepts both `namespace` and `prefix` (DSC-82 alias).
// On write, `namespace` is the canonical key (DSC-82); any active `prefix =`
// line is stripped so a patched file never carries both keys.
const SCAFFOLD: &str = concat!(
    "[source]\n",
    "description = \"\"   # what this source offers\n",
    "min-mind-version = \"{version}\"   # older mind versions warn before melding\n",
    "# namespace = \"prefix\"   # namespace items as prefix:<name>\n",
    "\n",
    "# Declare hooks that run when a consumer melds, upgrades, or unmelds this\n",
    "# source. Remove the leading `# ` to enable a hook.\n",
    "#\n",
    "# An install hook re-runs whenever the source advances, so write it to be\n",
    "# idempotent (safe to run again on a host it already set up). If a step\n",
    "# cannot be made idempotent, declare an update hook: it runs at upgrade\n",
    "# INSTEAD of the install hooks.\n",
    "#\n",
    "# [[hooks]]\n",
    "# run = \"make install\"         # shell command to run\n",
    "# name = \"Build\"               # optional label shown in the prompt\n",
    "# event = \"install\"             # \"install\" (default), \"update\", or \"uninstall\"\n",
    "# optional = false              # false = required (default). optional only lets the\n",
    "#                               # user decline running it; a failure always aborts.\n",
    "#\n",
    "# [[hooks]]\n",
    "# run = \"make upgrade\"          # runs at upgrade in place of the install hooks\n",
    "# name = \"Upgrade\"\n",
    "# event = \"update\"\n",
    "#\n",
    "# [[hooks]]\n",
    "# run = \"make clean\"            # cleanup hook run at unmeld time\n",
    "# name = \"Cleanup\"\n",
    "# event = \"uninstall\"\n",
    "# optional = true               # the user may decline this step (its failure still aborts)\n",
);

/// INIT-3 / INIT-13: the scaffold `init-source` writes for a new `mind.toml`,
/// with `min-mind-version` set to the running release.
pub(crate) fn scaffold() -> String {
    SCAFFOLD.replace("{version}", crate::mindfile::running_release_version())
}

/// INIT-11: resolve the effective plugin name from the three-level priority.
///
/// `namespace_flag` (highest) > `mindfile_prefix` > `dir_basename`.
pub fn plugin_name(
    dir_basename: &str,
    mindfile_prefix: Option<&str>,
    namespace_flag: Option<&str>,
) -> String {
    if let Some(ns) = namespace_flag {
        return ns.to_string();
    }
    if let Some(p) = mindfile_prefix {
        return p.to_string();
    }
    dir_basename.to_string()
}

/// INIT-10: produce the `.claude-plugin/marketplace.json` content.
///
/// When `skills` is `None` the `"skills"` key is omitted entirely.
/// When `skills` is `Some(&[])` the key is present with an empty array.
pub fn render_marketplace_json(name: &str, description: &str, skills: Option<&[String]>) -> String {
    let mut plugin = serde_json::Map::new();
    plugin.insert("name".into(), serde_json::Value::String(name.to_string()));
    plugin.insert("source".into(), serde_json::Value::String(".".to_string()));
    plugin.insert(
        "description".into(),
        serde_json::Value::String(description.to_string()),
    );
    if let Some(paths) = skills {
        plugin.insert(
            "skills".into(),
            serde_json::Value::Array(
                paths
                    .iter()
                    .map(|p| serde_json::Value::String(p.clone()))
                    .collect(),
            ),
        );
    }

    let manifest = serde_json::json!({
        "name": name,
        "plugins": [serde_json::Value::Object(plugin)],
    });

    let mut out =
        serde_json::to_string_pretty(&manifest).expect("JSON serialization is infallible");
    out.push('\n');
    out
}

/// INIT-12: text-patch the `[source]` section of a `mind.toml`.
///
/// When `existing_content` is `None`, starts from the built-in scaffold.
/// Each requested key is inserted after the `[source]` header if absent, or
/// the existing active line is replaced in place. Comments are preserved.
pub fn patch_source_meta(
    existing_content: Option<&str>,
    flat_skills: bool,
    namespace: Option<&str>,
) -> String {
    let mut result = existing_content.map_or_else(scaffold, str::to_string);

    if flat_skills {
        result = set_key(&result, "flat-skills", "true");
    }
    if let Some(ns) = namespace {
        let value = toml_string(ns);
        // spec: INIT-11 / DSC-82 -- write `namespace =` as the active key.
        // `set_key("namespace", ...)` replaces any existing `namespace =` line
        // or inserts a new one after the `[source]` header.
        result = set_key(&result, "namespace", &value);
        // spec: DSC-82 -- strip any active `prefix =` line that may remain
        // (the deprecated alias key). This prevents a file from ending up with
        // both `namespace =` and `prefix =`.
        result = result
            .lines()
            .filter(|l| {
                let t = l.trim_start();
                t.starts_with('#') || (!t.starts_with("prefix =") && !t.starts_with("prefix="))
            })
            .collect::<Vec<_>>()
            .join("\n")
            + "\n";
    }

    result
}

/// The default release-tag template `init-source` declares (VER-131).
pub const RELEASE_TAGS: &str = "v{version}";

/// VER-131: declare `release-tags = "v{version}"` in a generated `mind.toml`.
pub fn with_release_tags(content: &str) -> String {
    set_key(content, "release-tags", &toml_string(RELEASE_TAGS))
}

/// Replace the active `<key> = ...` line in `content`, or insert it after
/// the `[source]` header. Non-active (commented) lines are left untouched.
///
/// When no `[source]` section exists, appends one at the end of the file
/// before inserting the key.
///
/// Always emits a trailing newline; normalizes content that lacks one.
fn set_key(content: &str, key: &str, value: &str) -> String {
    let new_line = format!("{key} = {value}");
    let key_eq = format!("{key} =");
    let key_eq_nospace = format!("{key}=");

    let mut output: Vec<String> = Vec::new();
    let mut replaced = false;
    let mut source_line_idx: Option<usize> = None;

    for line in content.lines() {
        if line.trim() == "[source]" && source_line_idx.is_none() {
            source_line_idx = Some(output.len());
        }
        let trimmed = line.trim_start();
        let is_active_key = !trimmed.starts_with('#')
            && (trimmed.starts_with(&key_eq) || trimmed.starts_with(&key_eq_nospace));

        if is_active_key {
            output.push(new_line.clone());
            replaced = true;
        } else {
            output.push(line.to_string());
        }
    }

    if !replaced {
        if let Some(i) = source_line_idx {
            output.insert(i + 1, new_line);
        } else {
            // No [source] section in the file; append one followed by the key.
            output.push("[source]".to_string());
            output.push(new_line);
        }
    }

    let mut result = output.join("\n");
    result.push('\n');
    result
}

/// Produce a TOML double-quoted string value with basic escaping.
fn toml_string(s: &str) -> String {
    let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
    format!("\"{escaped}\"")
}

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

    // -------------------------------------------------------------------------
    // plugin_name — INIT-11
    // -------------------------------------------------------------------------

    #[test]
    fn plugin_name_namespace_flag_wins() {
        assert_eq!(
            plugin_name("dirname", Some("prefix"), Some("ns-flag")),
            "ns-flag"
        );
    }

    #[test]
    fn plugin_name_mindfile_prefix_without_flag() {
        assert_eq!(plugin_name("dirname", Some("mypkg"), None), "mypkg");
    }

    #[test]
    fn plugin_name_falls_back_to_dirname() {
        assert_eq!(plugin_name("myrepo", None, None), "myrepo");
    }

    #[test]
    fn plugin_name_namespace_flag_overrides_prefix() {
        assert_eq!(
            plugin_name("dir", Some("pkg"), Some("override")),
            "override"
        );
    }

    // -------------------------------------------------------------------------
    // render_marketplace_json — INIT-10
    // -------------------------------------------------------------------------

    #[test]
    fn render_marketplace_json_no_skills_key() {
        let out = render_marketplace_json("myplugin", "A plugin", None);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["name"], "myplugin");
        let plugin = &v["plugins"][0];
        assert_eq!(plugin["name"], "myplugin");
        assert_eq!(plugin["source"], ".");
        assert_eq!(plugin["description"], "A plugin");
        assert!(
            plugin.get("skills").is_none(),
            "skills key must be absent when None"
        );
    }

    #[test]
    fn render_marketplace_json_with_skills() {
        let skills = vec!["review".to_string(), "build".to_string()];
        let out = render_marketplace_json("pkg", "desc", Some(&skills));
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        let s = v["plugins"][0]["skills"].as_array().expect("skills array");
        assert_eq!(s.len(), 2);
        assert_eq!(s[0], "review");
        assert_eq!(s[1], "build");
    }

    #[test]
    fn render_marketplace_json_with_empty_skills() {
        let skills: Vec<String> = vec![];
        let out = render_marketplace_json("p", "d", Some(&skills));
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        let s = v["plugins"][0]["skills"]
            .as_array()
            .expect("skills key present even if empty");
        assert!(s.is_empty());
    }

    #[test]
    fn render_marketplace_json_name_in_both_top_and_entry() {
        let out = render_marketplace_json("foo", "bar", None);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["name"], "foo", "top-level name");
        assert_eq!(v["plugins"][0]["name"], "foo", "entry name");
    }

    #[test]
    fn render_marketplace_json_ends_with_newline() {
        let out = render_marketplace_json("n", "d", None);
        assert!(out.ends_with('\n'), "output must end with newline");
    }

    // -------------------------------------------------------------------------
    // patch_source_meta — INIT-12
    // -------------------------------------------------------------------------

    #[test]
    fn patch_source_meta_inserts_flat_skills_into_scaffold() {
        // No existing file: starts from scaffold. flat-skills is absent in the
        // scaffold, so it is inserted right after [source].
        let out = patch_source_meta(None, true, None);
        assert!(
            out.contains("flat-skills = true"),
            "must insert flat-skills: {out}"
        );
        // The rest of the scaffold content is preserved.
        assert!(out.contains("[source]"), "must keep [source] header: {out}");
        assert!(
            out.contains("description = \"\""),
            "must keep description line: {out}"
        );
    }

    #[test]
    fn patch_source_meta_inserts_namespace_into_scaffold() {
        // spec: DSC-82 / INIT-11 -- patch_source_meta must write `namespace =` as
        // the active key (`prefix` is the deprecated read alias).
        let out = patch_source_meta(None, false, Some("mypkg"));
        assert!(
            out.contains("namespace = \"mypkg\""),
            "must insert namespace key: {out}"
        );
        // Must not emit `prefix =` as an active line (only `namespace =` is written).
        let active_prefix = out
            .lines()
            .any(|l| !l.trim_start().starts_with('#') && l.trim_start().starts_with("prefix ="));
        assert!(
            !active_prefix,
            "active key must be `namespace`, not `prefix`: {out}"
        );
    }

    #[test]
    fn patch_source_meta_replaces_existing_flat_skills_false() {
        let existing = "[source]\nflat-skills = false\ndescription = \"\"\n";
        let out = patch_source_meta(Some(existing), true, None);
        assert!(
            out.contains("flat-skills = true"),
            "must replace false with true: {out}"
        );
        assert!(
            !out.contains("flat-skills = false"),
            "old value must be gone: {out}"
        );
    }

    #[test]
    fn patch_source_meta_replaces_existing_prefix_key() {
        // spec: DSC-82 -- when the existing mind.toml uses the deprecated
        // `prefix = "old"`, patch_source_meta must normalize it to
        // `namespace = "new"` (single key, no duplication).
        let existing = "[source]\nprefix = \"old\"\ndescription = \"\"\n";
        let out = patch_source_meta(Some(existing), false, Some("new"));
        assert!(
            out.contains("namespace = \"new\""),
            "must write namespace = new: {out}"
        );
        // The old prefix key must be gone (replaced, not left alongside).
        assert!(
            !out.contains("prefix = \"old\""),
            "old prefix = old must be gone: {out}"
        );
        // No stray active `prefix =` line.
        let active_prefix = out
            .lines()
            .any(|l| !l.trim_start().starts_with('#') && l.trim_start().starts_with("prefix ="));
        assert!(!active_prefix, "no active prefix key must remain: {out}");
    }

    #[test]
    fn patch_source_meta_inserts_after_source_header() {
        let existing = "[source]\ndescription = \"\"\n";
        let out = patch_source_meta(Some(existing), true, None);
        // flat-skills must appear before description (inserted right after [source]).
        let flat_pos = out.find("flat-skills").unwrap();
        let desc_pos = out.find("description").unwrap();
        assert!(
            flat_pos < desc_pos,
            "flat-skills must appear before description: {out}"
        );
    }

    #[test]
    fn patch_source_meta_comment_lines_not_treated_as_active() {
        // A commented prefix line is not treated as an active key; the new
        // namespace is inserted as an active line (INIT-11 write key is
        // `namespace`).
        let existing = "[source]\n# prefix = \"old\"\ndescription = \"\"\n";
        let out = patch_source_meta(Some(existing), false, Some("real"));
        assert!(
            out.contains("namespace = \"real\""),
            "must insert active namespace key: {out}"
        );
        assert!(
            out.contains("# prefix = \"old\""),
            "must keep comment line: {out}"
        );
    }

    #[test]
    fn patch_source_meta_both_flags() {
        // Both flags: flat-skills and namespace (INIT-11/INIT-12 write behavior).
        let out = patch_source_meta(None, true, Some("mypkg"));
        assert!(
            out.contains("flat-skills = true"),
            "must have flat-skills: {out}"
        );
        assert!(
            out.contains("namespace = \"mypkg\""),
            "must emit namespace key: {out}"
        );
    }

    #[test]
    fn patch_source_meta_no_flags_returns_scaffold() {
        // Neither flag set: content is unchanged (just the scaffold).
        let out = patch_source_meta(None, false, None);
        assert_eq!(out, scaffold(), "no-op must return the scaffold unchanged");
    }

    #[test]
    fn scaffold_declares_the_running_release_as_min_mind_version() {
        // spec: INIT-13
        let out = scaffold();
        let line = format!(
            "min-mind-version = \"{}\"",
            crate::mindfile::running_release_version()
        );
        assert!(out.contains(&line), "{out}");
        assert!(!out.contains("{version}"), "{out}");
        // The scaffold must load: the value passes the DSC-40 validator even
        // on a `-dev` build.
        let dir = std::env::temp_dir().join(format!("mind-scaffold-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("mind.toml"), &out).unwrap();
        let loaded = crate::mindfile::MindToml::load(&dir);
        let _ = std::fs::remove_dir_all(&dir);
        let loaded = loaded.expect("scaffold parses").expect("present");
        assert!(crate::mindfile::unmet_min_version(Some(&loaded)).is_none());
    }

    #[test]
    fn running_release_version_drops_the_prerelease_suffix() {
        // spec: INIT-13
        let v = crate::mindfile::running_release_version();
        assert!(crate::mindfile::is_plausible_version(v), "{v}");
        assert!(env!("CARGO_PKG_VERSION").starts_with(v));
    }

    #[test]
    fn patch_source_meta_existing_content_no_flags() {
        let existing = "[source]\ndescription = \"existing\"\n";
        let out = patch_source_meta(Some(existing), false, None);
        assert_eq!(
            out, existing,
            "no-op must return existing content unchanged"
        );
    }

    #[test]
    fn toml_string_escapes_quotes_and_backslashes() {
        assert_eq!(toml_string("foo"), "\"foo\"");
        assert_eq!(toml_string("foo\"bar"), "\"foo\\\"bar\"");
        assert_eq!(toml_string("foo\\bar"), "\"foo\\\\bar\"");
    }

    // -------------------------------------------------------------------------
    // set_key — M7: missing [source] section
    // -------------------------------------------------------------------------

    /// spec: M7 — when the file has no [source] header, set_key must append
    /// one before inserting the key so the value lands in the right TOML scope.
    #[test]
    fn set_key_creates_source_section_when_absent() {
        // A mind.toml that only has [[items]] and no [source] block.
        let content = "[[items]]\nkind = \"skill\"\nname = \"foo\"\n";
        let out = set_key(content, "prefix", "\"mypkg\"");

        // The [source] header must now be present.
        assert!(
            out.contains("[source]"),
            "must create [source] section: {out}"
        );
        // The key must be present.
        assert!(
            out.contains("prefix = \"mypkg\""),
            "must insert key under [source]: {out}"
        );
        // [source] must precede the key.
        let source_pos = out.find("[source]").unwrap();
        let key_pos = out.find("prefix = \"mypkg\"").unwrap();
        assert!(source_pos < key_pos, "[source] must precede the key: {out}");
        // Original [[items]] content must be preserved.
        assert!(
            out.contains("[[items]]"),
            "must keep [[items]] section: {out}"
        );
        // Output must end with a newline.
        assert!(out.ends_with('\n'), "must end with newline: {out:?}");
    }

    /// spec: M7 regression — when [source] already exists, set_key inserts the
    /// key right after the header (existing happy path must not regress).
    #[test]
    fn set_key_inserts_after_existing_source_section() {
        let content = "[source]\ndescription = \"\"\n";
        let out = set_key(content, "prefix", "\"mypkg\"");

        assert!(out.contains("prefix = \"mypkg\""), "must insert key: {out}");
        // The key must appear after [source].
        let source_pos = out.find("[source]").unwrap();
        let key_pos = out.find("prefix = \"mypkg\"").unwrap();
        assert!(
            source_pos < key_pos,
            "key must appear after [source]: {out}"
        );
        // description line must still be present.
        assert!(
            out.contains("description = \"\""),
            "must preserve existing lines: {out}"
        );
    }
}