fallow-cli 2.78.1

CLI for fallow, Rust-native codebase intelligence for TypeScript and JavaScript
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
//! Auto-fix for `unused-catalog-entries` findings.
//!
//! Removes unused pnpm catalog entries from `pnpm-workspace.yaml`. The
//! strategy is line-aware deletion rather than full YAML parse-and-reprint:
//! there is no comment-preserving YAML writer in the workspace, and a
//! full reprint via `serde_yaml_ng` would obliterate comments, anchors,
//! and stylistic choices. Each entry's start line is taken from the
//! finding's `line` field; the end line is computed by scanning forward
//! for lines whose indentation is strictly greater than the entry line's
//! own indent (this covers object-form entries such as
//! `react:\n    specifier: ^18.2.0\n    publishConfig: {}`).
//!
//! Entries whose `hardcoded_consumers` is non-empty are skipped: removing
//! the catalog entry while a workspace package still references it via
//! the `catalog:` protocol would break the user's next `pnpm install`.
//! The skip is reported in the fix output (and in human stderr) so the
//! user knows to migrate the consumer first.
//!
//! Multi-document YAML files (`---` document separators) are rejected
//! with a skip record because the single-pass line scanner cannot
//! reliably attribute lines to documents.

use std::path::Path;

use fallow_config::{CatalogPrecedingCommentPolicy, OutputFormat};
use fallow_core::results::{
    EmptyCatalogGroup, EmptyCatalogGroupFinding, UnusedCatalogEntry, UnusedCatalogEntryFinding,
};

use super::plan::{CapturedHashes, FixPlan, read_source_with_hash_check};

