cmx-core 0.3.0

Embeddable core for installing agent skills across platforms — cmx-aware lockfile tracking, plan/apply installs, version guards
Documentation
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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
use anyhow::{Context, Result, bail, ensure};
use chrono::{DateTime, TimeZone, Utc};
use serde::Serialize;
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};

use crate::config;
use crate::frontmatter;
use crate::lockfile;
use crate::platform::Platform;
use crate::skill_fs::{self, SkillFile};
use crate::skill_install::{
    BundledSkill, InstallPlan, Report, Scope, SkillInstaller, TargetAction, ToolIdentity,
};
use crate::targets;
use crate::test_support::TestContext;
use crate::types::{ArtifactKind, CmxConfig, InstallScope, LockEntry, LockFile, LockSource};

const FIXTURE_TOOL_NAME: &str = "fixture-tool";
const FIXTURE_VERSION: &str = "2.4.6";

/// Generate the committed language-neutral conformance fixtures under `out`.
///
/// The observable behavior always comes from the in-memory `test-support`
/// oracle and a fixed injected clock. `out` is the only real filesystem write.
pub fn generate_conformance_fixtures(out: &Path) -> Result<()> {
    recreate_dir(out)?;
    write_readme(&out.join("README.md"))?;
    generate_checksum_fixtures(&out.join("checksum"))?;
    generate_frontmatter_fixtures(&out.join("frontmatter"))?;
    generate_version_guard_fixtures(&out.join("version-guard"))?;
    generate_paths_fixtures(&out.join("paths"))?;
    generate_target_resolve_fixtures(&out.join("target-resolve"))?;
    generate_install_e2e_fixtures(&out.join("install-e2e"))?;
    Ok(())
}

fn fixed_time() -> DateTime<Utc> {
    Utc.with_ymd_and_hms(2026, 7, 5, 12, 0, 0)
        .single()
        .expect("fixed conformance timestamp is valid")
}

fn fixed_timestamp() -> String {
    fixed_time().to_rfc3339()
}

fn recreate_dir(path: &Path) -> Result<()> {
    if path.exists() {
        fs::remove_dir_all(path)
            .with_context(|| format!("remove existing fixture dir {}", path.display()))?;
    }
    fs::create_dir_all(path).with_context(|| format!("create fixture dir {}", path.display()))?;
    Ok(())
}

fn ensure_parent(path: &Path) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .with_context(|| format!("create parent dir {}", parent.display()))?;
    }
    Ok(())
}

fn write_bytes(path: &Path, bytes: &[u8]) -> Result<()> {
    ensure_parent(path)?;
    fs::write(path, bytes).with_context(|| format!("write {}", path.display()))
}

fn write_json<T>(path: &Path, value: &T) -> Result<()>
where
    T: Serialize,
{
    let bytes = serde_json::to_vec_pretty(value)?;
    write_bytes(path, &bytes)
}

fn normalized_path_string(path: &Path) -> String {
    use std::path::Component;
    // Join the *non-root* components with `/`, re-adding a single leading slash
    // for absolute paths. Joining every component (including `Component::RootDir`,
    // which stringifies to `/`) would emit a doubled leading slash — `//home/...`
    // — for absolute dest_dirs.
    let mut absolute = false;
    let parts: Vec<String> = path
        .components()
        .filter_map(|component| match component {
            Component::RootDir => {
                absolute = true;
                None
            }
            other => Some(other.as_os_str().to_string_lossy().into_owned()),
        })
        .collect();
    let joined = parts.join("/");
    if absolute {
        format!("/{joined}")
    } else {
        joined
    }
}

fn bundle() -> BundledSkill {
    BundledSkill::from_files(vec![
        SkillFile::text(
            "SKILL.md",
            "---\nname: fixture-tool\ndescription: Fixture skill\nmetadata:\n  author: Fixture Bot\n---\n# Fixture skill\n",
        ),
        SkillFile::text("scripts/tool.py", "print('fixture tool')\n"),
    ])
}

fn tool_identity(version: &str) -> ToolIdentity {
    ToolIdentity::new(FIXTURE_TOOL_NAME, version)
}

fn installer(version: &str) -> SkillInstaller {
    SkillInstaller::new(tool_identity(version))
}

fn reconciled_files(skill: &BundledSkill, version: &str) -> Vec<SkillFile> {
    frontmatter::reconcile_skill_version(&skill.files, version)
}

fn bundled_checksum(skill: &BundledSkill, version: &str) -> String {
    skill_fs::checksum_bundled(&reconciled_files(skill, version))
}

fn skill_dest(paths: &crate::paths::ConfigPaths, scope: InstallScope) -> PathBuf {
    paths
        .with_platform(Platform::Claude)
        .require_install_dir(ArtifactKind::Skill, scope)
        .expect("claude supports skill installs")
        .join(FIXTURE_TOOL_NAME)
}

fn bundled_lock_entry(version: Option<&str>, checksum: &str) -> LockEntry {
    LockEntry {
        artifact_type: ArtifactKind::Skill,
        version: version.map(str::to_string),
        installed_at: fixed_timestamp(),
        source: LockSource {
            repo: format!("bundled:{FIXTURE_TOOL_NAME}"),
            path: format!("skills/{FIXTURE_TOOL_NAME}"),
        },
        source_checksum: checksum.to_string(),
        installed_checksum: checksum.to_string(),
    }
}

fn save_bundled_lock(
    test: &TestContext,
    scope: InstallScope,
    version: Option<&str>,
    checksum: &str,
) -> Result<()> {
    let mut packages = BTreeMap::new();
    packages.insert(FIXTURE_TOOL_NAME.to_string(), bundled_lock_entry(version, checksum));
    let lock = LockFile {
        version: 1,
        packages,
    };
    let paths = test.paths.with_platform(Platform::Claude);
    lockfile::save(&lock, scope, &test.fs, &paths)
}

fn write_bundle_version(
    test: &TestContext,
    scope: InstallScope,
    skill: &BundledSkill,
    version: &str,
) -> Result<String> {
    let files = reconciled_files(skill, version);
    let checksum = skill_fs::checksum_bundled(&files);
    skill_fs::write_skill_files(&skill_dest(&test.paths, scope), &files, &test.fs)?;
    Ok(checksum)
}

