spm-cli 0.2.0

Skill package manager — declare AI skills in ai.json, materialize them for Claude/Copilot without polluting your repo.
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
//! End-to-end tests that drive the real `spm` binary against throwaway git repos.
//! Each test gets an isolated scratch dir and its own `SPM_HOME`, so the global
//! store/vendor areas never leak between tests or into the developer's home.

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

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

/// A sandbox: unique scratch root holding a fake skill repo, a project dir, and
/// an isolated SPM_HOME.
struct Sandbox {
    root: PathBuf,
    skill_repo: PathBuf,
    project: PathBuf,
    spm_home: PathBuf,
}

impl Sandbox {
    fn new() -> Self {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let root =
            std::env::temp_dir().join(format!("spm-test-{}-{nanos}-{n}", std::process::id()));
        let sb = Sandbox {
            skill_repo: root.join("skill"),
            project: root.join("project"),
            spm_home: root.join("home"),
            root,
        };
        std::fs::create_dir_all(&sb.project).unwrap();
        sb.init_skill_repo();
        sb
    }

    /// Build a git repo containing one skill, an annotated tag `v0.1.0`, and a
    /// `main` branch — exercising both tag (with `^{}` deref) and branch resolution.
    fn init_skill_repo(&self) {
        std::fs::create_dir_all(&self.skill_repo).unwrap();
        std::fs::write(
            self.skill_repo.join("SKILL.md"),
            "---\nname: greet\ndescription: Say hello nicely.\n---\nGreet warmly.\n",
        )
        .unwrap();
        self.git(&["init", "-q", "-b", "main"]);
        self.git(&["add", "-A"]);
        self.git(&["commit", "-qm", "initial"]);
        self.git(&["tag", "-a", "v0.1.0", "-m", "v0.1.0"]);
    }

    /// Run `git <args>` in the skill repo with a pinned, hermetic identity
    /// (signing disabled) so the harness is independent of the developer's
    /// global git config.
    fn git(&self, args: &[&str]) {
        let ok = Command::new("git")
            .args([
                "-c",
                "user.email=t@t",
                "-c",
                "user.name=t",
                "-c",
                "commit.gpgsign=false",
                "-c",
                "tag.gpgSign=false",
            ])
            .args(args)
            .current_dir(&self.skill_repo)
            .status()
            .unwrap()
            .success();
        assert!(ok, "git {args:?} failed");
    }

    /// Add, on `main`, a `pack/` directory that is a *container* of skills
    /// (`pack/alpha/SKILL.md`, `pack/beta/SKILL.md`) with no `SKILL.md` at its
    /// own root, plus a `bare/` directory with no skill at all. Used to exercise
    /// the container-detection and generic no-SKILL.md warnings.
    fn add_skill_pack(&self) {
        for sub in ["alpha", "beta"] {
            let dir = self.skill_repo.join("pack").join(sub);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("SKILL.md"), format!("---\nname: {sub}\n---\n")).unwrap();
        }
        let bare = self.skill_repo.join("bare");
        std::fs::create_dir_all(&bare).unwrap();
        std::fs::write(bare.join("README.md"), "not a skill\n").unwrap();
        self.git(&["add", "-A"]);
        self.git(&["commit", "-qm", "add pack"]);
    }

    /// Add, on `main`, a `linked/` skill dir whose `SKILL.md` is a **symlink**
    /// (to a sibling regular file). Since `copy_tree` skips symlinks, the
    /// materialized skill ends up with no `SKILL.md`, so spm must still warn.
    #[cfg(unix)]
    fn add_symlinked_skill(&self) {
        let dir = self.skill_repo.join("linked");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("real.md"), "---\nname: linked\n---\n").unwrap();
        std::os::unix::fs::symlink("real.md", dir.join("SKILL.md")).unwrap();
        self.git(&["add", "-A"]);
        self.git(&["commit", "-qm", "add symlinked skill"]);
    }

    fn skill_url(&self) -> String {
        format!("file://{}", self.skill_repo.display())
    }

    /// Run `spm <args>` in the project dir with the sandboxed SPM_HOME.
    fn spm(&self, args: &[&str]) -> std::process::Output {
        Command::new(env!("CARGO_BIN_EXE_spm"))
            .args(args)
            .current_dir(&self.project)
            .env("SPM_HOME", &self.spm_home)
            .output()
            .unwrap()
    }

    /// Run `spm`, asserting success and returning stdout.
    fn ok(&self, args: &[&str]) -> String {
        let out = self.spm(args);
        assert!(
            out.status.success(),
            "spm {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).into_owned()
    }

    fn read(&self, rel: &str) -> String {
        std::fs::read_to_string(self.project.join(rel)).unwrap()
    }

    /// The generated Claude marketplace dir, now project-local (gitignored).
    fn claude_market_dir(&self) -> PathBuf {
        self.project.join(".spm/claude")
    }
}

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