/// Apply unused-catalog-entry fixes to `pnpm-workspace.yaml`.
///
/// Returns `(had_write_error, applied_count, skipped_count)` so the
/// orchestrator can build the top-level fix-output summary. The returned
/// `skipped_count` only counts entries that were intentionally not
/// removed (hardcoded consumer, multi-doc YAML, line out of range); it
/// does NOT count entries that produced a write error.
#[expect(
    clippy::too_many_arguments,
    reason = "fix-layer signatures match the orchestrator's call shape: root + entries + policy + (hashes, plan) for issue #454 batch atomicity + output/dry_run/fixes for the per-fixer wire"
)]
pub(super) fn apply_catalog_entry_fixes(
    root: &Path,
    entries: &[UnusedCatalogEntryFinding],
    preceding_comment_policy: CatalogPrecedingCommentPolicy,
    hashes: &CapturedHashes,
    plan: &mut FixPlan,
    output: OutputFormat,
    dry_run: bool,
    fixes: &mut Vec<serde_json::Value>,
) -> CatalogFixSummary {
    let mut summary = CatalogFixSummary::default();

    if entries.is_empty() {
        return summary;
    }

    // All entries share the same file (`pnpm-workspace.yaml`), but we group
    // defensively so we read+write the file once even if a future detector
    // adds entries from multiple files.
    let mut by_path: rustc_hash::FxHashMap<&Path, Vec<&UnusedCatalogEntry>> =
        rustc_hash::FxHashMap::default();
    for entry in entries {
        let entry = &entry.entry;
        by_path.entry(entry.path.as_path()).or_default().push(entry);
    }

    for (relative_path, file_entries) in by_path {
        let absolute = root.join(relative_path);
        let Some((content, meta)) = read_source_with_hash_check(root, &absolute, hashes, plan)
        else {
            // Skip silently when the workspace file is unreadable or escapes
            // the root: matches the existing pattern in enum_members/deps.
            // Hash mismatch records itself on `plan.skipped()`; the
            // orchestrator surfaces it.
            continue;
        };

        // Multi-document YAML defense (panel P1.6). The line scanner cannot
        // reliably attribute lines to documents when `---` separators are
        // present; refuse to edit and surface the skip.
        if is_multi_document_yaml(&content) {
            for entry in &file_entries {
                summary.skipped += 1;
                fixes.push(skip_record(
                    entry,
                    "multi_document_yaml",
                    "Skipped: pnpm-workspace.yaml contains a `---` document separator; fallow fix does not support multi-document YAML",
                    output,
                    relative_path,
                ));
            }
            continue;
        }

        let lines: Vec<&str> = content.split(meta.line_ending).collect();

        // Compute the line range for each entry and split into "remove" vs
        // "skip" buckets.
        let mut to_remove: Vec<(std::ops::Range<usize>, &UnusedCatalogEntry)> = Vec::new();
        for entry in &file_entries {
            if !entry.hardcoded_consumers.is_empty() {
                summary.skipped += 1;
                let consumer_summary = format_consumer_summary(&entry.hardcoded_consumers);
                let description = format!(
                    "Skipped: {consumer_summary} still pin `{}` with a hardcoded version. Switch the consumer(s) to \"{}\": \"catalog:{}\" first, then rerun fallow fix.",
                    entry.entry_name,
                    entry.entry_name,
                    if entry.catalog_name == "default" {
                        String::new()
                    } else {
                        entry.catalog_name.clone()
                    },
                );
                fixes.push(skip_record(
                    entry,
                    "hardcoded_consumers",
                    &description,
                    output,
                    relative_path,
                ));
                continue;
            }

            let line_idx = entry.line.saturating_sub(1) as usize;
            if line_idx >= lines.len() {
                summary.skipped += 1;
                fixes.push(skip_record(
                    entry,
                    "line_out_of_range",
                    "Skipped: the reported line is past the end of pnpm-workspace.yaml; the file may have been edited since fallow check ran",
                    output,
                    relative_path,
                ));
                continue;
            }

            let range = compute_deletion_range(&lines, line_idx, entry, preceding_comment_policy);
            to_remove.push((range, entry));
        }

        if to_remove.is_empty() {
            continue;
        }

        // Sort descending by start so removals don't shift later indices.
        // Use end as a tiebreaker (longer-range first) so an overlapping
        // pair is handled deterministically.
        to_remove.sort_by(|a, b| {
            b.0.start
                .cmp(&a.0.start)
                .then_with(|| b.0.end.cmp(&a.0.end))
        });

        // Dedup overlapping ranges. With at most one entry per source line
        // (the detector emits one finding per line), overlap should only
        // occur on object-form entries where two findings somehow share a
        // span. Keep the first (longer) range in each overlapping pair.
        let mut deduped: Vec<(std::ops::Range<usize>, &UnusedCatalogEntry)> = Vec::new();
        for (range, entry) in to_remove {
            if let Some((last_range, _)) = deduped.last()
                && last_range.start < range.end
                && range.start < last_range.end
            {
                continue;
            }
            deduped.push((range, entry));
        }

        if dry_run {
            for (range, entry) in &deduped {
                if !matches!(output, OutputFormat::Json) {
                    eprintln!(
                        "Would remove catalog entry from {}:{} `{}` (catalog: {})",
                        relative_path.display(),
                        range.start + 1,
                        entry.entry_name,
                        entry.catalog_name,
                    );
                }
                fixes.push(remove_record(entry, range, false, relative_path));
            }
            summary.applied += deduped.len();
            continue;
        }

        // Track the parent header line for each deletion so we can detect
        // when an entire catalog group becomes empty (e.g. removing the
        // last entry from `catalogs.react17` leaves `react17:` with a
        // null value, which pnpm rejects with "Cannot convert undefined
        // or null to object" at install time).
        let parent_header_indices: Vec<usize> = deduped
            .iter()
            .filter_map(|(_, entry)| find_parent_header_line(&lines, entry))
            .collect();

        // Apply: drain ranges from a fresh Vec<String>, rewrite emptied
        // parent headers to `key: {}`, validate by reparse, then atomic-write.
        let mut new_lines: Vec<String> = lines.iter().map(ToString::to_string).collect();
        for (range, _) in &deduped {
            new_lines.drain(range.clone());
        }
        rewrite_empty_catalog_parents(&mut new_lines, &parent_header_indices, &deduped);

        let mut new_content = new_lines.join(meta.line_ending);
        if content.ends_with(meta.line_ending) && !new_content.ends_with(meta.line_ending) {
            new_content.push_str(meta.line_ending);
        }

        // Reparse-validate (panel P1.7). If the post-edit content fails to
        // parse, abort the write rather than risk corrupting the file. We
        // do not attempt a structural diff: any successful parse is a good
        // enough signal here, because the failure modes the validator
        // catches are syntactic (indent disasters, key-value disasters).
        if serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&new_content).is_err() {
            summary.write_error = true;
            eprintln!(
                "Error: refusing to write {}: post-edit content failed YAML reparse. The file was not modified.",
                relative_path.display(),
            );
            continue;
        }

        // Stage the post-edit YAML for the orchestrator's batch commit.
        // Pre-stage YAML reparse-validation above ensures we never queue
        // a syntactically broken document; rename-time errors are reported
        // per-path by the orchestrator.
        plan.stage(
            absolute.clone(),
            super::io::bytes_with_optional_bom(new_content, &meta),
        );

        for (range, entry) in &deduped {
            let mut record = remove_record(entry, range, true, relative_path);
            // Sidechannel so the orchestrator can flip `applied: false`
            // post-commit if the rename for this absolute path fails.
            record["__target"] = serde_json::json!(absolute.display().to_string());
            fixes.push(record);
            let entry_idx = entry.line.saturating_sub(1) as usize;
            summary.comment_lines_removed += entry_idx.saturating_sub(range.start);
        }
        summary.applied += deduped.len();
    }

    summary
}

