callisto-graph 0.4.1

Callisto Release Engine — Dependency DAG solver and topological cascade release planner.
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
use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use callisto_changelog::{ChangeSource, ChangelogEntry, ChangelogInput};
use callisto_format::{parse_changeset, Changeset};
use callisto_model::{BumpReason, CommitSha, Diagnostic, Package, PackageId, Severity, Version};
use callisto_vcs::{GitAccess, GitDataSource};

use crate::config::resolve::resolve_package_config;
use crate::config::GroupTable;
use crate::config::{PreMajorInferencePolicy, ResolvedConfig};
use crate::error::GraphError;
use crate::infer::SeverityInference;
use crate::resolver::DependencyResolver;
use crate::tags::TagIndex;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LoadedChangeset {
    pub path: PathBuf,
    pub id: String,
    pub changeset: Changeset,
}

#[derive(Clone, Debug, Default)]
pub struct Aggregation {
    pub severities: BTreeMap<PackageId, Severity>,
    pub reasons: BTreeMap<PackageId, BumpReason>,
    pub named_by: BTreeMap<PackageId, NamedBy>,
    pub consumed: Vec<PathBuf>,
    pub changelog_inputs: BTreeMap<PackageId, ChangelogInput>,
    pub inference_commits: BTreeMap<PackageId, Vec<(CommitSha, String)>>,
    pub diagnostics: Vec<Diagnostic>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NamedBy {
    Changeset,
    Inference,
}

pub fn load_changesets(root: &Path, cfg: &ResolvedConfig) -> Result<Vec<LoadedChangeset>, GraphError> {
    let dir = root.join(&cfg.changesets_dir);
    if !dir.exists() {
        return Ok(Vec::new());
    }

    let entries = fs::read_dir(&dir).map_err(|e| callisto_model::ManifestError::Read {
        path: dir.clone(),
        message: e.to_string(),
    })?;

    let mut files = Vec::new();
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("md") {
            if let Some(file_name) = path.file_name().and_then(|s| s.to_str()) {
                if file_name != "README.md" && file_name != "config.json" && file_name != "pre.json" {
                    files.push(path);
                }
            }
        }
    }

    files.sort();

    let mut loaded = Vec::new();
    for path in files {
        let content = fs::read_to_string(&path).map_err(|e| callisto_model::ManifestError::Read {
            path: path.clone(),
            message: e.to_string(),
        })?;
        let changeset = parse_changeset(&content).map_err(|e| GraphError::ParseChangeset {
            path: path.clone(),
            source: e,
        })?;
        let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("").to_string();
        let rel_path = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
        loaded.push(LoadedChangeset {
            path: rel_path,
            id: stem,
            changeset,
        });
    }

    Ok(loaded)
}

pub fn apply_pre_major(
    inferred: Severity,
    policy: PreMajorInferencePolicy,
    current: &Version,
    has_prior_release: bool,
) -> (Severity, bool) {
    if policy == PreMajorInferencePolicy::Off {
        return (inferred, false);
    }
    if current.major() != Some(0) || current.minor() == Some(0) || !has_prior_release {
        return (inferred, false);
    }

    match (policy, inferred) {
        (PreMajorInferencePolicy::Conservative | PreMajorInferencePolicy::ConservativeFeat, Severity::Major) => {
            (Severity::Minor, true)
        }
        (PreMajorInferencePolicy::ConservativeFeat, Severity::Minor) => (Severity::Patch, true),
        (_, s) => (s, false),
    }
}

/// Resolves a release tag name to the commit SHA it points at, so that
/// severity inference can be scoped to `since..HEAD` instead of walking the
/// entire history on every `aggregate()`-driven command.
///
/// Thin wrapper around [`GitDataSource::resolve_commit`] (native gix,
/// falling back to a `CommandRunner`-shelled `git rev-parse` when gix is
/// unavailable -- most notably on `wasm32`): any failure to resolve the tag
/// (missing, unborn repo, etc.) degrades gracefully to `None`, which
/// callers treat as "infer over full history" -- the same behavior this
/// function has always had, now delegated to [`GitAccess`] instead of
/// hand-rolling the gix-then-runner-fallback shape itself.
fn resolve_since(git: &impl GitDataSource, tag_name: &str) -> Option<CommitSha> {
    git.resolve_commit(tag_name).ok().flatten()
}

/// Resolves a changeset entry's parsed `PackageId` against the packages in
/// the graph.
///
/// `PackageId::matches` is pairwise: a bare id and a prefixed id with the
/// same name are compatible, since bare doesn't specify an ecosystem. But
/// a polyglot workspace can legitimately have the same name in two-plus
/// ecosystems (`cargo/foo`, `npm/foo`), and a bare `foo` can't resolve to
/// either without more context. `.find()` over such a graph would silently
/// pick whichever candidate comes first -- the ambiguity bug this function
/// fixes by collecting *all* matches and only succeeding when there's
/// exactly one.
///
/// `Ok(None)`: no match (unknown package, reported separately by
/// `validate`). `Ok(Some(pkg))`: unambiguous. `Err(AmbiguousName)`: two or
/// more matches.
pub(crate) fn resolve_target_package<'a>(
    packages: impl Iterator<Item = &'a Package>,
    id: &PackageId,
) -> Result<Option<&'a Package>, GraphError> {
    id.resolve_unique(packages, |p| &p.id)
        .map_err(|candidates| GraphError::AmbiguousName {
            name: id.display_name(),
            candidates: candidates.iter().map(|p| p.id.clone()).collect(),
        })
}