fn write_drifted_bundle_version(
    test: &TestContext,
    scope: InstallScope,
    skill: &BundledSkill,
    version: &str,
) -> Result<String> {
    let mut files = reconciled_files(skill, version);
    let checksum = skill_fs::checksum_bundled(&files);
    let drifted = files
        .iter_mut()
        .find(|file| file.rel_path == Path::new("scripts/tool.py"))
        .context("bundle contains scripts/tool.py")?;
    drifted.bytes = b"print('drifted local edit')\n".to_vec();
    skill_fs::write_skill_files(&skill_dest(&test.paths, scope), &files, &test.fs)?;
    Ok(checksum)
}

fn all_lock_paths(paths: &crate::paths::ConfigPaths, scope: InstallScope) -> BTreeSet<PathBuf> {
    Platform::ALL
        .iter()
        .map(|platform| paths.with_platform(*platform).lock_path(scope))
        .collect()
}

fn normalized_fixture_path(path: &Path) -> PathBuf {
    if path.is_absolute() {
        path.strip_prefix(Path::new("/"))
            .expect("absolute path always strips root")
            .to_path_buf()
    } else {
        PathBuf::from("project").join(path)
    }
}

fn snapshot_tree(test: &TestContext, scope: InstallScope) -> BTreeMap<PathBuf, Vec<u8>> {
    let lock_paths = all_lock_paths(&test.paths, scope);
    test.fs
        .snapshot_files()
        .into_iter()
        .filter(|(path, _)| !lock_paths.contains(path))
        .map(|(path, bytes)| (normalized_fixture_path(&path), bytes))
        .collect()
}

fn snapshot_locks(test: &TestContext, scope: InstallScope) -> Result<BTreeMap<String, Value>> {
    let mut locks = BTreeMap::new();
    for platform in Platform::ALL {
        let path = test.paths.with_platform(platform).lock_path(scope);
        if let Some(bytes) = test.fs.get_file_content(&path) {
            let name = path
                .file_name()
                .context("lock path has file name")?
                .to_string_lossy()
                .to_string();
            let value = serde_json::from_slice::<Value>(&bytes)
                .with_context(|| format!("parse fake lock {}", path.display()))?;
            locks.insert(name, value);
        }
    }
    Ok(locks)
}

fn write_tree_snapshot(root: &Path, files: &BTreeMap<PathBuf, Vec<u8>>) -> Result<()> {
    fs::create_dir_all(root).with_context(|| format!("create {}", root.display()))?;
    for (rel_path, bytes) in files {
        write_bytes(&root.join(rel_path), bytes)?;
    }
    Ok(())
}

fn write_lock_snapshot(root: &Path, locks: &BTreeMap<String, Value>) -> Result<()> {
    fs::create_dir_all(root).with_context(|| format!("create {}", root.display()))?;
    for (name, value) in locks {
        write_json(&root.join(name), value)?;
    }
    Ok(())
}

fn action_kind(action: &TargetAction) -> &'static str {
    match action {
        TargetAction::Install => "install",
        TargetAction::Update { .. } => "update",
        TargetAction::Skip => "skip",
        TargetAction::DriftedSkip { .. } => "drifted-skip",
        TargetAction::RefuseNewer { .. } => "refuse-newer",
        TargetAction::Downgrade { .. } => "downgrade",
    }
}

#[derive(Serialize)]
struct ActionSnapshot {
    kind: String,
    from: Option<String>,
    installed: Option<String>,
    will_write: bool,
    blocked: bool,
}

fn snapshot_action(action: &TargetAction) -> ActionSnapshot {
    match action {
        TargetAction::Install | TargetAction::Skip => ActionSnapshot {
            kind: action_kind(action).to_string(),
            from: None,
            installed: None,
            will_write: action.will_write(),
            blocked: action.is_blocked(),
        },
        TargetAction::Update { from } => ActionSnapshot {
            kind: action_kind(action).to_string(),
            from: from.clone(),
            installed: None,
            will_write: action.will_write(),
            blocked: action.is_blocked(),
        },
        TargetAction::DriftedSkip { installed } | TargetAction::RefuseNewer { installed } => {
            ActionSnapshot {
                kind: action_kind(action).to_string(),
                from: None,
                installed: Some(installed.clone()),
                will_write: action.will_write(),
                blocked: action.is_blocked(),
            }
        }
        TargetAction::Downgrade { from } => ActionSnapshot {
            kind: action_kind(action).to_string(),
            from: Some(from.clone()),
            installed: None,
            will_write: action.will_write(),
            blocked: action.is_blocked(),
        },
    }
}

#[derive(Serialize)]
struct ChecksumManifest {
    schema_version: u32,
    cases: Vec<ChecksumCase>,
}

#[derive(Serialize)]
struct ChecksumCase {
    name: String,
    description: String,
    input: InlineFilesInput,
    expected: ChecksumExpected,
}

#[derive(Serialize)]
struct InlineFilesInput {
    files: Vec<TextFixtureFile>,
}

#[derive(Serialize)]
struct TextFixtureFile {
    path: String,
    content_utf8: String,
}

#[derive(Serialize)]
struct ChecksumExpected {
    sha256: String,
    canonical_order: Vec<String>,
    canonical_included_paths: Vec<String>,
}

fn checksum_case(name: &str, description: &str, files: Vec<(&str, &str)>) -> ChecksumCase {
    let skill_files = files
        .iter()
        .map(|(path, content)| SkillFile::text(path, content))
        .collect::<Vec<_>>();
    let canonical = skill_fs::canonical_files(&skill_files);
    let canonical_order = canonical
        .iter()
        .map(|file| normalized_path_string(&file.rel_path))
        .collect::<Vec<_>>();
    let checksum = skill_fs::checksum_bundled(&skill_files);

    ChecksumCase {
        name: name.to_string(),
        description: description.to_string(),
        input: InlineFilesInput {
            files: files
                .into_iter()
                .map(|(path, content)| TextFixtureFile {
                    path: path.to_string(),
                    content_utf8: content.to_string(),
                })
                .collect(),
        },
        expected: ChecksumExpected {
            sha256: checksum,
            canonical_order: canonical_order.clone(),
            canonical_included_paths: canonical_order,
        },
    }
}