fn skill_head(repo: &Path) -> String {
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(repo)
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout).trim().to_string()
}

#[test]
fn claude_add_resolves_tag_to_commit_and_wires_marketplace() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);

    // ai.lock pins the annotated tag to the underlying commit (not the tag object).
    let lock = sb.read("ai.lock");
    assert!(lock.contains("\"reference\": \"tag:v0.1.0\""), "{lock}");
    assert!(
        lock.contains(&skill_head(&sb.skill_repo)),
        "lock should pin repo HEAD commit: {lock}"
    );

    // Skill physically copied into the plugin dir.
    let skill_md = sb.claude_market_dir().join("plugin/skills/greet/SKILL.md");
    assert!(skill_md.exists(), "missing {}", skill_md.display());

    // Project pointer written to the gitignored local settings file.
    let settings = sb.read(".claude/settings.local.json");
    assert!(settings.contains("\"spm@spm\": true"), "{settings}");
    assert!(settings.contains("extraKnownMarketplaces"), "{settings}");

    // The project-local marketplace dir is gitignored (with an explanatory
    // comment) so the copied skills are never committed.
    let gitignore = sb.read(".gitignore");
    assert!(gitignore.contains(".spm/"), "{gitignore}");
    assert!(gitignore.contains("spm-managed Claude"), "{gitignore}");

    // Nothing landed in the global vendors area.
    assert!(!sb.spm_home.join("vendors").exists());
    // Nothing leaked into the project tree beyond ai.json/ai.lock/.claude/.spm.
    assert!(!sb.project.join("skills").exists());
}

#[test]
fn copilot_add_materializes_project_local_skills() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "copilot"]);
    sb.ok(&[
        "add",
        &sb.skill_url(),
        "--branch",
        "main",
        "--name",
        "greet",
    ]);

    // Skills are copied into a project-local dir, not a user-global marketplace.
    let skill_md = sb
        .project
        .join(".agents/skills/spm-managed-skills/greet/SKILL.md");
    assert!(skill_md.exists(), "missing {}", skill_md.display());
    // Nothing lands in the global vendors area anymore.
    assert!(!sb.spm_home.join("vendors/copilot").exists());

    // The managed dir is gitignored (with an explanatory comment) so the copied
    // skills are never committed.
    let gitignore = sb.read(".gitignore");
    assert!(
        gitignore.contains(".agents/skills/spm-managed-skills/"),
        "{gitignore}"
    );
    assert!(gitignore.contains("spm-managed"), "{gitignore}");
}

#[test]
fn remove_prunes_skill() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);
    sb.ok(&["remove", "greet"]);

    assert!(!sb.read("ai.json").contains("greet"));
    let skills_dir = sb.claude_market_dir().join("plugin/skills");
    assert!(std::fs::read_dir(&skills_dir).unwrap().next().is_none());
}

#[test]
fn install_is_idempotent_from_lock() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);
    let lock_before = sb.read("ai.lock");

    sb.ok(&["install"]);
    let lock_after = sb.read("ai.lock");
    assert_eq!(lock_before, lock_after, "install must not change the lock");
}

#[test]
fn clean_removes_generated_config() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);
    sb.ok(&["clean"]);

    let settings = sb.read(".claude/settings.local.json");
    assert!(!settings.contains("spm@spm"), "{settings}");
    // The project-local marketplace dir is removed after clean.
    assert!(
        !sb.claude_market_dir().exists(),
        "marketplace dir should be gone after clean"
    );
    // The gitignore block spm added is removed too.
    let gitignore = sb.project.join(".gitignore");
    if gitignore.exists() {
        let gi = std::fs::read_to_string(&gitignore).unwrap();
        assert!(!gi.contains(".spm/"), "{gi}");
    }
}