/// Apply empty-catalog-group fixes to `pnpm-workspace.yaml`.
///
/// Deletes only the named catalog header line. Comments or blank lines between
/// that header and the next sibling remain in place, matching the conservative
/// comment-preservation policy used by the catalog entry fixer.
pub(super) fn apply_empty_catalog_group_fixes(
    root: &Path,
    groups: &[EmptyCatalogGroupFinding],
    hashes: &CapturedHashes,
    plan: &mut FixPlan,
    output: OutputFormat,
    dry_run: bool,
    fixes: &mut Vec<serde_json::Value>,
) -> CatalogFixSummary {
    let mut summary = CatalogFixSummary::default();

    if groups.is_empty() {
        return summary;
    }

    let mut by_path: rustc_hash::FxHashMap<&Path, Vec<&EmptyCatalogGroup>> =
        rustc_hash::FxHashMap::default();
    for group in groups {
        let group = &group.group;
        by_path.entry(group.path.as_path()).or_default().push(group);
    }

    for (relative_path, file_groups) in by_path {
        let absolute = root.join(relative_path);
        let Some((content, meta)) = read_source_with_hash_check(root, &absolute, hashes, plan)
        else {
            continue;
        };

        if is_multi_document_yaml(&content) {
            for group in &file_groups {
                summary.skipped += 1;
                fixes.push(skip_group_record(
                    group,
                    "multi_document_yaml",
                    "Skipped: pnpm-workspace.yaml contains a `---` document separator; fallow fix does not support multi-document YAML",
                    output,
                    relative_path,
                ));
            }
            continue;
        }

        let lines: Vec<&str> = content.split(meta.line_ending).collect();
        let mut to_remove: Vec<(usize, &EmptyCatalogGroup)> = Vec::new();
        for group in &file_groups {
            let line_idx = group.line.saturating_sub(1) as usize;
            if line_idx >= lines.len() {
                summary.skipped += 1;
                fixes.push(skip_group_record(
                    group,
                    "line_out_of_range",
                    "Skipped: the reported line is past the end of pnpm-workspace.yaml; the file may have been edited since fallow check ran",
                    output,
                    relative_path,
                ));
                continue;
            }
            to_remove.push((line_idx, group));
        }

        if to_remove.is_empty() {
            continue;
        }

        to_remove.sort_by_key(|(line_idx, _)| std::cmp::Reverse(*line_idx));
        to_remove.dedup_by_key(|(line_idx, _)| *line_idx);

        if dry_run {
            for (line_idx, group) in &to_remove {
                if !matches!(output, OutputFormat::Json) {
                    eprintln!(
                        "Would remove empty catalog group from {}:{} `{}`",
                        relative_path.display(),
                        line_idx + 1,
                        group.catalog_name,
                    );
                }
                fixes.push(remove_group_record(group, *line_idx, false, relative_path));
            }
            summary.applied += to_remove.len();
            continue;
        }

        let mut new_lines: Vec<String> = lines.iter().map(ToString::to_string).collect();
        for (line_idx, _) in &to_remove {
            new_lines.remove(*line_idx);
        }

        let mut new_content = new_lines.join(meta.line_ending);
        if content.ends_with(meta.line_ending) && !new_content.ends_with(meta.line_ending) {
            new_content.push_str(meta.line_ending);
        }

        if serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&new_content).is_err() {
            summary.write_error = true;
            eprintln!(
                "Error: refusing to write {}: post-edit content failed YAML reparse. The file was not modified.",
                relative_path.display(),
            );
            continue;
        }

        plan.stage(
            absolute.clone(),
            super::io::bytes_with_optional_bom(new_content, &meta),
        );

        for (line_idx, group) in &to_remove {
            let mut record = remove_group_record(group, *line_idx, true, relative_path);
            record["__target"] = serde_json::json!(absolute.display().to_string());
            fixes.push(record);
        }
        summary.applied += to_remove.len();
    }

    summary
}

/// Output of `apply_catalog_entry_fixes` consumed by the orchestrator.
#[derive(Debug, Default)]
pub(super) struct CatalogFixSummary {
    pub applied: usize,
    pub skipped: usize,
    pub write_error: bool,
    /// Total leading-comment lines absorbed across all applied fixes.
    /// Surfaced in the human summary so users see that comments were
    /// removed alongside entries (`Fixed N issue(s) (+M comment lines)`).
    pub comment_lines_removed: usize,
}

/// Compute the deletion range `[start, end)` (line indices) for a catalog
/// entry whose key sits on `entry_idx`. Object-form entries
/// (`react:\n    specifier: ^18.2.0`) consume every subsequent line with
/// strictly greater indent. Blank lines and lines at the entry's own
/// indent (or shallower) stop the forward scan: blank lines are
/// conservatively treated as inter-entry whitespace that should be
/// preserved.
///
/// Depending on `preceding_comment_policy`, the range may also extend
/// backward to include a contiguous YAML comment block immediately above
/// the entry.
fn compute_deletion_range(
    lines: &[&str],
    entry_idx: usize,
    entry: &UnusedCatalogEntry,
    preceding_comment_policy: CatalogPrecedingCommentPolicy,
) -> std::ops::Range<usize> {
    let start_idx =
        comment_block_start(lines, entry_idx, entry, preceding_comment_policy).unwrap_or(entry_idx);
    let entry_indent = leading_spaces(lines[entry_idx]);
    let mut end_idx = entry_idx + 1;
    while end_idx < lines.len() {
        let line = lines[end_idx];
        if line.trim().is_empty() {
            break;
        }
        if leading_spaces(line) <= entry_indent {
            break;
        }
        end_idx += 1;
    }
    start_idx..end_idx
}

fn comment_block_start(
    lines: &[&str],
    entry_idx: usize,
    entry: &UnusedCatalogEntry,
    policy: CatalogPrecedingCommentPolicy,
) -> Option<usize> {
    if matches!(policy, CatalogPrecedingCommentPolicy::Never) || entry_idx == 0 {
        return None;
    }

    let entry_indent = leading_spaces(lines[entry_idx]);
    let mut comment_start = entry_idx;
    while comment_start > 0 && is_entry_comment(lines[comment_start - 1], entry_indent) {
        comment_start -= 1;
    }
    if comment_start == entry_idx {
        return None;
    }

    // Per-block escape hatch (`# fallow-keep`): any line in the block bearing
    // this marker preserves the entire block regardless of policy. Mirrors
    // fallow's existing `fallow-ignore-next-line` / `fallow-ignore-file`
    // inline-suppression convention so users discover it without docs.
    let block = &lines[comment_start..entry_idx];
    if block.iter().any(|line| line.contains("fallow-keep")) {
        return None;
    }

    match policy {
        CatalogPrecedingCommentPolicy::Always => Some(comment_start),
        CatalogPrecedingCommentPolicy::Never => None,
        CatalogPrecedingCommentPolicy::Auto => {
            // Section-banner heuristic: a comment line consisting of `#`
            // followed by 3+ repeated separator characters (`=`, `-`, `*`,
            // `_`, `~`, `+`, `#`) is treated as a curated banner that
            // semantically owns the following section, not the next entry.
            // Auto preserves the block when any line in it matches.
            if block.iter().any(|line| is_section_banner_line(line)) {
                return None;
            }
            let before_comment = comment_start.checked_sub(1)?;
            if lines[before_comment].trim().is_empty()
                || find_parent_header_line(lines, entry) == Some(before_comment)
            {
                Some(comment_start)
            } else {
                None
            }
        }
    }
}