fn generate_checksum_fixtures(out: &Path) -> Result<()> {
    fs::create_dir_all(out).with_context(|| format!("create {}", out.display()))?;

    let string_sort = checksum_case(
        "string-sort-a-dot-slash",
        "Pins SPEC §11.4 string sorting for `a`, `a.b`, and `a/b` using an inline file set that cannot exist on disk.",
        vec![("a/b", "nested\n"), ("a.b", "dotted\n"), ("a", "bare\n")],
    );
    ensure!(
        string_sort.expected.canonical_order == vec!["a", "a.b", "a/b"],
        "checksum oracle no longer sorts `a`, `a.b`, `a/b` as SPEC §11.4 requires"
    );

    let filter = checksum_case(
        "canonical-filter",
        "Exercises dotfile, dotdir, transient-name, and `.pyc` filtering while leaving canonical files intact.",
        vec![
            ("SKILL.md", "# skill\n"),
            ("scripts/tool.py", "print('ok')\n"),
            (".hidden", "secret\n"),
            ("scripts/.env", "TOKEN=1\n"),
            ("node_modules/pkg/index.js", "vendored\n"),
            ("scripts/node_modules/pkg/index.js", "nested vendored\n"),
            ("__pycache__/tool.cpython-313.pyc", "compiled\n"),
            ("scripts/tool.pyc", "compiled\n"),
            (".DS_Store", "mac metadata\n"),
            ("nested/.git/config", "[core]\n"),
        ],
    );

    let manifest = ChecksumManifest {
        schema_version: 1,
        cases: vec![string_sort, filter],
    };
    write_json(&out.join("manifest.json"), &manifest)
}

#[derive(Serialize)]
struct FrontmatterManifest {
    schema_version: u32,
    cases: Vec<FrontmatterCase>,
}

#[derive(Serialize)]
struct FrontmatterCase {
    name: String,
    description: String,
    input: FrontmatterInput,
    expected: FrontmatterExpected,
}

#[derive(Serialize)]
struct FrontmatterInput {
    version: String,
    skill_md_path: String,
}

#[derive(Serialize)]
struct FrontmatterExpected {
    skill_md_path: String,
    byte_exact: bool,
    idempotent_second_pass: bool,
}

struct FrontmatterFixture<'a> {
    name: &'a str,
    description: &'a str,
    version: &'a str,
    input: Vec<u8>,
    idempotent_second_pass: bool,
}

fn reconcile_skill_md_bytes(input: &[u8], version: &str) -> Result<Vec<u8>> {
    let files = vec![SkillFile {
        rel_path: PathBuf::from("SKILL.md"),
        bytes: input.to_vec(),
    }];
    let reconciled = frontmatter::reconcile_skill_version(&files, version);
    reconciled
        .into_iter()
        .find(|file| file.rel_path == Path::new("SKILL.md"))
        .map(|file| file.bytes)
        .context("reconciled bundle still contains SKILL.md")
}

fn generate_frontmatter_fixtures(out: &Path) -> Result<()> {
    fs::create_dir_all(out).with_context(|| format!("create {}", out.display()))?;

    let fixtures = vec![
        FrontmatterFixture {
            name: "no-fence",
            description: "Leaves SKILL.md unchanged when no leading frontmatter fence exists.",
            version: FIXTURE_VERSION,
            input: b"# No frontmatter\n\nBody only.\n".to_vec(),
            idempotent_second_pass: false,
        },
        FrontmatterFixture {
            name: "empty-metadata-block",
            description: "Adds `metadata.version` using the default two-space indent when the metadata block is empty.",
            version: FIXTURE_VERSION,
            input: b"---\nname: Empty metadata\nmetadata:\n---\n# Body\n".to_vec(),
            idempotent_second_pass: false,
        },
        FrontmatterFixture {
            name: "existing-metadata-version",
            description: "Replaces an existing `metadata.version` value in place.",
            version: FIXTURE_VERSION,
            input: b"---\nname: Existing\nmetadata:\n  version: \"0.0.0\"\n  author: Test\n---\n# Body\n".to_vec(),
            idempotent_second_pass: false,
        },
        FrontmatterFixture {
            name: "shadowing-top-level-version",
            description: "Removes a shadowing top-level `version:` key and writes `metadata.version` instead.",
            version: FIXTURE_VERSION,
            input: b"---\nname: Shadow\nversion: 9.9.9\nmetadata:\n  author: Test\n---\n# Body\n".to_vec(),
            idempotent_second_pass: false,
        },
        FrontmatterFixture {
            name: "crlf-line-endings",
            description: "Captures the reference output for CRLF frontmatter input exactly as emitted by the Rust oracle.",
            version: FIXTURE_VERSION,
            input: b"---\r\nname: CrLf\r\nmetadata:\r\n  version: \"0.0.0\"\r\n---\r\n# Body\r\n".to_vec(),
            idempotent_second_pass: false,
        },
        FrontmatterFixture {
            name: "metadata-indent-four-spaces",
            description: "Inserts `metadata.version` using the indentation of the metadata block's first child.",
            version: FIXTURE_VERSION,
            input: b"---\nmetadata:\n    author: Test\n---\n# Body\n".to_vec(),
            idempotent_second_pass: false,
        },
        FrontmatterFixture {
            name: "folded-description-before-version",
            description: "Updates `metadata.version` without disturbing a folded `description:` block above it.",
            version: FIXTURE_VERSION,
            input: b"---\nmetadata:\n  description: >\n    line one\n    line two\n  version: \"0.0.0\"\n---\n# Body\n".to_vec(),
            idempotent_second_pass: false,
        },
        FrontmatterFixture {
            name: "idempotent-already-reconciled",
            description: "Re-running reconciliation against already-correct bytes yields the same byte stream.",
            version: FIXTURE_VERSION,
            input: format!(
                "---\nmetadata:\n  version: \"{FIXTURE_VERSION}\"\n  author: Test\n---\n# Body\n"
            )
            .into_bytes(),
            idempotent_second_pass: true,
        },
    ];

    let mut manifest_cases = Vec::new();
    for fixture in fixtures {
        let case_dir = out.join(fixture.name);
        let input_path = case_dir.join("input").join("SKILL.md");
        let expected_path = case_dir.join("expected").join("SKILL.md");
        let expected_bytes = reconcile_skill_md_bytes(&fixture.input, fixture.version)?;

        write_bytes(&input_path, &fixture.input)?;
        write_bytes(&expected_path, &expected_bytes)?;

        if fixture.idempotent_second_pass {
            let second_pass = reconcile_skill_md_bytes(&expected_bytes, fixture.version)?;
            ensure!(
                second_pass == expected_bytes,
                "frontmatter idempotency fixture `{}` no longer round-trips byte-for-byte",
                fixture.name
            );
        }

        manifest_cases.push(FrontmatterCase {
            name: fixture.name.to_string(),
            description: fixture.description.to_string(),
            input: FrontmatterInput {
                version: fixture.version.to_string(),
                skill_md_path: format!("{}/input/SKILL.md", fixture.name),
            },
            expected: FrontmatterExpected {
                skill_md_path: format!("{}/expected/SKILL.md", fixture.name),
                byte_exact: true,
                idempotent_second_pass: fixture.idempotent_second_pass,
            },
        });
    }

    let manifest = FrontmatterManifest {
        schema_version: 1,
        cases: manifest_cases,
    };
    write_json(&out.join("manifest.json"), &manifest)
}

