project-canon-cli 0.8.1

The project-canon binary — conformance verbs plus binary-owned distribution of the AI-first CLI canon and companion cli-canon skill.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
//! End-to-end integration tests for the `project-canon skill` verb — run the built binary against
//! throwaway temp dirs and assert install file layout, the single-source invariant, `--dry-run`
//! print-not-write, idempotent re-install, the clobber/force guards, `--json` shape, `--agent`
//! selection, and `list`/`print`.
//!
//! Hermetic and side-effect-safe by construction: every `install` passes `--target <tmp>`, so no
//! write ever reaches `$HOME` or this repo's real `.claude/`. The binary never shells out or hits
//! the network.

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

/// A throwaway install-base dir under the OS temp root; removed on drop.
struct Tmp {
    path: PathBuf,
}

impl Tmp {
    fn new(tag: &str) -> Tmp {
        static N: AtomicU32 = AtomicU32::new(0);
        let n = N.fetch_add(1, Ordering::Relaxed);
        let path =
            std::env::temp_dir().join(format!("pc-skill-it-{tag}-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&path).unwrap();
        Tmp { path }
    }
    fn str(&self) -> &str {
        self.path.to_str().unwrap()
    }
    fn claude_skill(&self) -> PathBuf {
        self.path.join(".claude/skills/ai-first-cli-canon/SKILL.md")
    }
    fn codex_skill(&self) -> PathBuf {
        self.path.join(".codex/skills/ai-first-cli-canon/SKILL.md")
    }
    fn legacy_codex_prompt(&self, name: &str) -> PathBuf {
        self.path.join(".codex/prompts").join(format!("{name}.md"))
    }
    fn skill_resource(&self, agent: &str, name: &str, resource: &str) -> PathBuf {
        let root = match agent {
            "claude" => ".claude/skills",
            "pi" => ".pi/agent/skills",
            "codex" => ".codex/skills",
            other => panic!("unsupported native skill agent {other}"),
        };
        self.path.join(root).join(name).join(resource)
    }
    fn snapshot(&self) -> Vec<(String, Vec<u8>)> {
        fn walk(root: &std::path::Path, dir: &std::path::Path, files: &mut Vec<(String, Vec<u8>)>) {
            let mut entries = std::fs::read_dir(dir)
                .unwrap()
                .map(|entry| entry.unwrap().path())
                .collect::<Vec<_>>();
            entries.sort();
            for path in entries {
                if path.is_dir() {
                    walk(root, &path, files);
                } else {
                    files.push((
                        path.strip_prefix(root).unwrap().display().to_string(),
                        std::fs::read(path).unwrap(),
                    ));
                }
            }
        }
        let mut files = Vec::new();
        walk(&self.path, &self.path, &mut files);
        files
    }
}

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

/// A `project-canon` command with every `PROJECT_CANON_*` variable scrubbed (a stray override on
/// the dev/CI machine must not perturb these hermetic fixtures).
fn base_command() -> Command {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_project-canon"));
    for (key, _) in std::env::vars_os() {
        if key.to_string_lossy().starts_with("PROJECT_CANON_") {
            cmd.env_remove(key);
        }
    }
    cmd
}

fn run(args: &[&str]) -> Output {
    base_command()
        .arg("skill")
        .args(args)
        .output()
        .expect("run project-canon skill")
}

fn code(output: &Output) -> i32 {
    output.status.code().expect("exited with a code")
}

/// The master canon this repo maintains — the single source the installed skills must embed.
/// Read straight from `project_canon_core::CANON` (the one physical copy, packaged in core) so
/// this stays self-contained inside the published tarball and free of root-symlink fragility.
fn master_canon() -> String {
    project_canon_core::CANON.to_string()
}

fn write_managed_legacy_prompt(t: &Tmp, name: &str) -> PathBuf {
    let path = t.legacy_codex_prompt(name);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(
        &path,
        format!(
            "<!-- Installed by `project-canon skill install` — {name} cli_version=0.8.0 schema_version=1. -->\n\nLEGACY"
        ),
    )
    .unwrap();
    path
}

#[test]
fn install_writes_all_agent_forms() {
    let t = Tmp::new("both");
    let out = run(&["install", "--target", t.str()]);
    assert_eq!(
        code(&out),
        0,
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(t.claude_skill().is_file(), "claude SKILL.md missing");
    assert!(
        t.skill_resource("pi", "ai-first-cli-canon", "SKILL.md")
            .is_file(),
        "pi SKILL.md missing"
    );
    assert!(t.codex_skill().is_file(), "codex SKILL.md missing");

    let claude = std::fs::read_to_string(t.claude_skill()).unwrap();
    let codex = std::fs::read_to_string(t.codex_skill()).unwrap();
    // Every native form declares §17 frontmatter.
    assert!(claude.starts_with("---\nname: ai-first-cli-canon"));
    assert!(claude.contains("cli_version:"));
    assert!(codex.starts_with("---\nname: ai-first-cli-canon"));
    assert!(codex.contains("cli_version:"));
}

#[test]
fn explicit_all_matches_the_default_three_runtime_layout() {
    let default = Tmp::new("default-all");
    let explicit = Tmp::new("explicit-all");
    assert_eq!(code(&run(&["install", "--target", default.str()])), 0);
    assert_eq!(
        code(&run(&[
            "install",
            "--target",
            explicit.str(),
            "--agent",
            "all",
        ])),
        0
    );

    assert_eq!(
        default.snapshot(),
        explicit.snapshot(),
        "default and explicit all must emit identical complete trees"
    );
}

#[test]
fn installed_skill_embeds_the_master_canon_verbatim() {
    // The single-source invariant: no drifting second copy — both forms embed the master bytes.
    let t = Tmp::new("single-source");
    assert_eq!(code(&run(&["install", "--target", t.str()])), 0);
    let master = master_canon();
    let claude = std::fs::read_to_string(t.claude_skill()).unwrap();
    let codex = std::fs::read_to_string(t.codex_skill()).unwrap();
    assert!(
        claude.contains(&master),
        "claude skill must embed the master canon verbatim"
    );
    assert!(
        codex.contains(&master),
        "codex skill must embed the master canon verbatim"
    );
}

#[test]
fn dry_run_prints_but_writes_nothing() {
    let t = Tmp::new("dry");
    let out = run(&["install", "--target", t.str(), "--dry-run"]);
    assert_eq!(code(&out), 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("dry-run"), "{stdout}");
    assert!(stdout.contains("would-install"), "{stdout}");
    // Nothing written — not even the agent dirs.
    assert!(!t.path.join(".claude").exists());
    assert!(!t.path.join(".codex").exists());
    assert!(!t.path.join(".pi").exists());
}

#[test]
fn codex_install_removes_managed_legacy_prompts_after_writing_native_trees() {
    let t = Tmp::new("legacy-managed");
    let canon_legacy = write_managed_legacy_prompt(&t, "ai-first-cli-canon");
    let cli_legacy = write_managed_legacy_prompt(&t, "cli-canon");

    let out = run(&["install", "--target", t.str(), "--agent", "codex", "--json"]);
    assert_eq!(code(&out), 0, "{}", String::from_utf8_lossy(&out.stderr));
    assert!(!canon_legacy.exists());
    assert!(!cli_legacy.exists());
    assert!(t.codex_skill().is_file());
    assert!(t
        .skill_resource("codex", "cli-canon", "templates/review-report.md")
        .is_file());
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("\"action\":\"remove-managed-legacy\""));
    assert!(stdout.contains("\"managed_legacy_removed\":2"));
}

#[test]
fn legacy_migration_preserves_foreign_and_newer_files() {
    let t = Tmp::new("legacy-foreign");
    let foreign = t.legacy_codex_prompt("ai-first-cli-canon");
    std::fs::create_dir_all(foreign.parent().unwrap()).unwrap();
    std::fs::write(&foreign, "FOREIGN PROMPT").unwrap();
    let newer = t.legacy_codex_prompt("cli-canon");
    std::fs::write(
        &newer,
        "<!-- Installed by `project-canon skill install` — cli-canon cli_version=99.0.0 schema_version=1. -->\n\nFUTURE",
    )
    .unwrap();

    let out = run(&[
        "install",
        "--target",
        t.str(),
        "--agent",
        "codex",
        "--force",
        "--json",
    ]);
    assert_eq!(code(&out), 0, "{}", String::from_utf8_lossy(&out.stderr));
    assert_eq!(std::fs::read_to_string(foreign).unwrap(), "FOREIGN PROMPT");
    assert!(std::fs::read_to_string(newer).unwrap().contains("FUTURE"));
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("\"legacy_preserved\":2"));
}

#[test]
fn legacy_migration_dry_run_reports_removal_without_writing() {
    let t = Tmp::new("legacy-dry-run");
    let legacy = write_managed_legacy_prompt(&t, "ai-first-cli-canon");
    let before = t.snapshot();
    let out = run(&[
        "install",
        "ai-first-cli-canon",
        "--target",
        t.str(),
        "--agent",
        "codex",
        "--dry-run",
        "--json",
    ]);
    assert_eq!(code(&out), 0);
    assert_eq!(t.snapshot(), before);
    assert!(legacy.is_file());
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("\"action\":\"remove-managed-legacy\""));
    assert!(stdout.contains("\"managed_legacy_would_remove\":1"));
    assert!(stdout.contains("\"managed_legacy_removed\":0"));
    assert!(stdout.contains("\"would_write\":1"));
    assert!(stdout.contains("\"written\":0"));
}