fn is_entry_comment(line: &str, entry_indent: usize) -> bool {
    leading_spaces(line) == entry_indent && line.trim_start().starts_with('#')
}

/// Recognize banner-shaped comment lines like `# ====`, `# ----`, `# ====
/// React 18 pins ====`. Returns true when the comment body (after `#` and
/// optional leading whitespace) starts with 3+ repeats of `=`, `-`, `*`,
/// `_`, `~`, `+`, or `#`. Used by the Auto policy to preserve section
/// dividers above the next catalog entry.
fn is_section_banner_line(line: &str) -> bool {
    let Some(after_hash) = line.trim_start().strip_prefix('#') else {
        return false;
    };
    let body = after_hash.trim_start();
    let Some(first) = body.chars().next() else {
        return false;
    };
    if !matches!(first, '=' | '-' | '*' | '_' | '~' | '+' | '#') {
        return false;
    }
    body.chars().take(3).all(|c| c == first)
}

fn leading_spaces(line: &str) -> usize {
    line.bytes().take_while(|&b| b == b' ').count()
}

/// Detect a `---` YAML document separator on its own line. We don't try to
/// distinguish "leading directive divider" from "real document split"; any
/// `---` on its own line disqualifies the file from in-place line edits.
fn is_multi_document_yaml(content: &str) -> bool {
    content
        .lines()
        .any(|line| line.trim_end() == "---" || line.trim_end().starts_with("--- "))
}

/// Locate the line index of a catalog entry's parent header in the
/// PRE-deletion `lines` Vec. Returns:
/// - `Some(idx)` of the line containing `catalog:` for default-catalog entries
/// - `Some(idx)` of the line containing `<name>:` (indented under `catalogs:`)
///   for named-catalog entries
/// - `None` if no matching parent is found (the file shape diverges from
///   what the detector reported; the caller skips the rewrite step)
fn find_parent_header_line(lines: &[&str], entry: &UnusedCatalogEntry) -> Option<usize> {
    let entry_line_idx = entry.line.saturating_sub(1) as usize;
    if entry_line_idx >= lines.len() {
        return None;
    }
    let entry_indent = leading_spaces(lines[entry_line_idx]);

    // Walk backwards from the entry line to find the first line at
    // strictly lower indent. For default-catalog entries the parent
    // must start with `catalog:`; for named-catalog entries the parent
    // is the `<name>:` line at an intermediate indent under `catalogs:`.
    for idx in (0..entry_line_idx).rev() {
        let line = lines[idx];
        let stripped = line.trim_end();
        let content = stripped.trim_start();
        if content.is_empty() || content.starts_with('#') {
            continue;
        }
        let indent = leading_spaces(stripped);
        if indent >= entry_indent {
            continue;
        }
        if entry.catalog_name == "default" {
            return content.starts_with("catalog:").then_some(idx);
        }
        // Strip leading quotes for quoted-key catalog names.
        let key = content
            .trim_start_matches(['"', '\''])
            .split([':', '"', '\''])
            .next()
            .unwrap_or("");
        return (key == entry.catalog_name).then_some(idx);
    }
    None
}

/// Rewrite parent catalog headers whose only children were just deleted.
///
/// pnpm rejects null-valued catalogs (`catalogs:\n  react17:\n` parses
/// as `{'catalogs': {'react17': None}}`) with
/// `Cannot convert undefined or null to object` at install time. When
/// we empty a catalog group via `apply_catalog_entry_fixes`, rewrite
/// the header from `react17:` to `react17: {}` so the file stays
/// installable. Verified against pnpm 10.33.4.
///
/// `parent_indices` are line indices into the PRE-deletion `lines` Vec.
/// `deleted_ranges` are the ranges that were drained from that Vec.
/// Both are translated into POST-deletion `new_lines` coordinates by
/// subtracting the number of deleted lines preceding each anchor.
fn rewrite_empty_catalog_parents(
    new_lines: &mut [String],
    parent_indices: &[usize],
    deleted_ranges: &[(std::ops::Range<usize>, &UnusedCatalogEntry)],
) {
    // Dedup parents and map their pre-deletion indices into post-deletion
    // indices. A parent header line itself is NEVER inside a deletion
    // range (deletions cover entry lines plus their multi-line children,
    // which all sit BELOW the parent), so the mapping is simply
    // `new_idx = pre_idx - (lines deleted strictly before pre_idx)`.
    let mut unique_parents: Vec<usize> = parent_indices.to_vec();
    unique_parents.sort_unstable();
    unique_parents.dedup();

    for parent_pre_idx in unique_parents {
        let deleted_before: usize = deleted_ranges
            .iter()
            .map(|(range, _)| {
                if range.end <= parent_pre_idx {
                    range.end - range.start
                } else if range.start <= parent_pre_idx {
                    // Parent inside a deletion range is impossible by
                    // construction (deletions start at entry lines, which
                    // are strictly below the parent). Skip defensively.
                    0
                } else {
                    0
                }
            })
            .sum();
        let new_idx = parent_pre_idx.saturating_sub(deleted_before);
        if new_idx >= new_lines.len() {
            continue;
        }
        if has_remaining_children(new_lines, new_idx) {
            continue;
        }
        // Append ` {}` to the header line, preserving any trailing
        // whitespace / line ending semantics. `new_lines` was produced
        // by `content.split(line_ending)`, so trailing whitespace is
        // already trimmed and the line ending is added back on join.
        let original = new_lines[new_idx].clone();
        let trimmed_end = original.trim_end();
        let trailing = &original[trimmed_end.len()..];
        new_lines[new_idx] = format!("{trimmed_end} {{}}{trailing}");
    }
}