#[derive(Serialize)]
struct VersionGuardManifest {
    schema_version: u32,
    cases: Vec<VersionGuardCase>,
}

#[derive(Serialize)]
struct VersionGuardCase {
    name: String,
    description: String,
    input: VersionGuardInput,
    expected: ActionSnapshot,
}

#[derive(Serialize)]
struct VersionGuardInput {
    bundled_version: String,
    tracked: bool,
    installed_version: Option<String>,
    disk_state: String,
    force: bool,
}

fn observe_version_guard(
    bundled_version: &str,
    tracked: bool,
    installed_version: Option<&str>,
    disk_state: &str,
    force: bool,
) -> Result<ActionSnapshot> {
    let test = TestContext::at(fixed_time());
    let skill = bundle();
    let checksum = bundled_checksum(&skill, bundled_version);

    if tracked {
        save_bundled_lock(&test, InstallScope::Global, installed_version, &checksum)?;
    }

    match disk_state {
        "missing" => {}
        "matches-source" => {
            write_bundle_version(&test, InstallScope::Global, &skill, bundled_version)?;
        }
        "drifted" => {
            write_drifted_bundle_version(&test, InstallScope::Global, &skill, bundled_version)?;
        }
        other => bail!("unknown version-guard disk state `{other}`"),
    }

    let plan = installer(bundled_version).plan(&skill, Scope::Global, force, &test.ctx())?;
    ensure!(
        plan.targets.len() == 1,
        "version-guard fixtures expect a single target, got {}",
        plan.targets.len()
    );
    Ok(snapshot_action(&plan.targets[0].action))
}

fn version_guard_semver_install_inputs() -> Vec<(&'static str, &'static str, VersionGuardInput)> {
    vec![
        (
            "untracked-install",
            "No lock entry always plans an install.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: false,
                installed_version: None,
                disk_state: "missing".to_string(),
                force: false,
            },
        ),
        (
            "tracked-version-absent-update",
            "A tracked entry with no installed version compares as Less and updates.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: None,
                disk_state: "matches-source".to_string(),
                force: false,
            },
        ),
        (
            "older-update",
            "An older installed semver version updates.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: Some("1.9.0".to_string()),
                disk_state: "matches-source".to_string(),
                force: false,
            },
        ),
        (
            "equal-missing-disk-install",
            "An equal tracked version with no on-disk copy installs again.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: Some(FIXTURE_VERSION.to_string()),
                disk_state: "missing".to_string(),
                force: false,
            },
        ),
        (
            "equal-same-skip",
            "An equal tracked version with matching bytes skips.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: Some(FIXTURE_VERSION.to_string()),
                disk_state: "matches-source".to_string(),
                force: false,
            },
        ),
        (
            "equal-drifted-skip",
            "An equal tracked version with local edits drift-skips when force is false.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: Some(FIXTURE_VERSION.to_string()),
                disk_state: "drifted".to_string(),
                force: false,
            },
        ),
        (
            "equal-drifted-force-update",
            "An equal tracked version with local edits updates when force is true.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: Some(FIXTURE_VERSION.to_string()),
                disk_state: "drifted".to_string(),
                force: true,
            },
        ),
    ]
}

fn version_guard_semver_newer_inputs() -> Vec<(&'static str, &'static str, VersionGuardInput)> {
    vec![
        (
            "newer-refuse",
            "A newer installed semver version blocks the plan without force.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: Some("9.0.0".to_string()),
                disk_state: "matches-source".to_string(),
                force: false,
            },
        ),
        (
            "newer-force-downgrade",
            "A newer installed semver version downgrades when force is true.",
            VersionGuardInput {
                bundled_version: FIXTURE_VERSION.to_string(),
                tracked: true,
                installed_version: Some("9.0.0".to_string()),
                disk_state: "matches-source".to_string(),
                force: true,
            },
        ),
    ]
}

fn version_guard_non_semver_inputs() -> Vec<(&'static str, &'static str, VersionGuardInput)> {
    vec![
        (
            "non-semver-equal-fallback",
            "Equal non-semver strings fall back to string equality and then to normal equal-version handling.",
            VersionGuardInput {
                bundled_version: "dev-build".to_string(),
                tracked: true,
                installed_version: Some("dev-build".to_string()),
                disk_state: "matches-source".to_string(),
                force: false,
            },
        ),
        (
            "non-semver-unequal-fallback",
            "Unequal non-semver strings fall back to Less and update.",
            VersionGuardInput {
                bundled_version: "dev-build".to_string(),
                tracked: true,
                installed_version: Some("nightly".to_string()),
                disk_state: "matches-source".to_string(),
                force: false,
            },
        ),
    ]
}

fn version_guard_inputs() -> Vec<(&'static str, &'static str, VersionGuardInput)> {
    let mut inputs = version_guard_semver_install_inputs();
    inputs.extend(version_guard_semver_newer_inputs());
    inputs.extend(version_guard_non_semver_inputs());
    inputs
}