#[test]
fn legacy_migration_scope_follows_agent_and_skill_selection() {
    let t = Tmp::new("legacy-scope");
    let canon_legacy = write_managed_legacy_prompt(&t, "ai-first-cli-canon");
    let cli_legacy = write_managed_legacy_prompt(&t, "cli-canon");

    assert_eq!(
        code(&run(&[
            "install",
            "ai-first-cli-canon",
            "--target",
            t.str(),
            "--agent",
            "claude",
        ])),
        0
    );
    assert!(
        canon_legacy.is_file(),
        "non-Codex install must not migrate Codex state"
    );

    assert_eq!(
        code(&run(&[
            "install",
            "ai-first-cli-canon",
            "--target",
            t.str(),
            "--agent",
            "codex",
        ])),
        0
    );
    assert!(
        !canon_legacy.exists(),
        "selected skill's managed prompt should migrate"
    );
    assert!(
        cli_legacy.is_file(),
        "unselected skill's prompt must be untouched"
    );
}

#[cfg(unix)]
#[test]
fn legacy_migration_never_removes_a_symlink() {
    let t = Tmp::new("legacy-symlink");
    let sentinel = t.path.join("legacy-sentinel.md");
    std::fs::write(&sentinel, "KEEP").unwrap();
    let legacy = t.legacy_codex_prompt("ai-first-cli-canon");
    std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
    std::os::unix::fs::symlink(&sentinel, &legacy).unwrap();

    let out = run(&[
        "install",
        "ai-first-cli-canon",
        "--target",
        t.str(),
        "--agent",
        "codex",
    ]);
    assert_eq!(code(&out), 0, "{}", String::from_utf8_lossy(&out.stderr));
    assert!(std::fs::symlink_metadata(&legacy)
        .unwrap()
        .file_type()
        .is_symlink());
    assert_eq!(std::fs::read_to_string(sentinel).unwrap(), "KEEP");
}