/// Return true if `parent_idx` in `lines` is followed by at least one
/// child line (indent strictly greater than the parent's). Comments and
/// blank lines are skipped; a sibling-or-shallower non-blank line means
/// the parent has no children.
fn has_remaining_children(lines: &[String], parent_idx: usize) -> bool {
    let parent_indent = leading_spaces(&lines[parent_idx]);
    for line in lines.iter().skip(parent_idx + 1) {
        let stripped = line.trim_end();
        let content = stripped.trim_start();
        if content.is_empty() || content.starts_with('#') {
            continue;
        }
        let indent = leading_spaces(stripped);
        return indent > parent_indent;
    }
    false
}

fn skip_record(
    entry: &UnusedCatalogEntry,
    skip_reason: &str,
    description: &str,
    output: OutputFormat,
    relative_path: &Path,
) -> serde_json::Value {
    if !matches!(output, OutputFormat::Json) {
        eprintln!(
            "Skipped catalog entry {}:{} `{}` ({skip_reason})",
            relative_path.display(),
            entry.line,
            entry.entry_name,
        );
    }
    let consumers: Option<serde_json::Value> =
        if skip_reason == "hardcoded_consumers" && !entry.hardcoded_consumers.is_empty() {
            Some(serde_json::Value::Array(
                entry
                    .hardcoded_consumers
                    .iter()
                    .map(|p| {
                        // Normalize separators to match the check-side
                        // `hardcoded_consumers` shape (which uses
                        // `serde_path::serialize_vec` doing `.replace('\\', "/")`)
                        // so agents correlating check + fix output see the
                        // same path strings on Windows.
                        serde_json::Value::String(p.to_string_lossy().replace('\\', "/"))
                    })
                    .collect(),
            ))
        } else {
            None
        };
    let mut value = serde_json::json!({
        "type": "remove_catalog_entry",
        "entry_name": entry.entry_name,
        "catalog_name": entry.catalog_name,
        "file": relative_path.to_string_lossy().replace('\\', "/"),
        "line": entry.line,
        "applied": false,
        "skipped": true,
        "skip_reason": skip_reason,
        "description": description,
    });
    if let Some(consumers) = consumers
        && let serde_json::Value::Object(map) = &mut value
    {
        map.insert("consumers".to_string(), consumers);
    }
    value
}

fn remove_record(
    entry: &UnusedCatalogEntry,
    range: &std::ops::Range<usize>,
    applied: bool,
    relative_path: &Path,
) -> serde_json::Value {
    let removed_lines = range.end - range.start;
    let mut value = serde_json::json!({
        "type": "remove_catalog_entry",
        "entry_name": entry.entry_name,
        "catalog_name": entry.catalog_name,
        "file": relative_path.to_string_lossy().replace('\\', "/"),
        // `line` is the first deleted line (the leading comment block when
        // `fix.catalog.deletePrecedingComments` absorbs one). `entry_line`
        // is the catalog entry's original line so consumers that keyed on
        // the entry position (CI annotators, dedup caches) keep a stable
        // anchor. Both are 1-based.
        "line": range.start + 1,
        "entry_line": entry.line,
        "removed_lines": removed_lines,
    });
    if applied && let serde_json::Value::Object(map) = &mut value {
        map.insert("applied".to_string(), serde_json::Value::Bool(true));
    }
    value
}

fn skip_group_record(
    group: &EmptyCatalogGroup,
    skip_reason: &str,
    description: &str,
    output: OutputFormat,
    relative_path: &Path,
) -> serde_json::Value {
    if !matches!(output, OutputFormat::Json) {
        eprintln!(
            "Skipped empty catalog group {}:{} `{}` ({skip_reason})",
            relative_path.display(),
            group.line,
            group.catalog_name,
        );
    }
    serde_json::json!({
        "type": "remove_empty_catalog_group",
        "catalog_name": group.catalog_name,
        "file": relative_path.to_string_lossy().replace('\\', "/"),
        "line": group.line,
        "applied": false,
        "skipped": true,
        "skip_reason": skip_reason,
        "description": description,
    })
}

fn remove_group_record(
    group: &EmptyCatalogGroup,
    line_idx: usize,
    applied: bool,
    relative_path: &Path,
) -> serde_json::Value {
    let mut value = serde_json::json!({
        "type": "remove_empty_catalog_group",
        "catalog_name": group.catalog_name,
        "file": relative_path.to_string_lossy().replace('\\', "/"),
        "line": line_idx + 1,
        "removed_lines": 1,
    });
    if applied && let serde_json::Value::Object(map) = &mut value {
        map.insert("applied".to_string(), serde_json::Value::Bool(true));
    }
    value
}