fn generate_version_guard_fixtures(out: &Path) -> Result<()> {
    fs::create_dir_all(out).with_context(|| format!("create {}", out.display()))?;
    let mut cases = Vec::new();
    for (name, description, input) in version_guard_inputs() {
        let expected = observe_version_guard(
            &input.bundled_version,
            input.tracked,
            input.installed_version.as_deref(),
            &input.disk_state,
            input.force,
        )?;
        cases.push(VersionGuardCase {
            name: name.to_string(),
            description: description.to_string(),
            input,
            expected,
        });
    }

    let manifest = VersionGuardManifest {
        schema_version: 1,
        cases,
    };
    write_json(&out.join("manifest.json"), &manifest)
}

#[derive(Serialize)]
struct PathsManifest {
    schema_version: u32,
    cases: Vec<PathCase>,
}

#[derive(Serialize)]
struct PathCase {
    name: String,
    input: PathInput,
    expected: PathExpected,
}

#[derive(Serialize)]
struct PathInput {
    platform: String,
    kind: String,
    scope: String,
}

#[derive(Serialize)]
struct PathExpected {
    subpath: String,
    lockname: String,
}

fn generate_paths_fixtures(out: &Path) -> Result<()> {
    fs::create_dir_all(out).with_context(|| format!("create {}", out.display()))?;

    let mut cases = Vec::new();
    for scope in InstallScope::ALL {
        for platform in Platform::ALL {
            let paths = crate::paths::ConfigPaths::for_test_with_platform(
                PathBuf::from("/home/testuser"),
                PathBuf::from("/home/testuser/.config/context-mixer"),
                platform,
            );
            let subpath = platform
                .install_subpath(ArtifactKind::Skill, scope)
                .expect("every platform supports skills");
            let lockname = paths
                .lock_path(scope)
                .file_name()
                .context("lock path has file name")?
                .to_string_lossy()
                .to_string();

            cases.push(PathCase {
                name: format!("{}-{}", platform, scope.label()),
                input: PathInput {
                    platform: platform.to_string(),
                    kind: "skill".to_string(),
                    scope: scope.label().to_string(),
                },
                expected: PathExpected {
                    subpath: normalized_path_string(&subpath),
                    lockname,
                },
            });
        }
    }

    let manifest = PathsManifest {
        schema_version: 1,
        cases,
    };
    write_json(&out.join("manifest.json"), &manifest)
}

#[derive(Serialize)]
struct TargetResolveManifest {
    schema_version: u32,
    cases: Vec<TargetResolveCase>,
}

#[derive(Serialize)]
struct TargetResolveCase {
    name: String,
    description: String,
    input: TargetResolveInput,
    expected: TargetResolveExpected,
}

#[derive(Serialize)]
struct TargetResolveInput {
    scope: String,
    config_platforms: Vec<String>,
    non_empty_locks: Vec<String>,
}

#[derive(Serialize)]
struct TargetResolveExpected {
    resolved_platforms: Vec<String>,
}

fn observe_target_resolution(
    config_platforms: &[Platform],
    non_empty_locks: &[Platform],
) -> Result<Vec<String>> {
    let test = TestContext::at(fixed_time());
    if !config_platforms.is_empty() {
        let cfg = CmxConfig {
            platforms: config_platforms.to_vec(),
            ..Default::default()
        };
        config::save_config(&cfg, &test.fs, &test.paths)?;
    }

    for platform in non_empty_locks {
        let mut packages = BTreeMap::new();
        packages.insert(
            "existing-skill".to_string(),
            bundled_lock_entry(Some("1.0.0"), "sha256:existing"),
        );
        let lock = LockFile {
            version: 1,
            packages,
        };
        let paths = test.paths.with_platform(*platform);
        lockfile::save(&lock, InstallScope::Global, &test.fs, &paths)?;
    }

    let resolved =
        targets::resolve_targets(None, ArtifactKind::Skill, InstallScope::Global, &test.ctx())?;
    Ok(resolved.into_iter().map(|platform| platform.to_string()).collect())
}

fn generate_target_resolve_fixtures(out: &Path) -> Result<()> {
    fs::create_dir_all(out).with_context(|| format!("create {}", out.display()))?;

    let fixtures = vec![
        (
            "fresh-machine",
            "With no managed set and no non-empty locks, installs target Claude only.",
            vec![],
            vec![],
        ),
        (
            "explicit-config-set",
            "A non-empty managed config set overrides inferred locks.",
            vec![Platform::Codex, Platform::Gemini],
            vec![Platform::Claude, Platform::Hermes],
        ),
        (
            "unmanaged-nonempty-lock-inference",
            "Without a managed config, installs target every platform whose lockfile is already non-empty.",
            vec![],
            vec![Platform::Codex, Platform::Hermes],
        ),
    ];

    let mut cases = Vec::new();
    for (name, description, config_platforms, non_empty_locks) in fixtures {
        let expected = observe_target_resolution(&config_platforms, &non_empty_locks)?;
        cases.push(TargetResolveCase {
            name: name.to_string(),
            description: description.to_string(),
            input: TargetResolveInput {
                scope: InstallScope::Global.label().to_string(),
                config_platforms: config_platforms
                    .into_iter()
                    .map(|platform| platform.to_string())
                    .collect(),
                non_empty_locks: non_empty_locks
                    .into_iter()
                    .map(|platform| platform.to_string())
                    .collect(),
            },
            expected: TargetResolveExpected {
                resolved_platforms: expected,
            },
        });
    }

    let manifest = TargetResolveManifest {
        schema_version: 1,
        cases,
    };
    write_json(&out.join("manifest.json"), &manifest)
}

#[derive(Serialize)]
struct InstallE2eManifest {
    schema_version: u32,
    cases: Vec<InstallE2eCase>,
}

#[derive(Serialize)]
struct InstallE2eCase {
    name: String,
    description: String,
    input: InstallE2eInput,
    expected: InstallE2eExpectedPaths,
}

#[derive(Serialize)]
struct InstallE2eInput {
    tool_name: String,
    tool_version: String,
    scope: String,
    force: bool,
    bundle_dir: String,
    pre_tree_dir: String,
    pre_locks_dir: String,
}