#[test]
fn blocked_native_install_preserves_managed_legacy_prompt() {
    let t = Tmp::new("legacy-blocked-native");
    let legacy = write_managed_legacy_prompt(&t, "ai-first-cli-canon");
    let native = t.codex_skill();
    std::fs::create_dir_all(native.parent().unwrap()).unwrap();
    std::fs::write(&native, "FOREIGN NATIVE SKILL").unwrap();

    let out = run(&[
        "install",
        "ai-first-cli-canon",
        "--target",
        t.str(),
        "--agent",
        "codex",
    ]);
    assert_eq!(code(&out), 1);
    assert!(
        legacy.is_file(),
        "preflight conflict must prevent legacy cleanup"
    );
    assert_eq!(
        std::fs::read_to_string(native).unwrap(),
        "FOREIGN NATIVE SKILL"
    );
}

#[test]
fn reinstall_is_idempotent() {
    let t = Tmp::new("idem");
    assert_eq!(code(&run(&["install", "--target", t.str()])), 0);
    let first = std::fs::read(t.claude_skill()).unwrap();
    let out = run(&["install", "--target", t.str()]);
    assert_eq!(code(&out), 0);
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("unchanged"),
        "second install should report unchanged"
    );
    // Byte-identical after re-install.
    assert_eq!(std::fs::read(t.claude_skill()).unwrap(), first);
}