fn format_consumer_summary(consumers: &[std::path::PathBuf]) -> String {
    match consumers.len() {
        0 => String::new(),
        1 => format!("`{}`", consumers[0].display()),
        2 => format!(
            "`{}` and `{}`",
            consumers[0].display(),
            consumers[1].display()
        ),
        _ => format!(
            "`{}` and {} other consumer(s)",
            consumers[0].display(),
            consumers.len() - 1,
        ),
    }
}

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

    fn make_entry(name: &str, catalog: &str, line: u32) -> UnusedCatalogEntryFinding {
        UnusedCatalogEntryFinding::with_actions(UnusedCatalogEntry {
            entry_name: name.to_string(),
            catalog_name: catalog.to_string(),
            path: PathBuf::from("pnpm-workspace.yaml"),
            line,
            hardcoded_consumers: vec![],
        })
    }

    fn make_entry_with_consumers(
        name: &str,
        catalog: &str,
        line: u32,
        consumers: Vec<PathBuf>,
    ) -> UnusedCatalogEntryFinding {
        UnusedCatalogEntryFinding::with_actions(UnusedCatalogEntry {
            entry_name: name.to_string(),
            catalog_name: catalog.to_string(),
            path: PathBuf::from("pnpm-workspace.yaml"),
            line,
            hardcoded_consumers: consumers,
        })
    }

    fn make_group(name: &str, line: u32) -> EmptyCatalogGroupFinding {
        EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
            catalog_name: name.to_string(),
            path: PathBuf::from("pnpm-workspace.yaml"),
            line,
        })
    }

    fn seed_workspace_file(root: &Path, content: &str) {
        let path = root.join("pnpm-workspace.yaml");
        std::fs::write(&path, content).unwrap();
    }

    /// Thin wrappers preserving the pre-#454 test API surface: build a
    /// FixPlan + CapturedHashes around the entry-fix / group-fix call
    /// and commit. Commit failures fold into `summary.write_error` so
    /// pre-existing tests that assert on that field keep working.
    fn run_catalog_entry_fix(
        root: &Path,
        entries: &[UnusedCatalogEntryFinding],
        policy: CatalogPrecedingCommentPolicy,
        output: OutputFormat,
        dry_run: bool,
        fixes: &mut Vec<serde_json::Value>,
    ) -> CatalogFixSummary {
        let mut plan = FixPlan::new();
        let hashes = CapturedHashes::default();
        let mut summary = apply_catalog_entry_fixes(
            root, entries, policy, &hashes, &mut plan, output, dry_run, fixes,
        );
        if !dry_run && !plan.commit().failed.is_empty() {
            summary.write_error = true;
        }
        summary
    }

    fn run_empty_catalog_group_fix(
        root: &Path,
        groups: &[EmptyCatalogGroupFinding],
        output: OutputFormat,
        dry_run: bool,
        fixes: &mut Vec<serde_json::Value>,
    ) -> CatalogFixSummary {
        let mut plan = FixPlan::new();
        let hashes = CapturedHashes::default();
        let mut summary = apply_empty_catalog_group_fixes(
            root, groups, &hashes, &mut plan, output, dry_run, fixes,
        );
        if !dry_run && !plan.commit().failed.is_empty() {
            summary.write_error = true;
        }
        summary
    }

    #[test]
    fn removes_empty_named_catalog_group_header_only() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalogs:\n  react17: {}\n  # keep this note\n  vue3:\n    vue: ^3.4.0\n";
        seed_workspace_file(dir.path(), content);
        let groups = vec![make_group("react17", 2)];
        let mut fixes = Vec::new();

        let summary =
            run_empty_catalog_group_fix(dir.path(), &groups, OutputFormat::Json, false, &mut fixes);

        assert!(!summary.write_error);
        assert_eq!(summary.applied, 1);
        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(
            result,
            "catalogs:\n  # keep this note\n  vue3:\n    vue: ^3.4.0\n"
        );
        assert_eq!(fixes[0]["type"], "remove_empty_catalog_group");
        assert_eq!(fixes[0]["applied"], true);
    }

    #[test]
    fn removes_scalar_form_entry() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0\n  is-even: ^1.0.0\n  left-pad: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        assert_eq!(summary.applied, 1);
        assert_eq!(summary.skipped, 0);
        assert!(!summary.write_error);

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n  left-pad: ^1.0.0\n");
        assert_eq!(fixes.len(), 1);
        assert_eq!(fixes[0]["applied"], serde_json::json!(true));
        assert_eq!(fixes[0]["removed_lines"], serde_json::json!(1));
    }

    #[test]
    fn removes_object_form_entry_with_nested_keys() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0\n  react:\n    specifier: ^18.2.0\n    publishConfig:\n      access: public\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("react", "default", 3)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        assert_eq!(summary.applied, 1);
        assert_eq!(summary.skipped, 0);

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n  is-even: ^1.0.0\n");
        assert_eq!(fixes[0]["removed_lines"], serde_json::json!(4));
    }

    #[test]
    fn skips_entries_with_hardcoded_consumers() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry_with_consumers(
            "is-even",
            "default",
            2,
            vec![PathBuf::from("apps/web/package.json")],
        )];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        assert_eq!(summary.applied, 0);
        assert_eq!(summary.skipped, 1);

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, content, "file must not be modified when skipping");

        assert_eq!(fixes.len(), 1);
        assert_eq!(fixes[0]["skipped"], serde_json::json!(true));
        assert_eq!(
            fixes[0]["skip_reason"],
            serde_json::json!("hardcoded_consumers")
        );
        assert!(
            fixes[0]["description"]
                .as_str()
                .unwrap()
                .contains("apps/web/package.json")
        );
        assert!(fixes[0]["consumers"].is_array());
    }

    #[test]
    fn dry_run_does_not_modify_file() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 2)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            true,
            &mut fixes,
        );

        assert_eq!(summary.applied, 1);
        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, content);
        assert_eq!(fixes[0].get("applied"), None);
    }

    #[test]
    fn removes_named_catalog_entry() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalogs:\n  react17:\n    react: ^17.0.2\n    react-dom: ^17.0.2\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("react", "react17", 3)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        assert_eq!(summary.applied, 1);
        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalogs:\n  react17:\n    react-dom: ^17.0.2\n");
    }

    #[test]
    fn preserves_trailing_inline_comment_on_sibling() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0 # keep me\n  is-even: ^1.0.0 # remove me\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0 # keep me\n");
    }

    #[test]
    fn auto_deletes_leading_comment_after_parent_header() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  # mention is-even\n  is-even: ^1.0.0\n  is-odd: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n");
        assert_eq!(fixes[0]["line"], serde_json::json!(2));
        assert_eq!(fixes[0]["entry_line"], serde_json::json!(3));
        assert_eq!(fixes[0]["removed_lines"], serde_json::json!(2));
        assert_eq!(summary.comment_lines_removed, 1);
    }

    #[test]
    fn auto_preserves_block_with_fallow_keep_marker() {
        // `# fallow-keep` on any line in the contiguous comment block
        // protects the entire block from deletion regardless of policy.
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  # fallow-keep: audit trail for CVE-2024-XXXX\n  is-even: ^1.0.0\n  is-odd: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(
            result,
            "catalog:\n  # fallow-keep: audit trail for CVE-2024-XXXX\n  is-odd: ^1.0.0\n"
        );
        assert_eq!(summary.comment_lines_removed, 0);
    }

    #[test]
    fn always_preserves_block_with_fallow_keep_marker() {
        // `# fallow-keep` is a per-block escape hatch that overrides even
        // the `always` policy. The marker is the user's explicit intent
        // to keep this specific block.
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  # fallow-keep\n  is-even: ^1.0.0\n  is-odd: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Always,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  # fallow-keep\n  is-odd: ^1.0.0\n");
    }

    #[test]
    fn auto_preserves_section_banner_block() {
        // Section-banner comments (`# === React 18 production pins ===`,
        // `# ----`, etc.) semantically own the following section, not
        // the next entry. Auto must NOT delete them even when sitting
        // directly under the parent header.
        let dir = tempfile::tempdir().unwrap();
        let content =
            "catalog:\n  # === React 18 production pins ===\n  is-even: ^1.0.0\n  is-odd: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(
            result,
            "catalog:\n  # === React 18 production pins ===\n  is-odd: ^1.0.0\n"
        );
        assert_eq!(summary.comment_lines_removed, 0);
    }

    #[test]
    fn always_deletes_section_banner_block() {
        // The `always` policy still deletes banner-shaped blocks. The
        // banner heuristic is an Auto-only refinement; users who opt
        // into `always` get aggressive deletion. To protect a banner
        // under `always`, add a `# fallow-keep` marker.
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  # ====\n  is-even: ^1.0.0\n  is-odd: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Always,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n");
    }

    #[test]
    fn section_banner_detector_recognizes_separator_runs() {
        assert!(is_section_banner_line("# === banner ==="));
        assert!(is_section_banner_line("  # ----"));
        assert!(is_section_banner_line("# ***"));
        assert!(is_section_banner_line("# ___"));
        assert!(is_section_banner_line("#==="));
        assert!(!is_section_banner_line("# mention is-even"));
        assert!(!is_section_banner_line("# = single sep"));
        assert!(!is_section_banner_line("# -- two seps only"));
        assert!(!is_section_banner_line("not a comment"));
    }

    #[test]
    fn auto_deletes_leading_comment_after_blank_separator() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0\n\n  # mention is-even\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 5)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n\n");
    }

    #[test]
    fn auto_preserves_leading_comment_after_sibling_entry() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0\n  # shared note\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 4)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n  # shared note\n");
    }

    #[test]
    fn auto_deletes_named_catalog_leading_comment_after_named_header() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalogs:\n  react17:\n    # pinned for old peer deps\n    react: ^17.0.2\n    react-dom: ^17.0.2\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("react", "react17", 4)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalogs:\n  react17:\n    react-dom: ^17.0.2\n");
    }

    #[test]
    fn always_deletes_leading_comment_after_sibling_entry() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0\n  # force remove\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 4)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Always,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n");
    }

    #[test]
    fn never_preserves_leading_comment_after_parent_header() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  # keep always\n  is-even: ^1.0.0\n  is-odd: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Never,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  # keep always\n  is-odd: ^1.0.0\n");
    }

    #[test]
    fn removes_multiple_adjacent_entries_in_one_pass() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0\n  is-even: ^1.0.0\n  left-pad: ^1.0.0\n  right-pad: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![
            make_entry("is-even", "default", 3),
            make_entry("left-pad", "default", 4),
        ];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        assert_eq!(summary.applied, 2);
        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n  right-pad: ^1.0.0\n");
    }

    #[test]
    fn rejects_multi_document_yaml() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-even: ^1.0.0\n---\nfoo: bar\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 2)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        assert_eq!(summary.applied, 0);
        assert_eq!(summary.skipped, 1);
        assert_eq!(
            fixes[0]["skip_reason"],
            serde_json::json!("multi_document_yaml")
        );

        // File must not have been modified.
        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, content);
    }

    #[test]
    fn skips_when_line_out_of_range() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        // line 99 is way past EOF (file has 3 lines including trailing newline)
        let entries = vec![make_entry("is-even", "default", 99)];
        let mut fixes = Vec::new();
        let summary = run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        assert_eq!(summary.applied, 0);
        assert_eq!(summary.skipped, 1);
        assert_eq!(
            fixes[0]["skip_reason"],
            serde_json::json!("line_out_of_range")
        );
    }

    #[test]
    fn preserves_crlf_line_endings() {
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\r\n  is-odd: ^1.0.0\r\n  is-even: ^1.0.0\r\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\r\n  is-odd: ^1.0.0\r\n");
    }

    #[test]
    fn rewrites_emptied_default_catalog_to_empty_map() {
        // Regression: pnpm rejects `catalog:\n` (null value) with
        // "Cannot convert undefined or null to object". When the fix
        // empties the default catalog, the header must be rewritten to
        // `catalog: {}` so the file stays installable.
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 2)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog: {}\n");
        let parsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&result).unwrap();
        assert!(
            parsed
                .get("catalog")
                .and_then(serde_yaml_ng::Value::as_mapping)
                .is_some_and(serde_yaml_ng::Mapping::is_empty),
            "catalog must be `{{}}`, not null"
        );
    }

    #[test]
    fn rewrites_emptied_named_catalog_to_empty_map() {
        // Regression: same as above for named catalogs. Reproduces the
        // issue-329 fixture's `react17` group after removing both its
        // entries.
        let dir = tempfile::tempdir().unwrap();
        let content = "catalogs:\n  react17:\n    react: ^17.0.2\n    react-dom: ^17.0.2\n  legacy:\n    is-odd: ^3.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![
            make_entry("react", "react17", 3),
            make_entry("react-dom", "react17", 4),
        ];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(
            result,
            "catalogs:\n  react17: {}\n  legacy:\n    is-odd: ^3.0.0\n",
        );
        let parsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&result).unwrap();
        let react17 = parsed.get("catalogs").and_then(|c| c.get("react17"));
        assert!(
            react17
                .and_then(serde_yaml_ng::Value::as_mapping)
                .is_some_and(serde_yaml_ng::Mapping::is_empty),
            "react17 must be `{{}}`, not null. Got: {react17:?}"
        );
    }

    #[test]
    fn preserves_non_empty_sibling_named_catalogs() {
        // When one named catalog is emptied but a sibling stays populated,
        // only the emptied one gets the `{}` rewrite.
        let dir = tempfile::tempdir().unwrap();
        let content = "catalogs:\n  react17:\n    react: ^17.0.2\n  vue3:\n    vue: ^3.4.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("react", "react17", 3)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(
            result,
            "catalogs:\n  react17: {}\n  vue3:\n    vue: ^3.4.0\n"
        );
    }

    #[test]
    fn leaves_partially_populated_catalog_alone() {
        // When only some entries of a catalog are removed and siblings
        // remain, no `{}` rewrite is needed.
        let dir = tempfile::tempdir().unwrap();
        let content = "catalog:\n  is-odd: ^1.0.0\n  is-even: ^1.0.0\n";
        seed_workspace_file(dir.path(), content);

        let entries = vec![make_entry("is-even", "default", 3)];
        let mut fixes = Vec::new();
        run_catalog_entry_fix(
            dir.path(),
            &entries,
            CatalogPrecedingCommentPolicy::Auto,
            OutputFormat::Json,
            false,
            &mut fixes,
        );

        let result = std::fs::read_to_string(dir.path().join("pnpm-workspace.yaml")).unwrap();
        assert_eq!(result, "catalog:\n  is-odd: ^1.0.0\n");
    }

    // -- compute_deletion_range unit tests ----------------------------------

    #[test]
    fn deletion_range_scalar_form_spans_one_line() {
        let lines: Vec<&str> = "catalog:\n  is-even: ^1.0.0\n  is-odd: ^1.0.0\n"
            .split('\n')
            .collect();
        let entry = make_entry("is-even", "default", 2).entry;
        let range = compute_deletion_range(&lines, 1, &entry, CatalogPrecedingCommentPolicy::Auto);
        assert_eq!(range, 1..2);
    }

    #[test]
    fn deletion_range_object_form_spans_until_indent_drops() {
        let content = "catalog:\n  react:\n    specifier: ^18.2.0\n    publishConfig: {}\n  is-even: ^1.0.0\n";
        let lines: Vec<&str> = content.split('\n').collect();
        let entry = make_entry("react", "default", 2).entry;
        let range = compute_deletion_range(&lines, 1, &entry, CatalogPrecedingCommentPolicy::Auto);
        assert_eq!(range, 1..4);
    }

    #[test]
    fn deletion_range_stops_at_blank_line() {
        let content = "catalog:\n  is-even: ^1.0.0\n\n  is-odd: ^1.0.0\n";
        let lines: Vec<&str> = content.split('\n').collect();
        let entry = make_entry("is-even", "default", 2).entry;
        let range = compute_deletion_range(&lines, 1, &entry, CatalogPrecedingCommentPolicy::Auto);
        assert_eq!(range, 1..2);
    }

    #[test]
    fn is_multi_document_detects_separator() {
        assert!(is_multi_document_yaml("foo: bar\n---\nbaz: qux\n"));
        assert!(is_multi_document_yaml("---\nfoo: bar\n"));
        assert!(!is_multi_document_yaml("catalog:\n  is-even: ^1.0.0\n"));
        // A `---` inside a quoted value or as a substring is not a separator.
        assert!(!is_multi_document_yaml("catalog:\n  foo: \"---\"\n"));
    }
}