#[derive(Serialize)]
struct InstallE2eExpectedPaths {
    tree_dir: String,
    locks_dir: String,
    report_path: String,
}

#[derive(Serialize)]
struct PlanSnapshot {
    blocked: bool,
    cmx_present: bool,
    scope: String,
    source_checksum: String,
    targets: Vec<PlanTargetSnapshot>,
}

#[derive(Serialize)]
struct PlanTargetSnapshot {
    platform: String,
    dest_dir: String,
    action: ActionSnapshot,
    cmx_managed: bool,
}

#[derive(Serialize)]
struct ReportSnapshot {
    tool_name: String,
    scope: String,
    source_registered: bool,
    targets: Vec<ReportTargetSnapshot>,
}

#[derive(Serialize)]
struct ReportTargetSnapshot {
    platform: String,
    dest_dir: String,
    action: ActionSnapshot,
    files_written: usize,
    installed_checksum: Option<String>,
    discarded_paths: Vec<String>,
}

#[derive(Serialize)]
struct ApplySnapshot {
    status: String,
    error: Option<String>,
    report: Option<ReportSnapshot>,
}

#[derive(Serialize)]
struct InstallE2eReport {
    plan: PlanSnapshot,
    apply: ApplySnapshot,
}

fn snapshot_plan(plan: &InstallPlan) -> PlanSnapshot {
    PlanSnapshot {
        blocked: plan.is_blocked(),
        cmx_present: plan.cmx_present,
        scope: plan.scope.label().to_string(),
        source_checksum: plan.source_checksum.clone(),
        targets: plan
            .targets
            .iter()
            .map(|target| PlanTargetSnapshot {
                platform: target.platform.to_string(),
                dest_dir: normalized_path_string(&target.dest_dir),
                action: snapshot_action(&target.action),
                cmx_managed: target.cmx_managed,
            })
            .collect(),
    }
}

fn snapshot_report(report: &Report) -> ReportSnapshot {
    ReportSnapshot {
        tool_name: report.tool.name.clone(),
        scope: report.scope.label().to_string(),
        source_registered: report.source_registered,
        targets: report
            .targets
            .iter()
            .map(|target| ReportTargetSnapshot {
                platform: target.platform.to_string(),
                dest_dir: normalized_path_string(&target.dest_dir),
                action: snapshot_action(&target.action),
                files_written: target.files_written,
                installed_checksum: target.installed_checksum.clone(),
                discarded_paths: target
                    .discarded_paths
                    .iter()
                    .map(|path| normalized_path_string(path))
                    .collect(),
            })
            .collect(),
    }
}

struct InstallE2eFixture<'a> {
    name: &'a str,
    description: &'a str,
    tool_version: &'a str,
    force: bool,
    setup: fn(&TestContext, &BundledSkill) -> Result<()>,
}

fn setup_fresh_install(test: &TestContext, _skill: &BundledSkill) -> Result<()> {
    let _ = snapshot_locks(test, InstallScope::Global)?;
    Ok(())
}

fn setup_skip_identical(test: &TestContext, skill: &BundledSkill) -> Result<()> {
    let checksum = write_bundle_version(test, InstallScope::Global, skill, FIXTURE_VERSION)?;
    save_bundled_lock(test, InstallScope::Global, Some(FIXTURE_VERSION), &checksum)
}

fn setup_drifted_skip(test: &TestContext, skill: &BundledSkill) -> Result<()> {
    let checksum = bundled_checksum(skill, FIXTURE_VERSION);
    save_bundled_lock(test, InstallScope::Global, Some(FIXTURE_VERSION), &checksum)?;
    let _ = write_drifted_bundle_version(test, InstallScope::Global, skill, FIXTURE_VERSION)?;
    Ok(())
}

fn setup_update_from_older(test: &TestContext, skill: &BundledSkill) -> Result<()> {
    let checksum = write_bundle_version(test, InstallScope::Global, skill, "1.0.0")?;
    save_bundled_lock(test, InstallScope::Global, Some("1.0.0"), &checksum)
}

fn setup_refuse_newer(test: &TestContext, skill: &BundledSkill) -> Result<()> {
    let checksum = write_bundle_version(test, InstallScope::Global, skill, "9.0.0")?;
    save_bundled_lock(test, InstallScope::Global, Some("9.0.0"), &checksum)
}

fn run_install_e2e_case(root: &Path, fixture: &InstallE2eFixture<'_>) -> Result<InstallE2eCase> {
    let test = TestContext::at(fixed_time());
    let skill = bundle();

    (fixture.setup)(&test, &skill)?;

    let pre_tree = snapshot_tree(&test, InstallScope::Global);
    let pre_locks = snapshot_locks(&test, InstallScope::Global)?;

    let case_dir = root.join(fixture.name);
    write_tree_snapshot(&case_dir.join("bundle"), &bundle_snapshot(&skill))?;
    write_tree_snapshot(&case_dir.join("pre").join("tree"), &pre_tree)?;
    write_lock_snapshot(&case_dir.join("pre").join("locks"), &pre_locks)?;

    let installer = installer(fixture.tool_version);
    let plan = installer.plan(&skill, Scope::Global, fixture.force, &test.ctx())?;
    let plan_snapshot = snapshot_plan(&plan);

    let apply = match installer.apply(&skill, &plan, &test.ctx()) {
        Ok(report) => ApplySnapshot {
            status: "applied".to_string(),
            error: None,
            report: Some(snapshot_report(&report)),
        },
        Err(error) => ApplySnapshot {
            status: "blocked".to_string(),
            error: Some(error.to_string()),
            report: None,
        },
    };

    let expected_tree = snapshot_tree(&test, InstallScope::Global);
    let expected_locks = snapshot_locks(&test, InstallScope::Global)?;

    write_tree_snapshot(&case_dir.join("expected").join("tree"), &expected_tree)?;
    write_lock_snapshot(&case_dir.join("expected").join("locks"), &expected_locks)?;
    write_json(
        &case_dir.join("expected").join("report.json"),
        &InstallE2eReport {
            plan: plan_snapshot,
            apply,
        },
    )?;

    Ok(InstallE2eCase {
        name: fixture.name.to_string(),
        description: fixture.description.to_string(),
        input: InstallE2eInput {
            tool_name: FIXTURE_TOOL_NAME.to_string(),
            tool_version: fixture.tool_version.to_string(),
            scope: InstallScope::Global.label().to_string(),
            force: fixture.force,
            bundle_dir: format!("{}/bundle", fixture.name),
            pre_tree_dir: format!("{}/pre/tree", fixture.name),
            pre_locks_dir: format!("{}/pre/locks", fixture.name),
        },
        expected: InstallE2eExpectedPaths {
            tree_dir: format!("{}/expected/tree", fixture.name),
            locks_dir: format!("{}/expected/locks", fixture.name),
            report_path: format!("{}/expected/report.json", fixture.name),
        },
    })
}