#[test]
fn multi_target_wires_both_vendors() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude,copilot"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);

    assert!(sb
        .claude_market_dir()
        .join("plugin/skills/greet/SKILL.md")
        .exists());
    assert!(sb
        .project
        .join(".agents/skills/spm-managed-skills/greet/SKILL.md")
        .exists());
    assert!(sb.read(".claude/settings.local.json").contains("spm@spm"));
}

#[test]
fn unknown_target_is_rejected() {
    let sb = Sandbox::new();
    let out = sb.spm(&["init", "--target", "nonsense"]);
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("unknown target"));
}

#[test]
fn schema_rejects_unknown_target_value() {
    let sb = Sandbox::new();
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["bogus"],"skills":{}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success());
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("does not match schema"), "{err}");
}

#[test]
fn schema_rejects_skill_without_version_selector() {
    let sb = Sandbox::new();
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["claude"],"skills":{"x":{"git":"u"}}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success());
    assert!(String::from_utf8_lossy(&out.stderr).contains("oneOf"));
}

#[test]
fn rejects_path_traversal_in_skill_path() {
    let sb = Sandbox::new();
    // A hostile `path` escaping the fetched repo must be refused, not fetched.
    // Rejection happens at manifest load, before any git URL is touched.
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["claude"],"skills":{"evil":{"git":"u","tag":"v0.1.0","path":"../../../../../../etc"}}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success(), "traversal path must be rejected");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("`..`"), "{err}");
}

#[test]
fn rejects_absolute_skill_path() {
    let sb = Sandbox::new();
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["claude"],"skills":{"evil":{"git":"u","tag":"v0.1.0","path":"/etc"}}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success(), "absolute path must be rejected");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("relative to the repo root"), "{err}");
}

#[test]
fn rejects_path_traversal_in_skill_name() {
    let sb = Sandbox::new();
    // A skill name containing path separators would let the vendor write outside
    // its skills/ directory. Reject it at the manifest layer.
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["claude"],"skills":{"../../evil":{"git":"u","tag":"v0.1.0"}}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success(), "traversal name must be rejected");
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.contains("invalid skill name"), "{err}");
}

#[test]
fn rejects_traversal_name_on_add() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude"]);
    let out = sb.spm(&[
        "add",
        &sb.skill_url(),
        "--tag",
        "v0.1.0",
        "--name",
        "../escape",
    ]);
    assert!(!out.status.success(), "add must reject a traversal name");
    assert!(String::from_utf8_lossy(&out.stderr).contains("invalid skill name"));
    // A rejected add must not leave the bad name persisted in ai.json.
    assert!(!sb.read("ai.json").contains("escape"));
}

#[test]
fn rejects_forged_absolute_store_in_lock() {
    let sb = Sandbox::new();
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["claude"],"skills":{}}"#,
    )
    .unwrap();
    // A committed ai.lock is untrusted: an absolute `store` must never be acted on.
    std::fs::write(
        sb.project.join("ai.lock"),
        r#"{"id":"spm-deadbeef","skills":{"evil":{"git":"u","reference":"branch:main","commit":"0000000000000000000000000000000000000000","store":"/home/victim/.config/autostart"}}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success(), "forged store must be rejected");
    assert!(String::from_utf8_lossy(&out.stderr).contains("store key"));
}

#[test]
fn rejects_forged_project_id_in_lock() {
    let sb = Sandbox::new();
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["copilot"],"skills":{}}"#,
    )
    .unwrap();
    std::fs::write(
        sb.project.join("ai.lock"),
        r#"{"id":"../../evil","skills":{}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success(), "forged id must be rejected");
    assert!(String::from_utf8_lossy(&out.stderr).contains("invalid project id"));
}