pub fn aggregate<D, I>(
    graph: &D,
    config: &ResolvedConfig,
    git: &GitAccess<'_>,
    tags: &TagIndex,
    base_versions: &BTreeMap<PackageId, Version>,
    pre: Option<&callisto_format::PreState>,
    inference: &I,
) -> Result<Aggregation, GraphError>
where
    D: DependencyResolver,
    I: SeverityInference,
{
    let loaded = load_changesets(&config.root, config)?;
    let mut agg = Aggregation::default();

    // `git` is shared with the caller (a single `Workspace`-scoped
    // `GitAccess`, via `Workspace::git_access`) rather than discovered
    // fresh here, so a caller resolving both this and e.g. a head SHA in
    // the same command invocation only pays for one discovery. A
    // resolution failure degrades gracefully to `None`, same as
    // `resolve_since`'s own per-tag failure handling.

    for pkg in graph.packages() {
        let cur_sev = agg.severities.get(&pkg.id).copied().unwrap_or(Severity::None);
        let pathspecs: Vec<PathBuf> = pkg.manifests.iter().map(|m| m.path.clone()).collect();
        let last_tag = tags.last_tag(&pkg.id);
        let cur_ver = last_tag
            .map(|t| t.version.clone())
            .or_else(|| base_versions.get(&pkg.id).cloned())
            .ok_or_else(|| {
                GraphError::Manifest(callisto_model::ManifestError::MissingField {
                    path: pkg.manifests.first().map(|m| m.path.clone()).unwrap_or_default(),
                    field: "version",
                })
            })?;

        let since = last_tag.and_then(|t| resolve_since(git, t.name.as_str()));

        let policy = resolve_package_config(&pkg.id, config)?
            .and_then(|pcfg| pcfg.pre_major_inference)
            .unwrap_or(PreMajorInferencePolicy::Off);

        let window = crate::infer::InferenceWindowSpec {
            pathspecs: &pathspecs,
            since,
            current_version: &cur_ver,
            has_prior_release: last_tag.is_some(),
            policy,
        };

        match inference.infer(pkg, git, window) {
            Ok(Some(outcome)) => {
                if outcome.severity > cur_sev {
                    agg.severities.insert(pkg.id.clone(), outcome.severity);
                    agg.reasons.insert(
                        pkg.id.clone(),
                        BumpReason::Inference {
                            commits: outcome.commit_count,
                            remapped: outcome.remapped,
                        },
                    );
                    agg.named_by.insert(pkg.id.clone(), NamedBy::Inference);
                    agg.inference_commits.insert(pkg.id.clone(), outcome.commits.clone());
                }
            }
            Ok(None) => {}
            Err(e) => {
                agg.diagnostics.push(Diagnostic {
                    code: callisto_model::DiagnosticCode::PreMajorInferenceInert,
                    severity: callisto_model::DiagnosticSeverity::Warning,
                    message: format!("Commit inference failed for package `{}`: {e}", pkg.id.display_name()),
                    package: Some(pkg.id.clone()),
                    path: None,
                    governed_by: None,
                    escalated_by: None,
                });
            }
        }
    }

    // During a pre-release cycle (PreMode::Pre) changesets must NOT be consumed:
    // they remain on disk so they can be re-applied when the cycle exits.
    let is_pre_mode = pre.map(|s| s.mode == callisto_format::PreMode::Pre).unwrap_or(false);

    for cs in loaded {
        // Defer adding to `consumed` until after we confirm at least one entry
        // resolved to a real workspace package.  A changeset where every entry
        // names a removed package must NOT be consumed (which would delete it
        // on disk); instead, an UnknownPackage diagnostic is emitted and the
        // file is left for the user to clean up manually.
        let mut matched_any = false;
        for entry in cs.changeset.entries {
            let id = match PackageId::parse(&entry.name) {
                Ok(id) => id,
                Err(_) => {
                    agg.diagnostics.push(Diagnostic {
                        code: callisto_model::DiagnosticCode::UnknownPackage,
                        severity: callisto_model::DiagnosticSeverity::Warning,
                        message: format!(
                            "Changeset `{}` contains invalid package name `{}`",
                            cs.path.display(),
                            entry.name
                        ),
                        package: None,
                        path: Some(cs.path.clone()),
                        governed_by: None,
                        escalated_by: None,
                    });
                    continue;
                }
            };
            match resolve_target_package(graph.packages(), &id)? {
                Some(target_pkg) => {
                    matched_any = true;
                    let canonical_id = target_pkg.id.clone();
                    let cur_sev = agg.severities.get(&canonical_id).copied().unwrap_or(Severity::None);
                    if entry.severity > cur_sev {
                        agg.severities.insert(canonical_id.clone(), entry.severity);
                        agg.reasons.insert(
                            canonical_id.clone(),
                            BumpReason::Changeset {
                                changesets: vec![cs.id.clone()],
                            },
                        );
                        agg.named_by.insert(canonical_id.clone(), NamedBy::Changeset);
                    }

                    if entry.severity != Severity::None {
                        // In pre-release mode use the pre-cycle entry version as the
                        // changelog "from" baseline so the log covers the full pre
                        // range rather than reflecting live (pre-tagged) versions.
                        let pkg_ver = if is_pre_mode {
                            pre.and_then(|s| s.initial_versions.get(&canonical_id.display_name()))
                                .cloned()
                                .or_else(|| base_versions.get(&canonical_id).cloned())
                                .unwrap_or_else(|| Version::semver(0, 0, 0))
                        } else {
                            tags.last_tag(&canonical_id)
                                .map(|t| t.version.clone())
                                .or_else(|| base_versions.get(&canonical_id).cloned())
                                .unwrap_or_else(|| Version::semver(0, 0, 0))
                        };
                        let cl_input =
                            agg.changelog_inputs
                                .entry(canonical_id.clone())
                                .or_insert_with(|| ChangelogInput {
                                    package: canonical_id.clone(),
                                    from: pkg_ver,
                                    to: None,
                                    entries: Vec::new(),
                                });
                        cl_input.entries.push(ChangelogEntry {
                            severity: entry.severity,
                            source: ChangeSource::Changeset {
                                filename: cs.id.clone(),
                                summary: cs.changeset.summary.clone(),
                            },
                        });
                    }
                }
                None => {
                    // Entry references a package not in the workspace (e.g. a
                    // package that was removed since the changeset was written).
                    // Emit a diagnostic so the user knows, but do NOT count
                    // this as a match -- a fully-orphaned changeset stays on
                    // disk rather than being silently deleted.
                    agg.diagnostics.push(Diagnostic {
                        code: callisto_model::DiagnosticCode::UnknownPackage,
                        severity: callisto_model::DiagnosticSeverity::Warning,
                        message: format!(
                            "Changeset `{}` references package `{}` which is not in the \
                             workspace; the changeset will not be consumed until this entry \
                             is resolved",
                            cs.path.display(),
                            entry.name
                        ),
                        package: None,
                        path: Some(cs.path.clone()),
                        governed_by: None,
                        escalated_by: None,
                    });
                }
            }
        }
        // Only mark as consumed when at least one entry resolved to a real
        // package AND we are not in a pre-release cycle.  During pre mode the
        // changeset files must stay on disk so they can be re-applied on exit.
        // A fully-orphaned changeset is also left on disk regardless of mode.
        if matched_any && !is_pre_mode {
            agg.consumed.push(cs.path.clone());
        }
    }

    loop {
        let mut changed = false;
        if union_fixed(&mut agg, &config.groups, base_versions) {
            changed = true;
        }
        if union_linked(&mut agg, &config.groups, base_versions) {
            changed = true;
        }
        if !changed {
            break;
        }
    }

    Ok(agg)
}

pub(crate) fn union_fixed(
    agg: &mut Aggregation,
    groups: &GroupTable,
    base_versions: &BTreeMap<PackageId, Version>,
) -> bool {
    let mut changed = false;
    for g in groups.fixed.values() {
        let pkg_members: Vec<PackageId> = g
            .members(crate::config::GroupMemberKind::Package)
            .filter_map(|m| match m {
                crate::config::GroupMember::Package(ref id) => Some(id.clone()),
                _ => None,
            })
            .collect();

        let mut target = Severity::None;
        for m in &pkg_members {
            if let Some(&s) = agg.severities.get(m) {
                if s > target {
                    target = s;
                }
            }
        }

        if target == Severity::None {
            continue;
        }

        for m in pkg_members {
            let cur = agg.severities.get(&m).copied().unwrap_or(Severity::None);
            if target > cur {
                // Guard against stale group members: a package listed in the
                // config group that was subsequently removed from the workspace
                // must not be inserted into severities.  Doing so causes
                // `bump_target` in `solve_cascade` to call
                // `input.base.get(stale_id)` -> `None` ->
                // `Err(GraphError::Manifest(MissingField))`, which surfaces as
                // a misleading crash.  Emit a warning instead and skip.
                if !base_versions.contains_key(&m) {
                    agg.diagnostics.push(Diagnostic {
                        code: callisto_model::DiagnosticCode::UnknownPackage,
                        severity: callisto_model::DiagnosticSeverity::Warning,
                        message: format!(
                            "Fixed group `{}` references package `{}` which is not in the \
                             workspace; the stale group member is skipped. Remove it from \
                             callisto.toml to silence this warning.",
                            g.name,
                            m.display_name()
                        ),
                        package: Some(m.clone()),
                        path: None,
                        governed_by: Some(callisto_model::ConfigKey::FIXED_GROUP),
                        escalated_by: None,
                    });
                    continue;
                }
                agg.severities.insert(m.clone(), target);
                agg.reasons
                    .insert(m.clone(), BumpReason::FixedGroupUnion { group: g.name.clone() });
                changed = true;
            }
        }
    }
    changed
}