fn bundle_snapshot(skill: &BundledSkill) -> BTreeMap<PathBuf, Vec<u8>> {
    skill
        .files
        .iter()
        .map(|file| (file.rel_path.clone(), file.bytes.clone()))
        .collect()
}

fn generate_install_e2e_fixtures(out: &Path) -> Result<()> {
    fs::create_dir_all(out).with_context(|| format!("create {}", out.display()))?;

    let fixtures = vec![
        InstallE2eFixture {
            name: "fresh-install",
            description: "Fresh unmanaged install onto a machine with no existing locks.",
            tool_version: FIXTURE_VERSION,
            force: false,
            setup: setup_fresh_install,
        },
        InstallE2eFixture {
            name: "skip-identical",
            description: "Tracked current install with matching bytes skips cleanly.",
            tool_version: FIXTURE_VERSION,
            force: false,
            setup: setup_skip_identical,
        },
        InstallE2eFixture {
            name: "drifted-skip",
            description: "Tracked current install with local edits preserves those edits when force is false.",
            tool_version: FIXTURE_VERSION,
            force: false,
            setup: setup_drifted_skip,
        },
        InstallE2eFixture {
            name: "update-from-older",
            description: "Tracked older install updates to the bundled version.",
            tool_version: FIXTURE_VERSION,
            force: false,
            setup: setup_update_from_older,
        },
        InstallE2eFixture {
            name: "refuse-newer",
            description: "Tracked newer install blocks the plan without force.",
            tool_version: FIXTURE_VERSION,
            force: false,
            setup: setup_refuse_newer,
        },
        InstallE2eFixture {
            name: "force-downgrade",
            description: "Tracked newer install downgrades when force is true.",
            tool_version: FIXTURE_VERSION,
            force: true,
            setup: setup_refuse_newer,
        },
    ];

    let mut cases = Vec::new();
    for fixture in &fixtures {
        cases.push(run_install_e2e_case(out, fixture)?);
    }

    let manifest = InstallE2eManifest {
        schema_version: 1,
        cases,
    };
    write_json(&out.join("manifest.json"), &manifest)
}

fn write_readme(path: &Path) -> Result<()> {
    write_bytes(path, README.as_bytes())
}

const README: &str = r#"# cmx-core conformance fixtures

These fixtures are the language-neutral correctness contract for `cmx-core` ports.
Every case is generated from the Rust reference implementation with:

```bash
cargo run -p cmx-core --features test-support --bin generate-conformance-fixtures
```

The generator is a dedicated `test-support` binary so regeneration is explicit and reproducible, while the drift-guard test reuses the same library function in CI.

## Fixed environment

- Fixed clock: `2026-07-05T12:00:00+00:00`
- Virtual home: `/home/testuser`
- Global config root: `/home/testuser/.config/context-mixer`
- Local project root mapping: relative install paths are stored under `project/` in fixture trees

Tree snapshots use real files on disk. Absolute paths are stored without the leading `/`, so `/home/testuser/.claude/skills/fixture-tool/SKILL.md` appears as `home/testuser/.claude/skills/fixture-tool/SKILL.md`.

Lockfile expectations are stored as parsed JSON values, not byte-for-byte serialized text. Future ports must compare lockfiles as JSON values with sorted package keys.

## Layout

```text
cmx-core/conformance/
  README.md
  checksum/
  frontmatter/
  version-guard/
  paths/
  target-resolve/
  install-e2e/
```

Each category has one `manifest.json` that defines the schema for its cases. Inputs and expected outputs are separated explicitly.

## Category schemas

### `checksum/manifest.json`

Schema:

```json
{
  "schema_version": 1,
  "cases": [
    {
      "name": "string-sort-a-dot-slash",
      "description": "human-readable note",
      "input": {
        "files": [
          { "path": "a", "content_utf8": "bare\n" }
        ]
      },
      "expected": {
        "sha256": "sha256:...",
        "canonical_order": ["a", "a.b", "a/b"],
        "canonical_included_paths": ["a", "a.b", "a/b"]
      }
    }
  ]
}
```

Notes:

- Checksum cases use inline UTF-8 file sets because some parity cases, such as `a` plus `a/b`, cannot exist simultaneously on a real filesystem tree.
- `canonical_order` and `canonical_included_paths` are the reference's filtered, sorted input to the hash.

### `frontmatter/manifest.json`

Schema:

```json
{
  "schema_version": 1,
  "cases": [
    {
      "name": "existing-metadata-version",
      "description": "human-readable note",
      "input": {
        "version": "2.4.6",
        "skill_md_path": "existing-metadata-version/input/SKILL.md"
      },
      "expected": {
        "skill_md_path": "existing-metadata-version/expected/SKILL.md",
        "byte_exact": true,
        "idempotent_second_pass": false
      }
    }
  ]
}
```

The `input/` and `expected/` files are real `SKILL.md` byte fixtures. Ports must compare the expected output byte-for-byte.

### `version-guard/manifest.json`

Schema:

```json
{
  "schema_version": 1,
  "cases": [
    {
      "name": "equal-drifted-skip",
      "description": "human-readable note",
      "input": {
        "bundled_version": "2.4.6",
        "tracked": true,
        "installed_version": "2.4.6",
        "disk_state": "drifted",
        "force": false
      },
      "expected": {
        "kind": "drifted-skip",
        "from": null,
        "installed": "2.4.6",
        "will_write": false,
        "blocked": false
      }
    }
  ]
}
```

`disk_state` is one of `missing`, `matches-source`, or `drifted`.