#[test]
fn json_report_is_well_formed() {
    let t = Tmp::new("json");
    let out = run(&["install", "--target", t.str(), "--json", "--dry-run"]);
    assert_eq!(code(&out), 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stdout = stdout.trim();
    assert!(stdout.starts_with('{') && stdout.ends_with('}'), "{stdout}");
    assert!(stdout.contains("\"schema_version\":1"));
    assert!(stdout.contains("\"verb\":\"skill install\""));
    assert!(stdout.contains("\"dry_run\":true"));
    assert!(stdout.contains("\"agent\":\"claude\""));
    assert!(stdout.contains("\"agent\":\"pi\""));
    assert!(stdout.contains("\"agent\":\"codex\""));
    assert!(stdout.contains("\"name\":\"cli-canon\""));
    assert!(stdout.contains("\"resource\":\"templates/review-report.md\""));
    assert!(stdout.contains("\"action\":\"install\""));
    assert!(stdout.contains("\"written\":0"));
    assert!(stdout.contains("\"exit_code\":0"));
}

#[test]
fn agent_flag_selects_a_single_form() {
    let t = Tmp::new("agent");
    assert_eq!(
        code(&run(&["install", "--target", t.str(), "--agent", "claude"])),
        0
    );
    assert!(t.claude_skill().is_file());
    assert!(!t.codex_skill().exists(), "codex form must not be written");
}

#[test]
fn each_single_runtime_selection_stays_within_its_target_layout() {
    for agent in ["claude", "pi", "codex"] {
        let t = Tmp::new(agent);
        assert_eq!(
            code(&run(&[
                "install",
                "ai-first-cli-canon",
                "--target",
                t.str(),
                "--agent",
                agent,
            ])),
            0
        );
        assert_eq!(t.path.join(".claude").exists(), agent == "claude");
        assert_eq!(t.path.join(".pi").exists(), agent == "pi");
        assert_eq!(t.path.join(".codex").exists(), agent == "codex");
        let expected = match agent {
            "claude" => ".claude/skills/ai-first-cli-canon/SKILL.md",
            "pi" => ".pi/agent/skills/ai-first-cli-canon/SKILL.md",
            "codex" => ".codex/skills/ai-first-cli-canon/SKILL.md",
            _ => unreachable!(),
        };
        let files = t.snapshot();
        assert_eq!(files.len(), 1, "{agent} install wrote unexpected files");
        assert_eq!(files[0].0, expected);
        assert!(!files[0].1.is_empty());
    }
}

#[test]
fn foreign_file_is_refused_without_force_then_overwritten_with_force() {
    let t = Tmp::new("foreign");
    let p = t.claude_skill();
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
    std::fs::write(&p, "HAND WRITTEN — KEEP").unwrap();

    // Without --force: refused, exit 1, file untouched.
    let out = run(&["install", "--target", t.str(), "--agent", "claude"]);
    assert_eq!(
        code(&out),
        1,
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(String::from_utf8_lossy(&out.stderr).contains("non-managed"));
    assert_eq!(std::fs::read_to_string(&p).unwrap(), "HAND WRITTEN — KEEP");

    // With --force: overwritten.
    let out = run(&[
        "install",
        "--target",
        t.str(),
        "--agent",
        "claude",
        "--force",
    ]);
    assert_eq!(code(&out), 0);
    assert!(std::fs::read_to_string(&p)
        .unwrap()
        .contains(&master_canon()));
}

#[test]
fn a_managed_stale_file_upgrades_without_force() {
    // A file carrying our provenance marker but a different body is a managed upgrade — no --force.
    let t = Tmp::new("upgrade");
    let p = t.codex_skill();
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
    std::fs::write(
        &p,
        "<!-- Installed by `project-canon skill install` — ai-first-cli-canon cli_version=0.0.0 schema_version=1. -->\n\nSTALE BODY",
    )
    .unwrap();
    let out = run(&["install", "--target", t.str(), "--agent", "codex"]);
    assert_eq!(
        code(&out),
        0,
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(std::fs::read_to_string(&p)
        .unwrap()
        .contains(&master_canon()));
}

#[test]
fn newer_on_disk_is_refused_without_force() {
    let t = Tmp::new("newer");
    let p = t.codex_skill();
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
    std::fs::write(
        &p,
        "<!-- Installed by `project-canon skill install` — ai-first-cli-canon cli_version=99.0.0 schema_version=1. -->\n\nFUTURE",
    )
    .unwrap();
    let out = run(&["install", "--target", t.str(), "--agent", "codex"]);
    assert_eq!(code(&out), 1);
    assert!(String::from_utf8_lossy(&out.stderr).contains("newer"));
}

#[test]
fn unknown_skill_name_is_a_usage_error() {
    let t = Tmp::new("unknown");
    let out = run(&["install", "nope", "--target", t.str()]);
    assert_eq!(code(&out), 1);
    assert!(String::from_utf8_lossy(&out.stderr).contains("nope"));
}

#[test]
fn bad_agent_is_a_usage_error() {
    let t = Tmp::new("badagent");
    let out = run(&["install", "--target", t.str(), "--agent", "emacs"]);
    assert_eq!(code(&out), 1);
    assert!(String::from_utf8_lossy(&out.stderr).contains("emacs"));
}

#[test]
fn unknown_flag_is_a_usage_error() {
    let t = Tmp::new("badflag");
    let out = run(&["install", "--target", t.str(), "--nope"]);
    assert_eq!(code(&out), 1);
    assert!(String::from_utf8_lossy(&out.stderr).contains("--nope"));
}

#[test]
fn malformed_env_is_a_usage_error_but_help_still_exits_zero() {
    let t = Tmp::new("env");
    let bad = base_command()
        .args(["skill", "install", "--target", t.str()])
        .env("PROJECT_CANON_TW_ENABLED", "not-a-bool")
        .output()
        .unwrap();
    assert_eq!(code(&bad), 1);
    // --help short-circuits before env validation.
    let help = base_command()
        .args(["skill", "install", "--help"])
        .env("PROJECT_CANON_TW_ENABLED", "not-a-bool")
        .output()
        .unwrap();
    assert_eq!(code(&help), 0);
    assert!(String::from_utf8_lossy(&help.stdout).contains("USAGE"));
}

#[test]
fn cli_canon_installs_complete_native_trees_for_every_runtime() {
    let t = Tmp::new("cli-canon-tree");
    let out = run(&["install", "cli-canon", "--target", t.str()]);
    assert_eq!(
        code(&out),
        0,
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );

    for agent in ["claude", "pi", "codex"] {
        for resource in [
            "SKILL.md",
            "templates/conformance-probes.md",
            "templates/generate-plan.md",
            "templates/review-report.md",
        ] {
            assert!(
                t.skill_resource(agent, "cli-canon", resource).is_file(),
                "missing {agent} resource {resource}"
            );
        }
        let skill =
            std::fs::read_to_string(t.skill_resource(agent, "cli-canon", "SKILL.md")).unwrap();
        assert!(skill.contains("cli_version:"));
        assert!(skill.contains("schema_version:"));
    }
}

#[test]
fn cli_canon_print_discovers_and_streams_each_native_resource_exactly() {
    let t = Tmp::new("cli-canon-print");
    for agent in ["pi", "codex"] {
        assert_eq!(
            code(&run(&[
                "install",
                "cli-canon",
                "--target",
                t.str(),
                "--agent",
                agent,
            ])),
            0
        );
        for resource in [
            "SKILL.md",
            "templates/conformance-probes.md",
            "templates/generate-plan.md",
            "templates/review-report.md",
        ] {
            let printed = run(&[
                "print",
                "cli-canon",
                "--agent",
                agent,
                "--resource",
                resource,
            ]);
            assert_eq!(code(&printed), 0);
            assert_eq!(
                printed.stdout,
                std::fs::read(t.skill_resource(agent, "cli-canon", resource)).unwrap()
            );
        }
    }

    let json = run(&["print", "cli-canon", "--agent", "codex", "--json"]);
    let stdout = String::from_utf8(json.stdout).unwrap();
    assert!(stdout.contains("\"resource\":\"SKILL.md\""));
    assert!(stdout.contains("templates/conformance-probes.md"));
    assert!(stdout.contains("templates/generate-plan.md"));
    assert!(stdout.contains("templates/review-report.md"));
    assert!(stdout.contains("\"path_in_repo\":\"skills/cli-canon/SKILL.md\""));

    let template = run(&[
        "print",
        "cli-canon",
        "--agent",
        "pi",
        "--resource",
        "templates/review-report.md",
        "--json",
    ]);
    assert!(String::from_utf8(template.stdout)
        .unwrap()
        .contains("\"path_in_repo\":\"skills/cli-canon/templates/review-report.md\""));
}

#[test]
fn cli_canon_reinstall_is_idempotent_for_the_whole_tree() {
    let t = Tmp::new("cli-canon-idem");
    let args = ["install", "cli-canon", "--target", t.str(), "--agent", "pi"];
    assert_eq!(code(&run(&args)), 0);
    let out = run(&args);
    assert_eq!(code(&out), 0);
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(stdout.contains("wrote 0 files, 4 unchanged"), "{stdout}");
}

#[test]
fn list_reports_the_shipped_skill() {
    let out = run(&["list"]);
    assert_eq!(code(&out), 0);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("ai-first-cli-canon"));
    assert!(text.contains("cli-canon"));

    let json = run(&["list", "--json"]);
    assert_eq!(code(&json), 0);
    let stdout = String::from_utf8_lossy(&json.stdout);
    assert!(stdout.contains("\"verb\":\"skill list\""));
    assert!(stdout.contains("\"name\":\"ai-first-cli-canon\""));
    assert!(stdout.contains("\"name\":\"cli-canon\""));
    assert!(stdout.contains("\"supported_agents\":[\"claude\",\"pi\",\"codex\"]"));
    assert!(stdout.contains("\"selection_flag\":\"--agent\""));
    assert!(stdout.contains("\"default\":\"all\""));
    assert!(stdout.contains("\"accepted_values\":[\"claude\",\"pi\",\"codex\",\"all\"]"));
    assert!(stdout.contains("\"target_flag\":\"--target\""));
    assert!(stdout.contains("\"dry_run_flag\":\"--dry-run\""));
    assert!(stdout.contains("\"force_flag\":\"--force\""));
    assert!(stdout.contains("\"interactive\":false"));
    assert_eq!(stdout.matches("\"form\":\"agent-skill-tree\"").count(), 3);
    assert!(stdout.contains(".codex/skills/<name>/..."));
    assert!(!stdout.contains("self-contained-prompt"));
    assert!(stdout.contains("templates/conformance-probes.md"));
    assert!(stdout.contains("\"cli_version\""));
}

#[test]
fn print_is_byte_identical_to_what_install_writes() {
    // §16: print's output must equal the installed bytes for that agent.
    let t = Tmp::new("print");
    assert_eq!(code(&run(&["install", "--target", t.str()])), 0);
    let installed = std::fs::read_to_string(t.claude_skill()).unwrap();
    let printed = run(&["print", "ai-first-cli-canon", "--agent", "claude"]);
    assert_eq!(code(&printed), 0);
    assert_eq!(String::from_utf8_lossy(&printed.stdout), installed);
}

#[test]
fn print_json_carries_metadata_and_content() {
    let out = run(&["print", "ai-first-cli-canon", "--json"]);
    assert_eq!(code(&out), 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("\"name\":\"ai-first-cli-canon\""));
    assert!(stdout.contains("\"skill_schema_version\":2"));
    assert!(stdout.contains("\"path_in_repo\":\"AGENTS-AI-FIRST-CLI.md\""));
    assert!(stdout.contains("\"content\":"));
    assert!(stdout.contains("\"exit_code\":0"));
}

#[test]
fn show_is_an_alias_for_print() {
    // §15 names the read-only streamer `show`; §16 names it `print`. Both must work identically.
    let print = run(&["print", "ai-first-cli-canon", "--agent", "codex"]);
    let show = run(&["show", "ai-first-cli-canon", "--agent", "codex"]);
    assert_eq!(code(&print), 0);
    assert_eq!(code(&show), 0);
    assert_eq!(print.stdout, show.stdout);
}

#[test]
fn print_codex_is_byte_identical_to_install() {
    // §16 for the native Codex tree too.
    let t = Tmp::new("print-codex");
    assert_eq!(
        code(&run(&["install", "--target", t.str(), "--agent", "codex"])),
        0
    );
    let installed = std::fs::read_to_string(t.codex_skill()).unwrap();
    let printed = run(&["print", "ai-first-cli-canon", "--agent", "codex"]);
    assert_eq!(String::from_utf8_lossy(&printed.stdout), installed);
}

#[test]
fn list_and_print_reject_help_inline_value() {
    // Strict §1 parsing is uniform: `--help=x` is a usage error in every subcommand.
    assert_eq!(code(&run(&["list", "--help=x"])), 1);
    assert_eq!(code(&run(&["print", "--help=x"])), 1);
}

#[test]
fn list_and_print_refuse_a_malformed_env() {
    // env validation is uniform across all three subcommands, not just install.
    for sub in [
        ["list"].as_slice(),
        ["print", "ai-first-cli-canon"].as_slice(),
    ] {
        let out = base_command()
            .arg("skill")
            .args(sub)
            .env("PROJECT_CANON_TW_ENABLED", "not-a-bool")
            .output()
            .unwrap();
        assert_eq!(code(&out), 1, "sub {sub:?} should reject a malformed env");
    }
}

#[test]
fn list_json_envelope_is_consistent() {
    let out = run(&["list", "--json"]);
    assert_eq!(code(&out), 0);
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("\"verb\":\"skill list\""));
    assert!(stdout.contains("\"exit_code\":0"));
    // Top-level cli_version + the per-skill skill_schema_version key (uniform with print).
    assert!(stdout.contains("\"cli_version\":"));
    assert!(stdout.contains("\"skill_schema_version\":2"));
}

#[test]
fn blocked_install_emits_a_json_error_envelope() {
    // Under --json, a blocking conflict must still yield a structured envelope, not only stderr.
    let t = Tmp::new("blocked-json");
    let p = t.claude_skill();
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
    std::fs::write(&p, "HAND WRITTEN").unwrap();
    let out = run(&[
        "install",
        "--target",
        t.str(),
        "--agent",
        "claude",
        "--json",
    ]);
    assert_eq!(code(&out), 1);
    assert!(out.stdout.is_empty(), "failure must not write stdout");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.trim().starts_with('{'),
        "expected JSON error: {stderr}"
    );
    assert!(stderr.contains("\"schema_version\":1"));
    assert!(stderr.contains("\"code\":\"already_exists\""));
    // The foreign file is untouched.
    assert_eq!(std::fs::read_to_string(&p).unwrap(), "HAND WRITTEN");
}