pub(crate) fn union_linked(
    agg: &mut Aggregation,
    groups: &GroupTable,
    base_versions: &BTreeMap<PackageId, Version>,
) -> bool {
    let mut changed = false;
    for g in groups.linked.values() {
        let named: Vec<PackageId> = g
            .members(crate::config::GroupMemberKind::Package)
            .filter_map(|m| match m {
                crate::config::GroupMember::Package(ref id) => {
                    if agg.named_by.contains_key(id) {
                        Some(id.clone())
                    } else {
                        None
                    }
                }
                _ => None,
            })
            .collect();

        if named.is_empty() {
            continue;
        }

        let mut target_sev = Severity::None;
        for m in &named {
            if let Some(&s) = agg.severities.get(m) {
                if s > target_sev {
                    target_sev = s;
                }
            }
        }

        let all_members: Vec<PackageId> = g
            .members(crate::config::GroupMemberKind::Package)
            .filter_map(|m| match m {
                crate::config::GroupMember::Package(ref id) => Some(id.clone()),
                _ => None,
            })
            .collect();

        for m in all_members {
            let cur = agg.severities.get(&m).copied().unwrap_or(Severity::None);
            if target_sev > cur {
                // Guard against stale linked-group members, same rationale as
                // in `union_fixed`: a removed package must not enter
                // `agg.severities`, which would cause `bump_target` to crash.
                if !base_versions.contains_key(&m) {
                    agg.diagnostics.push(Diagnostic {
                        code: callisto_model::DiagnosticCode::UnknownPackage,
                        severity: callisto_model::DiagnosticSeverity::Warning,
                        message: format!(
                            "Linked group `{}` references package `{}` which is not in the \
                             workspace; the stale group member is skipped. Remove it from \
                             callisto.toml to silence this warning.",
                            g.name,
                            m.display_name()
                        ),
                        package: Some(m.clone()),
                        path: None,
                        governed_by: Some(callisto_model::ConfigKey::LINKED_GROUP),
                        escalated_by: None,
                    });
                    continue;
                }
                agg.severities.insert(m.clone(), target_sev);
                agg.reasons
                    .insert(m.clone(), BumpReason::LinkedGroupUnion { group: g.name.clone() });
                changed = true;
            }
        }
    }
    changed
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Mutex;

    use callisto_model::{
        CommandError, CommandOutput, CommandRunner, DepEdge, GroupKind, GroupName, ManifestDecl, ManifestFormat,
        ManifestRole, Package,
    };

    use crate::config::{GroupDef, GroupMember};
    use crate::infer::{InferenceOutcome, InferenceWindowSpec, SeverityInference};
    use callisto_fixtures::git::{init_repo, run_git, PoisonedRunner};

    /// Direct unit coverage for `apply_pre_major` across all three policy
    /// states, previously only exercised indirectly through full-config
    /// integration tests. `Off` never downgrades; `Conservative` downgrades
    /// Major->Minor only; `ConservativeFeat` downgrades both Major->Minor
    /// and Minor->Patch.
    #[test]
    fn apply_pre_major_off_never_downgrades() {
        let v = Version::semver(0, 1, 0);
        assert_eq!(
            apply_pre_major(Severity::Major, PreMajorInferencePolicy::Off, &v, true),
            (Severity::Major, false)
        );
        assert_eq!(
            apply_pre_major(Severity::Minor, PreMajorInferencePolicy::Off, &v, true),
            (Severity::Minor, false)
        );
    }

    #[test]
    fn apply_pre_major_conservative_downgrades_major_to_minor_only() {
        let v = Version::semver(0, 1, 0);
        assert_eq!(
            apply_pre_major(Severity::Major, PreMajorInferencePolicy::Conservative, &v, true),
            (Severity::Minor, true)
        );
        assert_eq!(
            apply_pre_major(Severity::Minor, PreMajorInferencePolicy::Conservative, &v, true),
            (Severity::Minor, false),
            "Conservative must not also downgrade Minor->Patch"
        );
    }

    #[test]
    fn apply_pre_major_conservative_feat_downgrades_both_levels() {
        let v = Version::semver(0, 1, 0);
        assert_eq!(
            apply_pre_major(Severity::Major, PreMajorInferencePolicy::ConservativeFeat, &v, true),
            (Severity::Minor, true)
        );
        assert_eq!(
            apply_pre_major(Severity::Minor, PreMajorInferencePolicy::ConservativeFeat, &v, true),
            (Severity::Patch, true)
        );
    }

    /// Shells out to the real `git` binary. Retained as the `CommandRunner`
    /// implementation passed to `aggregate()`/`TagIndex::build` in most
    /// tests below, even though neither actually uses it for git access
    /// anymore: both resolve against the real repo on disk via
    /// `callisto_vcs::GitRepository` (gix). See
    /// `test_aggregate_resolves_since_without_shelling_through_runner` for
    /// the test proving `aggregate()`'s since-resolution no longer needs a
    /// working runner at all.
    struct RealGitRunner;

    impl CommandRunner for RealGitRunner {
        fn run(&self, program: &str, args: &[&str], cwd: &Path) -> Result<CommandOutput, CommandError> {
            let output = std::process::Command::new(program)
                .args(args)
                .current_dir(cwd)
                .output()
                .map_err(|e| CommandError::Io {
                    program: program.to_string(),
                    message: e.to_string(),
                })?;
            Ok(CommandOutput {
                exit_code: output.status.code(),
                stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            })
        }
    }

    /// A directory that is guaranteed not to sit inside any Git repository,
    /// so `callisto_vcs::GitRepository::discover` fails exactly the way it
    /// unconditionally does on `wasm32` -- the native-testable stand-in for
    /// "gix is unavailable" used to force `resolve_since` through its
    /// `CommandRunner` fallback. Mirrors `tags.rs`'s helper of the same
    /// name.
    fn non_repo_dir() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        assert!(
            callisto_vcs::GitRepository::discover(dir.path()).is_err(),
            "test fixture must not be discoverable as a Git repo"
        );
        dir
    }

    /// A `CommandRunner` double that answers `git rev-parse --verify --quiet
    /// <tag>^{commit}` with a canned SHA and counts invocations. Stands in
    /// for the real `git` binary on the `resolve_since` fallback path,
    /// exercised when gix is unavailable (`repo: None`, as is permanently
    /// the case on `wasm32`).
    struct FakeRevParseRunner {
        calls: AtomicUsize,
        tag: String,
        sha: CommitSha,
    }

    impl CommandRunner for FakeRevParseRunner {
        fn run(&self, program: &str, args: &[&str], _cwd: &Path) -> Result<CommandOutput, CommandError> {
            assert_eq!(program, "git");
            assert_eq!(
                args,
                [
                    "rev-parse",
                    "--verify",
                    "--quiet",
                    format!("{}^{{commit}}", self.tag).as_str()
                ]
            );
            self.calls.fetch_add(1, Ordering::SeqCst);
            Ok(CommandOutput {
                exit_code: Some(0),
                stdout: format!("{}\n", self.sha.as_str()),
                stderr: String::new(),
            })
        }
    }

    /// Spec: `load_changesets` must include the filename in its error when a changeset file
    /// fails `parse_changeset`. The bare `?` propagation previously produced a
    /// `GraphError::Format(ParseError)` with no path context, making it impossible for a
    /// developer to triage which file caused the failure in a workspace with many changesets.
    #[test]
    fn test_load_changesets_error_includes_filename() {
        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();
        let cs_dir = root.join(".changeset");
        std::fs::create_dir_all(&cs_dir).unwrap();

        // Missing `---` frontmatter delimiter — parse_changeset returns
        // ParseError::MissingFrontmatterStart. The error must carry the filename so the
        // developer can find the broken file.
        std::fs::write(cs_dir.join("malformed-changeset.md"), "cargo/foo: patch\n\nSummary.\n").unwrap();

        let cfg = crate::config::load(root).unwrap();
        let result = load_changesets(root, &cfg);

        let err = result.expect_err("load_changesets must return Err for a malformed changeset file");
        let err_display = format!("{err}");
        assert!(
            err_display.contains("malformed-changeset"),
            "error message must contain the offending filename so the developer can triage; \
             got: {err_display:?}"
        );
    }

    /// Spec: `resolve_since` must not silently degrade to `None` (forcing
    /// an unbounded full-history commit walk, see
    /// `test_aggregate_scopes_inference_window_to_last_tag`) just because
    /// gix is unavailable -- it must fall back (via `GitAccess`) to a
    /// `CommandRunner`-shelled `git rev-parse --verify --quiet
    /// <tag>^{commit}` call.
    #[test]
    fn test_resolve_since_falls_back_to_command_runner_without_gix() {
        let dir = non_repo_dir();
        let sha = CommitSha::parse("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef").unwrap();
        let runner = FakeRevParseRunner {
            calls: AtomicUsize::new(0),
            tag: "pkg-a@1.0.0".to_string(),
            sha: sha.clone(),
        };
        let git = GitAccess::discover(dir.path(), &runner);

        let resolved = resolve_since(&git, "pkg-a@1.0.0");

        assert_eq!(
            resolved,
            Some(sha),
            "resolve_since must resolve the tag via the CommandRunner fallback when gix is \
             unavailable, not silently return None"
        );
        assert_eq!(runner.calls.load(Ordering::SeqCst), 1);
    }

    struct SinglePackageGraph {
        pkg: Package,
    }

    impl DependencyResolver for SinglePackageGraph {
        fn packages(&self) -> impl Iterator<Item = &Package> {
            std::iter::once(&self.pkg)
        }

        fn dependencies_of(&self, _id: &PackageId) -> impl Iterator<Item = &DepEdge> {
            std::iter::empty()
        }

        fn dependents_of(&self, _id: &PackageId) -> impl Iterator<Item = &DepEdge> {
            std::iter::empty()
        }
    }

    /// Records the `since` value passed into `InferenceWindowSpec` without
    /// doing any real inference work.
    #[derive(Default)]
    struct RecordingInference {
        captured_since: Mutex<Option<CommitSha>>,
    }

    impl SeverityInference for RecordingInference {
        fn infer(
            &self,
            _pkg: &Package,
            _git: &GitAccess<'_>,
            window: InferenceWindowSpec<'_>,
        ) -> Result<Option<InferenceOutcome>, GraphError> {
            *self.captured_since.lock().unwrap() = window.since.clone();
            Ok(None)
        }
    }

    /// Spec: `aggregate()` must scope commit inference to `last_tag..HEAD`
    /// instead of walking full history on every run. Reproduces the bug by
    /// building a real one-package repo with a real release tag, then
    /// asserting the `since` field handed to `SeverityInference::infer`
    /// carries the commit SHA the tag points at (not `None`, which forces a
    /// full-history walk in `callisto_conventional::window::fetch_commits`).
    #[test]
    fn test_aggregate_scopes_inference_window_to_last_tag() {
        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        let pkg_id = PackageId::parse("pkg-a").unwrap();
        let tag_name = format!("{}@1.0.0", pkg_id.display_name());
        // Explicit message + disabled gpg signing so this is robust
        // regardless of the developer machine's global git config (e.g.
        // `tag.forceSignAnnotated` / `tag.gpgSign`).
        run_git(root, &["-c", "tag.gpgSign=false", "tag", "-m", "release", &tag_name]);

        // A commit landing after the tag; a correctly-scoped inference
        // window must never need to look past `tag_name` to find it, but a
        // `since: None` (full history) window would happily walk right over
        // it and beyond, all the way back to the repo root.
        std::fs::write(root.join("CHANGES.md"), "more\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "feat: add changes file"]);

        let expected_sha_output = std::process::Command::new("git")
            .args(["rev-parse", "--verify", "--quiet", &format!("{tag_name}^{{commit}}")])
            .current_dir(root)
            .output()
            .unwrap();
        assert!(expected_sha_output.status.success());
        let expected_sha = CommitSha::parse(String::from_utf8_lossy(&expected_sha_output.stdout).trim()).unwrap();

        let runner = RealGitRunner;
        let manifest = ManifestDecl::new("Cargo.toml", ManifestRole::Canonical, ManifestFormat::CargoToml).unwrap();
        let graph = SinglePackageGraph {
            pkg: Package {
                id: pkg_id.clone(),
                manifests: vec![manifest],
                changelog: None,
                release_trigger: callisto_model::ReleaseTrigger::Changeset,
                publish_to: Vec::new(),
                tag_template: None,
            },
        };
        let git = GitAccess::discover(root, &runner);
        let cfg = crate::config::load(root).unwrap();
        let tags = TagIndex::build(&git, &graph, &cfg).unwrap();

        // Sanity: the tag we just created was actually picked up.
        assert_eq!(
            tags.last_tag(&pkg_id).map(|t| t.version.render().to_string()),
            Some("1.0.0".to_string())
        );

        let inference = RecordingInference::default();
        let base_versions = BTreeMap::new();

        aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &inference).unwrap();

        let captured = inference.captured_since.lock().unwrap().clone();
        assert_eq!(
            captured,
            Some(expected_sha),
            "aggregate() must scope inference to last_tag..HEAD instead of hardcoding `since: None` \
             (full history)"
        );
    }

    struct FixedCommitsInference {
        commits: Vec<(CommitSha, String)>,
    }

    impl SeverityInference for FixedCommitsInference {
        fn infer(
            &self,
            _pkg: &Package,
            _git: &GitAccess<'_>,
            _window: InferenceWindowSpec<'_>,
        ) -> Result<Option<InferenceOutcome>, GraphError> {
            Ok(Some(InferenceOutcome {
                severity: Severity::Minor,
                commit_count: self.commits.len(),
                remapped: false,
                commits: self.commits.clone(),
            }))
        }
    }

    /// AC-003 scaffold: aggregate() must retain InferenceOutcome.commits
    /// on Aggregation.inference_commits keyed by package, not discard it
    /// after constructing BumpReason::Inference (which only carries a count).
    #[test]
    fn test_aggregate_retains_inference_commits_on_aggregation() {
        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();
        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        let pkg_id = PackageId::parse("pkg-a").unwrap();
        let manifest = ManifestDecl::new("Cargo.toml", ManifestRole::Canonical, ManifestFormat::CargoToml).unwrap();
        let graph = SinglePackageGraph {
            pkg: Package {
                id: pkg_id.clone(),
                manifests: vec![manifest],
                changelog: None,
                release_trigger: callisto_model::ReleaseTrigger::Changeset,
                publish_to: Vec::new(),
                tag_template: None,
            },
        };
        let runner = RealGitRunner;
        let git = GitAccess::discover(root, &runner);
        let cfg = crate::config::load(root).unwrap();
        let tags = TagIndex::build(&git, &graph, &cfg).unwrap();

        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_id.clone(), callisto_model::Version::semver(1, 0, 0));

        let sha_recent = CommitSha::parse(&"a".repeat(40)).unwrap();
        let inference = FixedCommitsInference {
            commits: vec![(sha_recent.clone(), "feat: recent".to_string())],
        };

        let agg = aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &inference).unwrap();

        assert_eq!(
            agg.inference_commits.get(&pkg_id),
            Some(&vec![(sha_recent, "feat: recent".to_string())]),
            "Aggregation.inference_commits must retain InferenceOutcome.commits for the package"
        );
    }

    /// Spec: since-resolution must go through `callisto_vcs::GitRepository`
    /// (gix), not the `CommandRunner` shell-out -- a `CommandRunner` that
    /// fails on every call must not prevent `since` from being resolved.
    #[test]
    fn test_aggregate_resolves_since_without_shelling_through_runner() {
        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        let pkg_id = PackageId::parse("pkg-a").unwrap();
        let tag_name = format!("{}@1.0.0", pkg_id.display_name());
        run_git(root, &["-c", "tag.gpgSign=false", "tag", "-m", "release", &tag_name]);

        std::fs::write(root.join("CHANGES.md"), "more\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "feat: add changes file"]);

        let expected_sha_output = std::process::Command::new("git")
            .args(["rev-parse", "--verify", "--quiet", &format!("{tag_name}^{{commit}}")])
            .current_dir(root)
            .output()
            .unwrap();
        assert!(expected_sha_output.status.success());
        let expected_sha = CommitSha::parse(String::from_utf8_lossy(&expected_sha_output.stdout).trim()).unwrap();

        let poisoned = PoisonedRunner;
        let manifest = ManifestDecl::new("Cargo.toml", ManifestRole::Canonical, ManifestFormat::CargoToml).unwrap();
        let graph = SinglePackageGraph {
            pkg: Package {
                id: pkg_id.clone(),
                manifests: vec![manifest],
                changelog: None,
                release_trigger: callisto_model::ReleaseTrigger::Changeset,
                publish_to: Vec::new(),
                tag_template: None,
            },
        };
        let git = GitAccess::discover(root, &poisoned);
        let cfg = crate::config::load(root).unwrap();
        let tags = TagIndex::build(&git, &graph, &cfg).unwrap();

        assert_eq!(
            tags.last_tag(&pkg_id).map(|t| t.version.render().to_string()),
            Some("1.0.0".to_string())
        );

        let inference = RecordingInference::default();
        let base_versions = BTreeMap::new();

        aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &inference).unwrap();

        let captured = inference.captured_since.lock().unwrap().clone();
        assert_eq!(
            captured,
            Some(expected_sha),
            "aggregate() must resolve `since` via callisto_vcs::GitRepository (gix), not by \
             shelling out through the CommandRunner"
        );
    }

    fn make_pkg(id: PackageId) -> Package {
        let manifest = ManifestDecl::new("Cargo.toml", ManifestRole::Canonical, ManifestFormat::CargoToml).unwrap();
        Package {
            id,
            manifests: vec![manifest],
            changelog: None,
            release_trigger: callisto_model::ReleaseTrigger::Changeset,
            publish_to: Vec::new(),
            tag_template: None,
        }
    }

    /// Spec: a changeset entry naming a package by its bare name (no
    /// ecosystem prefix) must NOT silently resolve against an arbitrary
    /// candidate when the graph contains packages in two or more ecosystems
    /// sharing that name. Resolving `foo` against both `cargo/foo` and
    /// `npm/foo` is genuinely ambiguous and must be a caller-visible error,
    /// not a first-match-wins pick based on iteration order.
    #[test]
    fn test_resolve_target_package_ambiguous_bare_name_errors() {
        let pkg_cargo = make_pkg(PackageId::parse("cargo/foo").unwrap());
        let pkg_npm = make_pkg(PackageId::parse("npm/foo").unwrap());
        let packages = [pkg_cargo, pkg_npm];
        let bare = PackageId::parse("foo").unwrap();

        let result = resolve_target_package(packages.iter(), &bare);

        match result {
            Err(GraphError::AmbiguousName { name, candidates }) => {
                assert_eq!(name, "foo");
                assert_eq!(candidates.len(), 2);
                assert!(candidates.contains(&PackageId::parse("cargo/foo").unwrap()));
                assert!(candidates.contains(&PackageId::parse("npm/foo").unwrap()));
            }
            other => panic!("expected GraphError::AmbiguousName, got {other:?}"),
        }
    }

    /// Spec: a bare-name lookup must still resolve fine when the name is
    /// unambiguous (only one package with that name across all ecosystems
    /// in the graph).
    #[test]
    fn test_resolve_target_package_unambiguous_bare_name_resolves() {
        let pkg_cargo = make_pkg(PackageId::parse("cargo/foo").unwrap());
        let pkg_other = make_pkg(PackageId::parse("cargo/bar").unwrap());
        let packages = [pkg_cargo, pkg_other];
        let bare = PackageId::parse("foo").unwrap();

        let result = resolve_target_package(packages.iter(), &bare).unwrap();

        assert_eq!(
            result.map(|p| p.id.clone()),
            Some(PackageId::parse("cargo/foo").unwrap())
        );
    }

    /// Spec: a bare-name lookup for a name that doesn't exist anywhere in
    /// the graph resolves to `None` (not an error) -- unknown-package
    /// reporting is the caller's responsibility (see validate.rs).
    #[test]
    fn test_resolve_target_package_unknown_name_returns_none() {
        let pkg_cargo = make_pkg(PackageId::parse("cargo/foo").unwrap());
        let packages = [pkg_cargo];
        let bare = PackageId::parse("does-not-exist").unwrap();

        let result = resolve_target_package(packages.iter(), &bare).unwrap();

        assert!(result.is_none());
    }

    /// Spec: the ambiguity check must not assume exactly two colliding
    /// candidates. A workspace with the same bare name registered in three
    /// or more ecosystems (cargo/foo, npm/foo, pypi/foo) must still report
    /// every candidate in `AmbiguousName`, not just the first two (an
    /// off-by-one truncation or a hardcoded pairwise assumption would not
    /// be caught by the two-ecosystem test above).
    #[test]
    fn test_resolve_target_package_ambiguous_bare_name_three_ecosystems_errors() {
        let pkg_cargo = make_pkg(PackageId::parse("cargo/foo").unwrap());
        let pkg_npm = make_pkg(PackageId::parse("npm/foo").unwrap());
        let pkg_pypi = make_pkg(PackageId::parse("pypi/foo").unwrap());
        let packages = [pkg_cargo, pkg_npm, pkg_pypi];
        let bare = PackageId::parse("foo").unwrap();

        let result = resolve_target_package(packages.iter(), &bare);

        match result {
            Err(GraphError::AmbiguousName { name, candidates }) => {
                assert_eq!(name, "foo");
                assert_eq!(candidates.len(), 3);
                assert!(candidates.contains(&PackageId::parse("cargo/foo").unwrap()));
                assert!(candidates.contains(&PackageId::parse("npm/foo").unwrap()));
                assert!(candidates.contains(&PackageId::parse("pypi/foo").unwrap()));
            }
            other => panic!("expected GraphError::AmbiguousName with 3 candidates, got {other:?}"),
        }
    }

    /// Spec: bare-name matching against `PackageId::name()` is a plain
    /// string comparison, which is case-sensitive. A package registered as
    /// `cargo/Foo` must NOT be resolved by a bare lookup for `foo` -- they
    /// are treated as distinct names, so the lookup resolves to `None`
    /// (unknown-package) rather than matching or erroring as ambiguous.
    /// This test pins down that actual behavior explicitly so a future
    /// change to case handling is a deliberate, visible decision.
    #[test]
    fn test_resolve_target_package_bare_name_matching_is_case_sensitive() {
        let pkg_cargo = make_pkg(PackageId::parse("cargo/Foo").unwrap());
        let packages = [pkg_cargo];
        let bare = PackageId::parse("foo").unwrap();

        let result = resolve_target_package(packages.iter(), &bare).unwrap();

        assert!(
            result.is_none(),
            "case-sensitive name comparison must not match 'foo' against 'Foo'"
        );
    }

    /// Spec: a changeset where EVERY entry references a package not in the
    /// workspace must NOT be added to `consumed` (which would silently delete
    /// it on disk) and must emit a `DiagnosticCode::UnknownPackage` warning
    /// for each orphaned entry.  On the current (unfixed) code, the changeset
    /// IS added to `consumed` before the entry loop, so it ends up deleted
    /// despite no version bump ever being recorded.
    #[test]
    fn test_orphaned_changeset_not_consumed_emits_unknown_package_diagnostic() {
        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        // Minimal git repo so TagIndex::build can enumerate tags.
        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        // Changeset referencing only pkg-foo which is NOT in the workspace.
        let cs_dir = root.join(".changeset");
        std::fs::create_dir_all(&cs_dir).unwrap();
        std::fs::write(
            cs_dir.join("orphan-cs.md"),
            "---\n\"pkg-foo\": minor\n---\n\nOrphaned changeset.\n",
        )
        .unwrap();

        // Workspace has only pkg-bar.
        let pkg_bar_id = PackageId::parse("pkg-bar").unwrap();
        let graph = SinglePackageGraph {
            pkg: make_pkg(pkg_bar_id.clone()),
        };
        let cfg = crate::config::load(root).unwrap();
        let runner = RealGitRunner;
        let git = GitAccess::discover(root, &runner);
        let tags = crate::tags::TagIndex::build(&git, &graph, &cfg).unwrap();

        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_bar_id.clone(), Version::semver(1, 0, 0));

        let inference = RecordingInference::default();
        let agg = aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &inference).unwrap();

        assert!(
            agg.consumed.is_empty(),
            "a fully-orphaned changeset (all entries reference non-existent packages) must NOT \
             be added to consumed (which would cause it to be deleted on disk): got {:?}",
            agg.consumed
        );

        let unknown_pkg_diags: Vec<_> = agg
            .diagnostics
            .iter()
            .filter(|d| d.code == callisto_model::DiagnosticCode::UnknownPackage)
            .collect();
        assert!(
            !unknown_pkg_diags.is_empty(),
            "must emit at least one UnknownPackage diagnostic for orphaned changeset entries; \
             got diagnostics: {:?}",
            agg.diagnostics
        );
    }

    /// Spec: when a fixed group in callisto.toml references a package that
    /// no longer exists in the workspace, `union_fixed` must NOT insert
    /// the stale member into `agg.severities`. Doing so causes
    /// `bump_target` in `solve_cascade` to call
    /// `input.base.get(stale_id)` -> `None` ->
    /// `Err(GraphError::Manifest(MissingField))`, crashing `callisto
    /// version` with a misleading error. The stale member must be skipped
    /// and an `UnknownPackage` warning emitted.
    ///
    /// Setup: `pkg_bar` has `Severity::Minor` (from a changeset), `pkg_baz`
    /// has none yet. Fixed group has all three: `pkg_foo` (stale),
    /// `pkg_bar`, `pkg_baz`. `union_fixed` should propagate `Minor` to
    /// `pkg_baz`, skip `pkg_foo` with a diagnostic, and
    /// return `true` because `pkg_baz` changed.
    #[test]
    fn test_union_fixed_stale_member_emits_diagnostic_and_is_skipped() {
        let pkg_foo = PackageId::parse("pkg-foo").unwrap(); // stale: removed from workspace
        let pkg_bar = PackageId::parse("pkg-bar").unwrap(); // real workspace package (has severity)
        let pkg_baz = PackageId::parse("pkg-baz").unwrap(); // real workspace package (no severity yet)

        let mut agg = Aggregation::default();
        // pkg-bar has a changeset-driven Minor bump; pkg-baz has nothing yet.
        agg.severities.insert(pkg_bar.clone(), Severity::Minor);
        agg.named_by.insert(pkg_bar.clone(), NamedBy::Changeset);

        let mut groups = GroupTable::default();
        let group_def = GroupDef {
            name: GroupName("fixed-grp".to_string()),
            kind: GroupKind::Fixed,
            members: vec![
                GroupMember::Package(pkg_foo.clone()),
                GroupMember::Package(pkg_bar.clone()),
                GroupMember::Package(pkg_baz.clone()),
            ],
        };
        groups.fixed.insert(group_def.name.clone(), group_def);

        // Only pkg-bar and pkg-baz are in the workspace; pkg-foo is stale.
        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_bar.clone(), Version::semver(1, 0, 0));
        base_versions.insert(pkg_baz.clone(), Version::semver(1, 0, 0));

        let changed = union_fixed(&mut agg, &groups, &base_versions);

        // pkg_baz had no severity but should now have Minor propagated from pkg_bar.
        assert!(
            changed,
            "union_fixed must return true because pkg-baz received a propagated severity"
        );
        assert_eq!(
            agg.severities.get(&pkg_baz),
            Some(&Severity::Minor),
            "real member pkg-baz must receive the propagated Minor severity"
        );
        // The stale member must never enter severities.
        assert!(
            !agg.severities.contains_key(&pkg_foo),
            "stale group member pkg-foo must NOT be inserted into severities (would crash cascade \
             with a misleading MissingField error)"
        );

        let unknown_diags: Vec<_> = agg
            .diagnostics
            .iter()
            .filter(|d| d.code == callisto_model::DiagnosticCode::UnknownPackage)
            .collect();
        assert!(
            !unknown_diags.is_empty(),
            "must emit an UnknownPackage diagnostic for stale fixed group member; \
             got diagnostics: {:?}",
            agg.diagnostics
        );
    }

    fn linked_group(name: &str, members: &[PackageId]) -> GroupTable {
        let mut groups = GroupTable::default();
        let group_def = GroupDef {
            name: GroupName(name.to_string()),
            kind: GroupKind::Linked,
            members: members.iter().cloned().map(GroupMember::Package).collect(),
        };
        groups.linked.insert(group_def.name.clone(), group_def);
        groups
    }

    #[test]
    fn test_union_linked_propagates_severity_from_named_member() {
        let pkg_a = PackageId::parse("pkg-a").unwrap();
        let pkg_b = PackageId::parse("pkg-b").unwrap();

        let mut agg = Aggregation::default();
        agg.severities.insert(pkg_b.clone(), Severity::Minor);
        agg.named_by.insert(pkg_b.clone(), NamedBy::Changeset);

        let groups = linked_group("linked-pair", &[pkg_a.clone(), pkg_b.clone()]);

        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_a.clone(), Version::semver(1, 0, 0));
        base_versions.insert(pkg_b.clone(), Version::semver(1, 0, 0));

        let changed = union_linked(&mut agg, &groups, &base_versions);

        assert!(changed);
        assert_eq!(agg.severities.get(&pkg_a), Some(&Severity::Minor));
        assert_eq!(agg.severities.get(&pkg_b), Some(&Severity::Minor));
        assert_eq!(
            agg.reasons.get(&pkg_a),
            Some(&BumpReason::LinkedGroupUnion {
                group: GroupName("linked-pair".to_string()),
            })
        );
    }

    #[test]
    fn test_union_linked_does_not_downgrade_higher_existing_severity() {
        let pkg_a = PackageId::parse("pkg-a").unwrap();
        let pkg_b = PackageId::parse("pkg-b").unwrap();

        let mut agg = Aggregation::default();
        agg.severities.insert(pkg_a.clone(), Severity::Major);
        agg.severities.insert(pkg_b.clone(), Severity::Minor);
        agg.named_by.insert(pkg_a.clone(), NamedBy::Inference);
        agg.named_by.insert(pkg_b.clone(), NamedBy::Changeset);

        let groups = linked_group("linked-pair", &[pkg_a.clone(), pkg_b.clone()]);

        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_a.clone(), Version::semver(1, 0, 0));
        base_versions.insert(pkg_b.clone(), Version::semver(1, 0, 0));

        let changed = union_linked(&mut agg, &groups, &base_versions);

        assert!(changed);
        assert_eq!(agg.severities.get(&pkg_a), Some(&Severity::Major));
        assert_eq!(agg.severities.get(&pkg_b), Some(&Severity::Major));
    }

    #[test]
    fn test_union_linked_noop_when_no_member_named() {
        let pkg_a = PackageId::parse("pkg-a").unwrap();
        let pkg_b = PackageId::parse("pkg-b").unwrap();

        let mut agg = Aggregation::default();
        let groups = linked_group("linked-pair", &[pkg_a.clone(), pkg_b.clone()]);

        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_a.clone(), Version::semver(1, 0, 0));
        base_versions.insert(pkg_b.clone(), Version::semver(1, 0, 0));

        let changed = union_linked(&mut agg, &groups, &base_versions);

        assert!(!changed);
        assert!(agg.severities.is_empty());
    }

    /// Spec: when `SeverityInference::infer` returns `Err`, `aggregate()` must emit a
    /// diagnostic (warning level) describing the failure rather than silently discarding
    /// the error and leaving the package with no inferred severity bump.
    #[test]
    fn test_aggregate_inference_error_emits_diagnostic() {
        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        let pkg_id = PackageId::parse("pkg-a").unwrap();
        let graph = SinglePackageGraph {
            pkg: make_pkg(pkg_id.clone()),
        };
        let cfg = crate::config::load(root).unwrap();
        let runner = RealGitRunner;
        let git = GitAccess::discover(root, &runner);
        let tags = crate::tags::TagIndex::build(&git, &graph, &cfg).unwrap();
        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_id.clone(), Version::semver(1, 0, 0));

        struct AlwaysErrorInference;
        impl SeverityInference for AlwaysErrorInference {
            fn infer(
                &self,
                _pkg: &Package,
                _git: &GitAccess<'_>,
                _window: InferenceWindowSpec<'_>,
            ) -> Result<Option<InferenceOutcome>, GraphError> {
                Err(GraphError::Vcs(callisto_vcs::VcsError::Git(
                    "simulated inference failure".into(),
                )))
            }
        }

        let agg = aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &AlwaysErrorInference).unwrap();

        assert!(
            !agg.diagnostics.is_empty(),
            "aggregate() must emit a diagnostic when SeverityInference::infer returns Err; got none"
        );
    }

    /// Spec: a bare-name `[[package]]` rule in callisto.toml must match a workspace
    /// package with a prefixed ID (e.g. `cargo/pkg-a`) via `PackageId::matches()`.
    /// The previous `id == &pkg.id` structural equality check was silently inert for
    /// prefixed package IDs when the config rule used a bare name.
    #[test]
    fn test_aggregate_bare_name_config_policy_matches_prefixed_package() {
        use crate::config::resolve::PreMajorInferencePolicy;
        use std::sync::atomic::AtomicBool;

        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        // Config uses a BARE name, but the workspace package has a PREFIXED ID.
        // PackageId::matches() must bridge the gap; == does not.
        std::fs::write(
            root.join("callisto.toml"),
            "[[package]]\nmatch = \"pkg-a\"\npre-major-inference = \"conservative\"\n",
        )
        .unwrap();

        let pkg_id = PackageId::parse("cargo/pkg-a").unwrap();
        let graph = SinglePackageGraph {
            pkg: make_pkg(pkg_id.clone()),
        };
        let cfg = crate::config::load(root).unwrap();
        let runner = RealGitRunner;
        let git = GitAccess::discover(root, &runner);
        let tags = crate::tags::TagIndex::build(&git, &graph, &cfg).unwrap();
        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_id.clone(), Version::semver(0, 1, 0));

        struct PolicyCapturingInference2 {
            saw_non_off: AtomicBool,
        }
        impl SeverityInference for PolicyCapturingInference2 {
            fn infer(
                &self,
                _pkg: &Package,
                _git: &GitAccess<'_>,
                window: InferenceWindowSpec<'_>,
            ) -> Result<Option<InferenceOutcome>, GraphError> {
                if window.policy != PreMajorInferencePolicy::Off {
                    self.saw_non_off.store(true, Ordering::SeqCst);
                }
                Ok(None)
            }
        }

        let capturing = PolicyCapturingInference2 {
            saw_non_off: AtomicBool::new(false),
        };
        aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &capturing).unwrap();

        assert!(
            capturing.saw_non_off.load(Ordering::SeqCst),
            "a bare-name [[package]] rule must match a prefixed package ID via \
             PackageId::matches(); the old == comparison was silently inert for \
             cargo/pkg-a when callisto.toml uses match = \"pkg-a\""
        );
    }

    /// Spec: during a pre-release cycle (PreMode::Pre), aggregate() must NOT populate
    /// agg.consumed. Changesets must remain on disk so they can be re-applied when the
    /// cycle exits. The previous code unconditionally pushed to consumed regardless of
    /// the PreState passed in.
    #[test]
    fn test_aggregate_does_not_consume_changesets_during_pre_mode() {
        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        let cs_dir = root.join(".changeset");
        std::fs::create_dir_all(&cs_dir).unwrap();
        std::fs::write(
            cs_dir.join("some-feature.md"),
            "---\n\"pkg-a\": minor\n---\n\nA feature in pre mode.\n",
        )
        .unwrap();

        let pkg_id = PackageId::parse("pkg-a").unwrap();
        let graph = SinglePackageGraph {
            pkg: make_pkg(pkg_id.clone()),
        };
        let cfg = crate::config::load(root).unwrap();
        let runner = RealGitRunner;
        let git = GitAccess::discover(root, &runner);
        let tags = crate::tags::TagIndex::build(&git, &graph, &cfg).unwrap();
        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_id.clone(), Version::semver(1, 0, 0));

        let pre_state = callisto_format::PreState::entering("next", [("pkg-a".to_string(), Version::semver(1, 0, 0))]);

        let inference = RecordingInference::default();
        let agg = aggregate(&graph, &cfg, &git, &tags, &base_versions, Some(&pre_state), &inference).unwrap();

        assert!(
            agg.consumed.is_empty(),
            "changesets must NOT be consumed during a pre-release cycle (PreMode::Pre); \
             agg.consumed must be empty but got: {:?}",
            agg.consumed
        );
    }

    /// Spec: `aggregate()` must pass the per-package `pre_major_inference` policy from
    /// `config.packages` into `InferenceWindowSpec`, not always hardcode `OFF`.
    #[test]
    fn test_aggregate_pre_major_inference_policy_applied() {
        use crate::config::resolve::PreMajorInferencePolicy;
        use std::sync::atomic::AtomicBool;

        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        // Write a callisto.toml with pre_major_inference = "conservative" for pkg-a.
        // The [[package]] section requires a `match` field (pattern to match package names).
        std::fs::write(
            root.join("callisto.toml"),
            "[[package]]\nmatch = \"pkg-a\"\npre-major-inference = \"conservative\"\n",
        )
        .unwrap();

        let pkg_id = PackageId::parse("pkg-a").unwrap();
        let graph = SinglePackageGraph {
            pkg: make_pkg(pkg_id.clone()),
        };
        let cfg = crate::config::load(root).unwrap();
        let runner = RealGitRunner;
        let git = GitAccess::discover(root, &runner);
        let tags = crate::tags::TagIndex::build(&git, &graph, &cfg).unwrap();
        let mut base_versions = BTreeMap::new();
        base_versions.insert(pkg_id.clone(), Version::semver(0, 1, 0));

        // An inference impl that records whether it received a non-OFF policy.
        struct PolicyCapturingInference {
            saw_non_off: AtomicBool,
        }
        impl SeverityInference for PolicyCapturingInference {
            fn infer(
                &self,
                _pkg: &Package,
                _git: &GitAccess<'_>,
                window: InferenceWindowSpec<'_>,
            ) -> Result<Option<InferenceOutcome>, GraphError> {
                if window.policy != PreMajorInferencePolicy::Off {
                    self.saw_non_off.store(true, Ordering::SeqCst);
                }
                Ok(None)
            }
        }

        let capturing = PolicyCapturingInference {
            saw_non_off: AtomicBool::new(false),
        };
        aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &capturing).unwrap();

        assert!(
            capturing.saw_non_off.load(Ordering::SeqCst),
            "aggregate() must pass the per-package pre_major_inference policy from config.packages \
             into InferenceWindowSpec; received OFF even though callisto.toml sets conservative"
        );
    }

    /// AC-F7a: Prefixed rule (npm:pkg, OFF policy) must win over Bare rule (pkg, conservative)
    /// even when the Bare rule is declared first in callisto.toml.
    /// With single-pass lookup: the Bare rule (declared first) wins -> conservative applied.
    /// With resolve_package_config (two-pass): the Prefixed rule wins -> OFF applied.
    ///
    /// Two AtomicBool flags:
    /// - invoked: true if infer() was called at all (proves the package is pre-1.0 and
    ///   pre-major-inference was consulted; distinguishes OFF-applied from never-called).
    /// - saw_non_off: true if infer() received a non-OFF policy (single-pass failure mode).
    #[test]
    fn test_pre_major_inference_prefixed_beats_bare_when_bare_declared_first() {
        use crate::config::resolve::PreMajorInferencePolicy;
        use std::sync::atomic::AtomicBool;

        let ws_dir = tempfile::tempdir().unwrap();
        let root = ws_dir.path();

        init_repo(root);
        std::fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "."]);
        run_git(root, &["commit", "-q", "-m", "initial commit"]);

        // Bare rule declared FIRST in TOML: match = "pkg", pre-major-inference = "conservative"
        // Prefixed rule declared SECOND: match = "npm:pkg", pre-major-inference = "off"
        // Single-pass find() returns pkg (Bare, declared first) -> conservative applied.
        // Two-pass resolve_package_config: pass 1 finds npm:pkg (Prefixed) -> OFF applied.
        std::fs::write(
            root.join("callisto.toml"),
            "[[package]]\nmatch = \"pkg\"\npre-major-inference = \"conservative\"\n\n[[package]]\nmatch = \"npm:pkg\"\npre-major-inference = \"off\"\n",
        )
        .unwrap();

        let pkg_id = PackageId::parse("pkg").unwrap();
        let graph = SinglePackageGraph {
            pkg: make_pkg(pkg_id.clone()),
        };
        let cfg = crate::config::load(root).unwrap();
        let runner = RealGitRunner;
        let git = GitAccess::discover(root, &runner);
        let tags = crate::tags::TagIndex::build(&git, &graph, &cfg).unwrap();
        let mut base_versions = BTreeMap::new();
        // Version 0.1.0 (pre-1.0) ensures pre-major-inference is consulted.
        base_versions.insert(pkg_id.clone(), Version::semver(0, 1, 0));

        struct PolicyCapturingInference {
            invoked: AtomicBool,
            saw_non_off: AtomicBool,
        }
        impl SeverityInference for PolicyCapturingInference {
            fn infer(
                &self,
                _pkg: &Package,
                _git: &GitAccess<'_>,
                window: InferenceWindowSpec<'_>,
            ) -> Result<Option<InferenceOutcome>, GraphError> {
                // Set invoked before any policy check so we can distinguish
                // OFF-policy-applied from never-called.
                self.invoked.store(true, Ordering::SeqCst);
                if window.policy != PreMajorInferencePolicy::Off {
                    self.saw_non_off.store(true, Ordering::SeqCst);
                }
                Ok(None)
            }
        }

        let capturing = PolicyCapturingInference {
            invoked: AtomicBool::new(false),
            saw_non_off: AtomicBool::new(false),
        };
        aggregate(&graph, &cfg, &git, &tags, &base_versions, None, &capturing).unwrap();

        assert!(
            capturing.invoked.load(Ordering::SeqCst),
            "inference was never invoked; fixture is wrong and cannot distinguish OFF policy \
             from no invocation. Ensure Version::semver(0, 1, 0) is in base_versions so the \
             package is pre-1.0 and pre-major-inference is consulted."
        );
        assert!(
            !capturing.saw_non_off.load(Ordering::SeqCst),
            "expected OFF policy from Prefixed rule (npm:pkg); Bare rule (conservative) was \
             applied instead. Two-pass specificity is required: Prefixed rules must win over \
             Bare rules regardless of declaration order."
        );
    }
}