### `paths/manifest.json`

Schema:

```json
{
  "schema_version": 1,
  "cases": [
    {
      "name": "copilot-global",
      "input": {
        "platform": "copilot",
        "kind": "skill",
        "scope": "global"
      },
      "expected": {
        "subpath": ".copilot/skills",
        "lockname": "cmx-lock-copilot.json"
      }
    }
  ]
}
```

This category covers every platform in `Platform::ALL` at both scopes.

### `target-resolve/manifest.json`

Schema:

```json
{
  "schema_version": 1,
  "cases": [
    {
      "name": "fresh-machine",
      "description": "human-readable note",
      "input": {
        "scope": "global",
        "config_platforms": [],
        "non_empty_locks": []
      },
      "expected": {
        "resolved_platforms": ["claude"]
      }
    }
  ]
}
```

`non_empty_locks` lists the platforms whose scope-specific lockfiles were pre-populated before resolution.

### `install-e2e/manifest.json`

Schema:

```json
{
  "schema_version": 1,
  "cases": [
    {
      "name": "fresh-install",
      "description": "human-readable note",
      "input": {
        "tool_name": "fixture-tool",
        "tool_version": "2.4.6",
        "scope": "global",
        "force": false,
        "bundle_dir": "fresh-install/bundle",
        "pre_tree_dir": "fresh-install/pre/tree",
        "pre_locks_dir": "fresh-install/pre/locks"
      },
      "expected": {
        "tree_dir": "fresh-install/expected/tree",
        "locks_dir": "fresh-install/expected/locks",
        "report_path": "fresh-install/expected/report.json"
      }
    }
  ]
}
```

Case contents:

- `bundle/` is the original bundled skill file set before frontmatter reconciliation.
- `pre/tree/` is the non-lock virtual filesystem tree before `plan`/`apply`.
- `pre/locks/` stores any pre-existing lockfiles as JSON values, keyed by lock filename.
- `expected/tree/` and `expected/locks/` are the post-apply filesystem state.
- `expected/report.json` contains:
  - `plan`: the observed plan snapshot from the Rust oracle
  - `apply.status`: `applied` or `blocked`
  - `apply.error`: present only for blocked runs
  - `apply.report`: the normalized Rust `Report` snapshot for successful applies

Ports should materialize `bundle/`, `pre/tree/`, and `pre/locks/` into an isolated test root, execute the equivalent operation, then compare the resulting tree, lock JSON values, and normalized report against `expected/`.

## Drift guard

`cargo test --workspace` includes a drift-guard test that regenerates this entire tree into a temp directory and compares it against the committed fixtures. JSON files are compared by parsed value; all other files are compared byte-for-byte.
"#;

#[cfg(test)]
struct DiskTree {
    files: BTreeMap<PathBuf, Vec<u8>>,
}

#[cfg(test)]
fn collect_disk_tree(root: &Path) -> Result<DiskTree> {
    let mut tree = DiskTree {
        files: BTreeMap::new(),
    };
    collect_disk_tree_recursive(root, root, &mut tree)?;
    Ok(tree)
}

// Records files only — empty directories are intentionally ignored (see
// `assert_fixture_tree_matches`: git cannot track them, so they are not part of
// the fixture contract).
#[cfg(test)]
fn collect_disk_tree_recursive(root: &Path, current: &Path, tree: &mut DiskTree) -> Result<()> {
    for entry in fs::read_dir(current).with_context(|| format!("read {}", current.display()))? {
        let entry = entry?;
        let path = entry.path();
        let rel = path
            .strip_prefix(root)
            .with_context(|| format!("strip {} from {}", root.display(), path.display()))?
            .to_path_buf();

        if entry.file_type()?.is_dir() {
            collect_disk_tree_recursive(root, &path, tree)?;
        } else {
            let bytes = fs::read(&path).with_context(|| format!("read {}", path.display()))?;
            tree.files.insert(rel, bytes);
        }
    }
    Ok(())
}

#[cfg(test)]
fn assert_fixture_tree_matches(expected_root: &Path, actual_root: &Path) -> Result<()> {
    let expected = collect_disk_tree(expected_root)?;
    let actual = collect_disk_tree(actual_root)?;

    // Deliberately do NOT compare the empty-directory set. Git cannot track
    // empty directories, so any purely-empty scaffold dir the generator emits
    // (e.g. a fresh-install case's empty `pre/tree/...`) survives in a freshly
    // regenerated tree but vanishes from the committed tree — making a strict
    // `dirs ==` check pass only in the dirty worktree that just generated them
    // and fail from every clean checkout. The contract is the set of files and
    // their contents; the file checks below are authoritative and catch any
    // meaningful drift (a non-empty dir necessarily shows up as a file path).
    ensure!(
        expected.files.keys().collect::<Vec<_>>() == actual.files.keys().collect::<Vec<_>>(),
        "file set drift:\nexpected: {:?}\nactual: {:?}",
        expected.files.keys().collect::<Vec<_>>(),
        actual.files.keys().collect::<Vec<_>>()
    );

    for (rel_path, expected_bytes) in expected.files {
        let actual_bytes = actual
            .files
            .get(&rel_path)
            .with_context(|| format!("missing generated file {}", rel_path.display()))?;
        if rel_path.extension().is_some_and(|ext| ext == "json") {
            let expected_value = serde_json::from_slice::<Value>(&expected_bytes)
                .with_context(|| format!("parse committed JSON {}", rel_path.display()))?;
            let actual_value = serde_json::from_slice::<Value>(actual_bytes)
                .with_context(|| format!("parse regenerated JSON {}", rel_path.display()))?;
            ensure!(expected_value == actual_value, "JSON drift in {}", rel_path.display());
        } else {
            ensure!(expected_bytes == *actual_bytes, "byte drift in {}", rel_path.display());
        }
    }

    Ok(())
}

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

    #[test]
    fn committed_conformance_fixtures_match_regeneration() {
        let tmp = tempfile::tempdir().unwrap();
        let regenerated = tmp.path().join("conformance");
        generate_conformance_fixtures(&regenerated).unwrap();

        let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("conformance");
        assert_fixture_tree_matches(&committed, &regenerated).unwrap();
    }
}