#[test]
fn schema_rejects_abbreviated_commit() {
    let sb = Sandbox::new();
    std::fs::write(
        sb.project.join("ai.json"),
        r#"{"targets":["claude"],"skills":{"x":{"git":"u","commit":"abc1234"}}}"#,
    )
    .unwrap();
    let out = sb.spm(&["install"]);
    assert!(!out.status.success(), "abbreviated commit must be rejected");
    assert!(String::from_utf8_lossy(&out.stderr).contains("does not match schema"));
}

#[test]
fn copilot_clean_removes_project_local_dir_and_gitignore_entry() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "copilot"]);
    sb.ok(&[
        "add",
        &sb.skill_url(),
        "--branch",
        "main",
        "--name",
        "greet",
    ]);

    let managed = sb.project.join(".agents/skills/spm-managed-skills");
    assert!(
        managed.exists(),
        "skills should be materialized before clean"
    );
    assert!(sb
        .read(".gitignore")
        .contains(".agents/skills/spm-managed-skills/"));

    sb.ok(&["clean"]);

    assert!(
        !managed.exists(),
        "clean must remove the managed skills dir"
    );
    assert!(
        !sb.read(".gitignore")
            .contains(".agents/skills/spm-managed-skills/"),
        "clean must drop the gitignore entry"
    );
}

#[test]
fn uppercase_commit_pin_is_not_refetched() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude"]);
    // Pin the real HEAD as an UPPERCASE 40-hex SHA. It must resolve, and a second
    // install must reuse the cached checkout rather than deleting and refetching.
    let head = skill_head(&sb.skill_repo).to_uppercase();
    sb.ok(&["add", &sb.skill_url(), "--commit", &head, "--name", "greet"]);
    let second = sb.ok(&["install"]);
    assert!(
        second.contains("cached") && !second.contains("fetched"),
        "second install should be cached, got: {second}"
    );
    // The lock stores the normalized lowercase SHA.
    assert!(sb.read("ai.lock").contains(&head.to_lowercase()));
}

#[test]
fn container_path_warns_once_and_suggests_subskills() {
    let sb = Sandbox::new();
    sb.add_skill_pack();
    sb.ok(&["init", "--target", "claude,copilot"]);

    // `pack/` is a container of skills (alpha, beta), not a skill itself. The add
    // still succeeds (warning only), but must guide the user to the sub-skills.
    let out = sb.spm(&[
        "add",
        &sb.skill_url(),
        "--branch",
        "main",
        "--path",
        "pack",
        "--name",
        "pack",
    ]);
    assert!(
        out.status.success(),
        "add should succeed with a warning: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let err = String::from_utf8_lossy(&out.stderr);
    // Even with two vendors configured, the check runs once.
    assert_eq!(
        err.matches("has no SKILL.md at its root").count(),
        1,
        "warning must be emitted once, not per-vendor: {err}"
    );
    // Sorted, copy-pasteable suggestions for each discovered sub-skill — and
    // they must carry the version selector so they run as-is.
    assert!(
        err.contains("--branch main --path pack/alpha --name alpha"),
        "should suggest a runnable alpha command with selector: {err}"
    );
    assert!(
        err.contains("--branch main --path pack/beta --name beta"),
        "should suggest a runnable beta command with selector: {err}"
    );
}

#[test]
fn missing_skill_md_without_subskills_warns_once_generically() {
    let sb = Sandbox::new();
    sb.add_skill_pack();
    sb.ok(&["init", "--target", "claude,copilot"]);

    // `bare/` has no SKILL.md and no sub-skills: a single generic warning.
    let out = sb.spm(&[
        "add",
        &sb.skill_url(),
        "--branch",
        "main",
        "--path",
        "bare",
        "--name",
        "bare",
    ]);
    assert!(out.status.success());
    let err = String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        err.matches("has no SKILL.md at its root").count(),
        1,
        "generic warning must be emitted once: {err}"
    );
    assert!(err.contains("agents may ignore it"), "{err}");
    assert!(
        !err.contains("Did you mean"),
        "must not offer sub-skill suggestions when there are none: {err}"
    );
}