#[cfg(unix)]
#[test]
fn a_symlink_at_the_target_is_refused_and_not_followed() {
    // A planted final-path symlink must NOT be written through to its target (write-through would
    // clobber a foreign file, e.g. ~/.ssh/...). It is refused as a conflict; --force replaces the
    // link itself (via rename), never the file it points at.
    let t = Tmp::new("symlink");
    let sentinel = t.path.join("sentinel.txt");
    std::fs::write(&sentinel, "DO NOT TOUCH").unwrap();
    let link = t.codex_skill();
    std::fs::create_dir_all(link.parent().unwrap()).unwrap();
    std::os::unix::fs::symlink(&sentinel, &link).unwrap();

    let out = run(&["install", "--target", t.str(), "--agent", "codex"]);
    assert_eq!(
        code(&out),
        1,
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    // The symlink's target was never written through.
    assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "DO NOT TOUCH");

    // --force replaces the link with a real file; the sentinel is still untouched.
    let out = run(&[
        "install",
        "--target",
        t.str(),
        "--agent",
        "codex",
        "--force",
    ]);
    assert_eq!(code(&out), 0);
    assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "DO NOT TOUCH");
    assert!(std::fs::symlink_metadata(&link)
        .unwrap()
        .file_type()
        .is_file());
    assert!(std::fs::read_to_string(&link)
        .unwrap()
        .contains(&master_canon()));
}