#[cfg(unix)]
#[test]
fn symlinked_skill_md_still_warns() {
    let sb = Sandbox::new();
    sb.add_symlinked_skill();
    sb.ok(&["init", "--target", "copilot"]);

    // `linked/SKILL.md` is a symlink, which copy_tree skips — so the vendor dir
    // ends up with no SKILL.md. The check must not be fooled into silence by the
    // symlink resolving to a file in the store.
    let out = sb.spm(&[
        "add",
        &sb.skill_url(),
        "--branch",
        "main",
        "--path",
        "linked",
        "--name",
        "linked",
    ]);
    assert!(out.status.success());
    let err = String::from_utf8_lossy(&out.stderr);
    assert!(
        err.contains("has no SKILL.md at its root"),
        "symlinked SKILL.md must still warn: {err}"
    );
    // And nothing landed in the materialized dir root.
    assert!(!sb
        .project
        .join(".agents/skills/spm-managed-skills/linked/SKILL.md")
        .exists());
}

#[test]
fn status_reports_materialized_skills() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude,copilot"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);

    // With everything installed, `spm status` succeeds and reports the skill as
    // present for both targets — no MISSING markers.
    let out = sb.ok(&["status"]);
    assert!(out.contains("greet"), "{out}");
    assert!(out.contains("claude"), "{out}");
    assert!(out.contains("copilot"), "{out}");
    assert!(!out.contains("MISSING"), "nothing should be missing: {out}");
}

#[test]
fn status_flags_uninstalled_worktree() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "copilot"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);

    // Simulate a fresh worktree/clone: ai.json + ai.lock are committed and
    // present, but the gitignored materialized skills are absent.
    std::fs::remove_dir_all(sb.project.join(".agents")).unwrap();

    let out = sb.spm(&["status"]);
    assert!(
        !out.status.success(),
        "status must fail when declared skills are not materialized here"
    );
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        text.contains("MISSING"),
        "should mark greet MISSING: {text}"
    );
    assert!(
        text.contains("spm install"),
        "should tell the user to run `spm install` here: {text}"
    );
}

#[test]
fn status_succeeds_when_no_skills_are_declared() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "copilot"]);

    let out = sb.ok(&["status"]);
    assert!(out.contains("no skills declared"), "{out}");
    assert!(
        !out.contains("all declared skills are materialized"),
        "must not claim materialization when nothing is declared: {out}"
    );
}

#[test]
fn status_fails_when_declared_skills_are_not_locked() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "copilot"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);

    // ai.json still declares `greet`, but ai.lock is gone — resolution never
    // happened here, so status must not report a green "all materialized".
    std::fs::remove_file(sb.project.join("ai.lock")).unwrap();

    let out = sb.spm(&["status"]);
    assert!(
        !out.status.success(),
        "status must fail when ai.json declares skills that ai.lock does not"
    );
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(text.contains("ai.lock has none"), "{text}");
    assert!(text.contains("spm install"), "{text}");
}

#[test]
fn status_flags_claude_pointer_to_other_checkout() {
    let sb = Sandbox::new();
    sb.ok(&["init", "--target", "claude"]);
    sb.ok(&["add", &sb.skill_url(), "--tag", "v0.1.0", "--name", "greet"]);

    // Rewrite the settings pointer to a different absolute path, mimicking a
    // worktree that inherited the main checkout's registration (issue #28).
    // Mutate the JSON structurally: a textual replace would not match on Windows,
    // where the serialized path has its backslashes JSON-escaped.
    let sp = sb.project.join(".claude/settings.local.json");
    let other = sb
        .root
        .join("some-other-checkout")
        .join(".spm")
        .join("claude");
    let mut settings: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&sp).unwrap()).unwrap();
    settings["extraKnownMarketplaces"]["spm"]["source"]["path"] =
        serde_json::Value::String(other.to_string_lossy().into_owned());
    std::fs::write(&sp, serde_json::to_string_pretty(&settings).unwrap()).unwrap();

    let out = sb.spm(&["status"]);
    assert!(
        !out.status.success(),
        "status must fail when the Claude marketplace points at another checkout"
    );
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        text.contains("some-other-checkout"),
        "should surface the mismatched registered path: {text}"
    );
    assert!(
        text.contains("spm install"),
        "should tell the user to run `spm install` here: {text}"
    );
}