#[cfg(unix)]
#[test]
fn an_intermediate_runtime_symlink_is_refused_without_writing_outside_target() {
    let t = Tmp::new("parent-symlink");
    let external = Tmp::new("parent-symlink-external");
    std::os::unix::fs::symlink(&external.path, t.path.join(".claude")).unwrap();

    let out = run(&[
        "install",
        "ai-first-cli-canon",
        "--target",
        t.str(),
        "--agent",
        "claude",
    ]);
    assert_eq!(code(&out), 2);
    assert!(String::from_utf8_lossy(&out.stderr).contains("may escape --target"));
    assert!(external.snapshot().is_empty());
}

#[cfg(unix)]
#[test]
fn a_nested_runtime_symlink_is_refused_but_a_symlinked_target_is_allowed() {
    let t = Tmp::new("nested-parent-symlink");
    let external = Tmp::new("nested-parent-symlink-external");
    std::fs::create_dir_all(t.path.join(".pi/agent")).unwrap();
    std::os::unix::fs::symlink(&external.path, t.path.join(".pi/agent/skills")).unwrap();

    let out = run(&[
        "install",
        "ai-first-cli-canon",
        "--target",
        t.str(),
        "--agent",
        "pi",
    ]);
    assert_eq!(code(&out), 2);
    assert!(String::from_utf8_lossy(&out.stderr).contains("may escape --target"));
    assert!(external.snapshot().is_empty());

    let link_holder = Tmp::new("symlinked-target-holder");
    let target_link = link_holder.path.join("declared-target");
    std::os::unix::fs::symlink(&external.path, &target_link).unwrap();
    let out = run(&[
        "install",
        "ai-first-cli-canon",
        "--target",
        target_link.to_str().unwrap(),
        "--agent",
        "codex",
    ]);
    assert_eq!(code(&out), 0, "{}", String::from_utf8_lossy(&out.stderr));
    assert!(external
        .path
        .join(".codex/skills/ai-first-cli-canon/SKILL.md")
        .is_file());
}

#[test]
fn print_unknown_name_is_a_usage_error() {
    let out = run(&["print", "nope"]);
    assert_eq!(code(&out), 1);
    assert!(String::from_utf8_lossy(&out.stderr).contains("nope"));
}

#[test]
fn install_never_touches_this_repos_real_dotclaude() {
    // Defence-in-depth: a bare install with no --target must resolve $HOME, and these tests set
    // HOME to a temp dir so even that path is hermetic. Assert the write lands under the temp HOME.
    let home = Tmp::new("home");
    let out = base_command()
        .args(["skill", "install", "--agent", "codex"])
        .env("HOME", home.str())
        .output()
        .unwrap();
    assert_eq!(
        code(&out),
        0,
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(home
        .path
        .join(".codex/skills/ai-first-cli-canon/SKILL.md")
        .is_file());
}