cargo-cleanme 0.2.8

Safely clean inactive Cargo build artifacts through Cargo
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
use cargo_cleanme::{
    cli::{
        self, CleanupRequest, CleanupScope, Cli, ConfigCommand, Invocation, OutputFormat,
        ScanIntent,
    },
    config::{self, ConfigPathResolver},
    domain::ScanScope,
    error::AppError,
};
use std::collections::BTreeMap;
fn main() {
    // clap prints its own message and exits on a usage error, so parsing here
    // rather than inside `run` is what lets a fatal error know the output
    // format: log mode has to report it as one bounded line, not as prose.
    let cli = Cli::parse_normalized();
    // Captured before the move so a fatal error can still name the operation.
    let invocation = cli.invocation();
    let format = cli.format;
    match run(cli) {
        Ok(code) => std::process::exit(code),
        Err(e) => {
            if format == OutputFormat::Log {
                // No report exists yet, so there is no summary line to write;
                // this is the single bounded stderr diagnostic instead. It
                // carries a typed code and no text: a retained history pane has
                // no use for a path or a Cargo error.
                eprintln!(
                    "{}",
                    cargo_cleanme::output::log::fatal(operation_name(&invocation), error_code(&e))
                );
            } else {
                eprintln!("cargo-cleanme: {e}");
            }
            std::process::exit(2)
        }
    }
}

/// Stable `op=` value for an invocation, for the one line log mode writes when
/// an operation fails before producing a report.
fn operation_name(invocation: &Invocation) -> &'static str {
    match invocation {
        Invocation::Cleanup(_) => "clean",
        Invocation::Scan(_) => "scan",
        Invocation::Config(_) => "config",
        Invocation::Update { .. } => "update",
        // Unreachable through `clap`, so no consumer can observe this value.
        Invocation::UsageError(_) => "usage",
    }
}

/// Stable `reason=` code for a fatal error. The prose stays in the human path;
/// this exists so an unattended log can be grepped and alerted on.
fn error_code(error: &AppError) -> &'static str {
    match error {
        AppError::Config(_) | AppError::InvalidRoot { .. } => "config",
        AppError::Io(_) => "io",
        AppError::Scan(_) => "scan",
        AppError::Provenance(_) => "provenance",
        AppError::Update(_) => "update",
    }
}
/// Process-wide output options that apply to every report-producing operation.
#[derive(Clone, Copy, Debug)]
struct RunOptions {
    no_progress: bool,
    stats: bool,
    format: OutputFormat,
}
fn run(cli: Cli) -> Result<i32, AppError> {
    let path = ConfigPathResolver::new(cli.config.clone()).path()?;
    let options = RunOptions {
        no_progress: cli.no_progress,
        stats: cli.stats,
        format: cli.format,
    };
    // One resolved intent per invocation. Bare maintenance, `clean ROOT`,
    // `clean --known`, and `clean --full` all arrive as a CleanupRequest, so
    // they cannot reach different proof, policy, or reporting paths.
    match cli.invocation() {
        Invocation::Update { dry_run } => run_update(dry_run, options.format),
        Invocation::Config(command) => run_config(command, &path, options.format),
        Invocation::Scan(intent) => {
            run_scan(intent, &path, options, EmitReport::Yes).map(|outcome| outcome.code)
        }
        Invocation::Cleanup(request) => run_cleanup(request, &path, options),
        // Unreachable through `clap` (see `Invocation::UsageError`). Reported as
        // a usage error (exit 2) rather than guessing an operation.
        Invocation::UsageError(message) => Err(AppError::Config(message)),
    }
}

fn run_update(dry_run: bool, format: OutputFormat) -> Result<i32, AppError> {
    let plan = match cargo_cleanme::update::update(dry_run) {
        Ok(plan) => plan,
        // "Already at latest" is success with nothing to do (exit 0), not a
        // usage error (exit 2): schedulers must not alert on it. The JSON
        // branch still emits exactly one document with `changed:false`.
        // The two variants are matched separately (not by string equality on
        // the versions) so `01.02.03`-style spellings still report the exact
        // variant the version comparison produced.
        Err(cargo_cleanme::update::UpdateError::AlreadyCurrent { current, published }) => {
            if format == OutputFormat::Json {
                let target = cargo_cleanme::update::host_target().unwrap_or("unknown");
                let asset = cargo_cleanme::update::asset_for_target(target).unwrap_or("");
                let provenance = std::env::current_exe()
                    .ok()
                    .map(|exe| cargo_cleanme::update::classify_provenance(&exe).code())
                    .unwrap_or("unprovable_ownership");
                let document = serde_json::json!({
                    "schema_version": 1,
                    "cargo_cleanme_version": env!("CARGO_PKG_VERSION"),
                    "operation": "update",
                    "dry_run": dry_run,
                    "result": {
                        "from_version": current,
                        "to_version": published,
                        "target": target,
                        "asset": asset,
                        "tag": format!("v{published}"),
                        "provenance": provenance,
                        "changed": false,
                    }
                });
                println!("{document}");
            } else if format == OutputFormat::Log {
                println!(
                    "{}",
                    cargo_cleanme::output::log::update(
                        &current,
                        &published,
                        cargo_cleanme::update::host_target().unwrap_or("unknown"),
                        true,
                    )
                );
            } else {
                println!(
                    "cargo-cleanme: already at the latest stable version ({current}; published is {published})"
                );
            }
            return Ok(0);
        }
        Err(cargo_cleanme::update::UpdateError::NewerThanPublished { current, published }) => {
            if format == OutputFormat::Json {
                let target = cargo_cleanme::update::host_target().unwrap_or("unknown");
                let asset = cargo_cleanme::update::asset_for_target(target).unwrap_or("");
                let provenance = std::env::current_exe()
                    .ok()
                    .map(|exe| cargo_cleanme::update::classify_provenance(&exe).code())
                    .unwrap_or("unprovable_ownership");
                let document = serde_json::json!({
                    "schema_version": 1,
                    "cargo_cleanme_version": env!("CARGO_PKG_VERSION"),
                    "operation": "update",
                    "dry_run": dry_run,
                    "result": {
                        "from_version": current,
                        "to_version": published,
                        "target": target,
                        "asset": asset,
                        "tag": format!("v{published}"),
                        "provenance": provenance,
                        "changed": false,
                    }
                });
                println!("{document}");
            } else if format == OutputFormat::Log {
                println!(
                    "{}",
                    cargo_cleanme::output::log::update(
                        &current,
                        &published,
                        cargo_cleanme::update::host_target().unwrap_or("unknown"),
                        true,
                    )
                );
            } else {
                println!(
                    "cargo-cleanme: this build ({current}) is newer than the published release ({published}); refusing to downgrade it"
                );
            }
            return Ok(0);
        }
        Err(other) => return Err(other.into()),
    };
    if format == OutputFormat::Json {
        // The stream, trailing newline included, comes from the library seam the
        // contract tests drive, so "one JSON document on stdout" is a property
        // this function holds rather than a convention it happens to follow.
        print!(
            "{}",
            cargo_cleanme::output::update_json_stream(&plan, dry_run)
        );
    } else if format == OutputFormat::Log {
        // One bounded line, never the human paragraphs below: a scheduler
        // tailing this stream gets `key=value` for every `op` the log format
        // documents, not prose.
        println!(
            "{}",
            cargo_cleanme::output::log::update(
                &plan.from_version,
                &plan.to_version,
                &plan.target,
                dry_run,
            )
        );
    } else if dry_run {
        println!(
            "cargo-cleanme: {} -> {} available for {}",
            plan.from_version, plan.to_version, plan.target
        );
        println!("  release: {}", plan.tag);
        println!("  asset:   {}", plan.asset);
        println!("  install: not changed (--dry-run)");
    } else {
        println!("cargo-cleanme: updated to {}", plan.to_version);
    }
    Ok(0)
}

fn run_config(
    command: ConfigCommand,
    path: &std::path::Path,
    format: OutputFormat,
) -> Result<i32, AppError> {
    // `config` has no JSON envelope: `path`/`show` are a raw path and TOML
    // text. Emitting those on a `--format json` stdout would break the
    // one-JSON-document automation contract, so reject loudly (exit 2) rather
    // than emitting non-JSON.
    if format == OutputFormat::Json {
        return Err(AppError::Config(
            "config command does not support --format json; use human or log output".into(),
        ));
    }
    // `--format log` promises exactly one ASCII key=value line and no paths or
    // config text. `config path` and `config show` are nothing *but* a path and
    // config text, so in that format they report the action and leave their
    // content to the human output.
    let log = format == OutputFormat::Log;
    match command {
        ConfigCommand::Path => {
            if log {
                println!("{}", cargo_cleanme::output::log::config("path"));
            } else {
                println!("{}", path.display());
            }
        }
        ConfigCommand::Show => {
            let shown = config::show(&config::load_or_create(path)?)?;
            if log {
                println!("{}", cargo_cleanme::output::log::config("show"));
            } else {
                println!("{shown}");
            }
        }
        ConfigCommand::Edit => {
            config::ensure_exists(path)?;
            let (program, args) =
                cargo_cleanme::editor::resolve_editor().map_err(AppError::Config)?;
            let status = std::process::Command::new(&program)
                .args(args)
                .arg(path)
                .status()
                .map_err(|e| {
                    AppError::Config(format!("cannot launch editor {}: {e}", program.display()))
                })?;
            if !status.success() {
                eprintln!(
                    "cargo-cleanme: editor exited with {status}; config was not reverted: {}",
                    path.display()
                );
                // The exit contract is 0/1/2: an editor's arbitrary status
                // is reported in prose above, never propagated as our code.
                return Ok(1);
            }
            if !path.exists() {
                // `load` treats an absent file as "all defaults", so a
                // deleted config would silently reset every policy.
                return Err(AppError::Config(format!(
                    "editor removed the config file {}; refusing to treat that as an edit to defaults",
                    path.display()
                )));
            }
            config::load(path).map_err(|e| {
                AppError::Config(format!("edited config {} is invalid: {e}", path.display()))
            })?;
            if log {
                println!("{}", cargo_cleanme::output::log::config("edit"));
            } else {
                println!("edited {}", path.display());
            }
        }
    }
    Ok(0)
}

/// The roots a resolved cleanup intent operates on, plus the machine scope
/// label describing what was actually resolved.
///
/// Admission is provenance-aware (C028): `roots` holds only admitted
/// automatic roots plus strict explicit roots, collapsed after admission so an
/// invalid identity can never be hidden by canonicalization. `omitted_paths`
/// remembers safely omitted automatic roots for the late pre-spawn recheck;
/// `blocked` carries a whole-scope safety block when an automatic root is a
/// symlink or indeterminately unreadable, in which case no cleanup runs.
struct ResolvedCleanup {
    roots: Vec<std::path::PathBuf>,
    scope_label: &'static str,
    state_generation: Option<u64>,
    omitted_diagnostics: Vec<String>,
    omitted: Vec<cargo_cleanme::policy::AutomaticOmission>,
    blocked: Option<cargo_cleanme::cleanup::ScopeBlock>,
    /// True for Routine/Full scopes whose roots are automatic hints; false
    /// for explicit scopes where every defect stays a fatal usage error.
    automatic: bool,
}

fn run_cleanup(
    request: CleanupRequest,
    config_path: &std::path::Path,
    options: RunOptions,
) -> Result<i32, AppError> {
    let config = config::load_or_create(config_path)?;
    let mode = request.mode;
    let resolved = resolve_cleanup_roots(&request.scope, config_path, &config, options)?;
    let configured = &config.cleanup.policy;
    let overrides = &request.overrides;
    let policy = cargo_cleanme::cleanup::CleanupPolicy {
        min_reclaimable_bytes: overrides
            .min_reclaimable_bytes
            .unwrap_or(configured.min_reclaimable_bytes),
        min_inactive_seconds: overrides.older_than.or(configured.min_inactive_seconds),
        include: if overrides.include.is_empty() {
            configured.include.clone()
        } else {
            overrides.include.clone()
        },
        exclude: if overrides.exclude.is_empty() {
            configured.exclude.clone()
        } else {
            overrides.exclude.clone()
        },
    };
    let selector = overrides
        .profile
        .clone()
        .map(cargo_cleanme::cleanup::CleanupSelector::Profile)
        .or_else(|| {
            overrides
                .package
                .clone()
                .map(cargo_cleanme::cleanup::CleanupSelector::Package)
        });
    // Bounded, deterministic stderr notes for safely omitted automatic roots.
    // Human mode may name paths; log mode carries only the count in its one
    // line, so paths never reach a retained history pane.
    if !resolved.omitted_diagnostics.is_empty() && options.format != OutputFormat::Log {
        for diagnostic in &resolved.omitted_diagnostics {
            eprintln!("cargo-cleanme: {diagnostic}");
        }
    }
    if let Some(block) = resolved.blocked.clone() {
        // An automatic root is a symlink or indeterminately unreadable:
        // omission could conceal an expected scan tree, so nothing is
        // traversed and no Cargo process runs in any mode. This is a typed
        // whole-scope block (exit 1), never a fatal usage error.
        let report = cargo_cleanme::cleanup::CleanReport {
            results: Vec::new(),
            diagnostics: resolved.omitted.len(),
            failed: 0,
            mode,
            counters: Default::default(),
            scope_blocked: Some(block),
            unresolved_ownership: Vec::new(),
            selected_roots: resolved.roots.clone(),
            discovered_manifests: 0,
            resolved_workspaces: 0,
            units_considered: 0,
            effective_policy: Some(policy),
            selector,
        };
        emit_cleanup(&report, &resolved, &resolved.roots, options, "")?;
        return Ok(1);
    }
    if resolved.roots.is_empty() {
        // A successful no-op, not an error: there was simply nothing bounded
        // to clean. The report still states the resolved operation, scope, and
        // mode, so a machine consumer reads the same shape either way.
        // `diagnostics` counts safely omitted automatic roots, consistent with
        // the blocked scope above, so JSON agrees with stderr omissions.
        let empty = cargo_cleanme::cleanup::CleanReport {
            results: Vec::new(),
            diagnostics: resolved.omitted.len(),
            failed: 0,
            mode,
            counters: Default::default(),
            scope_blocked: None,
            unresolved_ownership: Vec::new(),
            selected_roots: Vec::new(),
            discovered_manifests: 0,
            resolved_workspaces: 0,
            units_considered: 0,
            effective_policy: Some(policy),
            selector,
        };
        emit_cleanup(
            &empty,
            &resolved,
            &[],
            options,
            "no bounded cleanup roots are known; no cleanup commands were run",
        )?;
        return Ok(0);
    }
    // Which resolved units are candidates. Resolved *here*, after the root set
    // is known, because `-i` needs those roots to list anything at all.
    let selection = match resolve_candidate_selection(&request, &resolved, &config, mode, options)?
    {
        SelectionOutcome::Chosen(selection) => selection,
        SelectionOutcome::Cancelled => {
            // A deliberate operator decision, not a failure and not a silent
            // no-op: say plainly that nothing ran.
            eprintln!(
                "cargo-cleanme: interactive selection cancelled; no cleanup commands were run"
            );
            return Ok(0);
        }
    };
    let show = options.format == OutputFormat::Human
        && cargo_cleanme::progress::should_show_progress(options.no_progress);
    let renderer = cargo_cleanme::progress::IndicatifRenderer::new(!show);
    let wall_start = std::time::Instant::now();
    // The bar must come down on the failure path too. `?` returned to the
    // top-level error reporter with the bar still live, and `BarState::drop`
    // *finishes* the bar rather than clearing it, so the retained line stayed
    // on screen above the `cargo-cleanme: …` message.
    let premise = cargo_cleanme::cleanup::AdmissionPremise {
        omitted: resolved.omitted.clone(),
    };
    let cleanup = run_engine_guarded(
        &resolved,
        &config,
        mode,
        &renderer,
        &policy,
        selector.clone(),
        Some(premise),
        &selection,
    );
    renderer.finish_and_clear();
    let report = cleanup?;
    if options.format == OutputFormat::Human
        && let Some(generation) = resolved.state_generation
    {
        println!("state generation last_full_at={generation} (Unix seconds)");
    }
    emit_cleanup(&report, &resolved, &resolved.roots, options, "")?;
    if options.stats {
        let elapsed = wall_start.elapsed();
        // C003 §7.6: cleanup --stats must account for the final
        // ownership-universe proof work, not only the initial scan.
        eprintln!(
            "cleanup stats: mode={:?} {} {} {} {} elapsed={:.2}s",
            mode,
            report.counters.stats_line(),
            report.counters.timings_line(),
            report.counters.proof_stats_line(),
            report.counters.proof_timings_line(),
            elapsed.as_secs_f64(),
        );
    }
    Ok(if report.failed > 0 || report.scope_blocked.is_some() {
        1
    } else {
        0
    })
}

/// What the selection step decided.
enum SelectionOutcome {
    /// Run the engine with this selection.
    Chosen(cargo_cleanme::cleanup::CleanupSelection),
    /// The operator quit the interactive list. Nothing runs.
    Cancelled,
}

/// Resolve which resolved cleanup units are candidates for this run.
///
/// Without `-i` this is the CLI's declared selection, with `WorkingDirectory`
/// turned into concrete roots. `WorkingDirectory` is the only unresolved form
/// and `resolved()` fails closed rather than falling back to "everything".
///
/// This is a *post-classification* filter: `resolve_cleanup_roots` and
/// `workspace::build_groups` inside the engine still see the full Routine
/// universe, so output shared with a workspace outside the anchor stays
/// `Shared`. Narrowing root selection here instead would be the ADR 006 defect.
///
/// With `-i` the operator's choice replaces it. The interactive path resolves
/// candidates through the *same* [`cargo_cleanme::cleanup::list_cleanup_candidates`]
/// pipeline the engine uses, so the offered rows are the engine's own units,
/// and the result is a strictly narrower `Roots` selection — never a way to
/// add, reclassify, or unblock one.
fn resolve_candidate_selection(
    request: &CleanupRequest,
    resolved: &ResolvedCleanup,
    config: &config::Config,
    mode: cargo_cleanme::cleanup::CleanMode,
    options: RunOptions,
) -> Result<SelectionOutcome, AppError> {
    if !request.interactive {
        return Ok(SelectionOutcome::Chosen(request.selection.resolved()?));
    }
    // The machine formats are refused first because that conflict is a static
    // property of the invocation: it is knowable without touching a single
    // stream, and clap makes the same kind of call by rejecting conflicting
    // argv before anything runs. The terminal precondition is reported next,
    //    for the same reason in the opposite direction — both are checked before
    // the listing, which is the first thing that would spawn `cargo metadata`.
    if options.format != OutputFormat::Human {
        return Err(AppError::Config(
            "interactive selection requires human output; --format json and --format log are \
             automation contracts and cannot carry a terminal session"
                .into(),
        ));
    }
    // The terminal precondition is checked *before* the listing, not after.
    // The listing is a full read-only resolution that spawns `cargo metadata`
    // across every resolved root; doing that only to then refuse for lack of a
    // terminal would spend the operator's time and spawn processes for a run
    // that was never going to happen.
    if let Err(reason) = cargo_cleanme::interactive::ensure_interactive_terminal(
        std::io::IsTerminal::is_terminal(&std::io::stdin()),
        std::io::IsTerminal::is_terminal(&std::io::stdout()),
    ) {
        return Err(AppError::Config(format!(
            "interactive selection requires a terminal ({reason}); \
             drop -i to clean without choosing interactively, or \
             use `cargo cleanme scan --all` to inspect the same units read-only"
        )));
    }
    // Progress bars would fight the repainting list, so the listing runs
    // silent. It is a read-only resolution: `cargo metadata` only.
    let silent = cargo_cleanme::progress::IndicatifRenderer::new(true);
    let listing = cargo_cleanme::cleanup::list_cleanup_candidates(
        &resolved.roots,
        config.scan.recency_seconds,
        mode,
        &cargo_cleanme::cleanup::SystemCleanupRunner,
        &silent,
        // Offer every unit in scope. The operator is choosing, and a list that
        // hid the units their anchor excluded would just move the surprise to
        // the report.
        &cargo_cleanme::cleanup::CleanupSelection::All,
    )?;
    if let Some(block) = listing.scope_blocked {
        // Offering rows from an unproven universe would be the ADR 006 shape in
        // a new costume: the operator would be picking from a list whose
        // classification is exactly what failed.
        return Err(AppError::Config(format!(
            "cannot present an interactive selection: {}",
            block.message
        )));
    }
    match cargo_cleanme::interactive::run_interactive(listing.candidates) {
        Ok(cargo_cleanme::interactive::SessionResult::Selected(roots)) => Ok(
            SelectionOutcome::Chosen(cargo_cleanme::cleanup::CleanupSelection::Roots(roots)),
        ),
        Ok(cargo_cleanme::interactive::SessionResult::Cancelled) => Ok(SelectionOutcome::Cancelled),
        Err(reason) => Err(AppError::Config(reason)),
    }
}

/// Run the combined cleanup engine against admitted roots, defending the
/// narrow race in which an admitted automatic root disappears between
/// admission and the engine's own strict validation.
///
/// On a fatal `InvalidRoot` over an automatic scope, the whole automatic set
/// is reclassified once with fresh metadata and — only when the offender now
/// proves safely omittable — the engine is re-run over the rebuilt universe
/// from scratch. Any other outcome becomes a typed whole-scope block, never a
/// silent sibling cleanup against a stale proof. Explicit scopes propagate
/// the fatal error unchanged.
#[allow(clippy::too_many_arguments)]
fn run_engine_guarded(
    resolved: &ResolvedCleanup,
    config: &config::Config,
    mode: cargo_cleanme::cleanup::CleanMode,
    renderer: &cargo_cleanme::progress::IndicatifRenderer,
    policy: &cargo_cleanme::cleanup::CleanupPolicy,
    selector: Option<cargo_cleanme::cleanup::CleanupSelector>,
    premise: Option<cargo_cleanme::cleanup::AdmissionPremise>,
    selection: &cargo_cleanme::cleanup::CleanupSelection,
) -> Result<cargo_cleanme::cleanup::CleanReport, AppError> {
    let attempt = |roots: &[std::path::PathBuf],
                   premise: Option<cargo_cleanme::cleanup::AdmissionPremise>| {
        cargo_cleanme::cleanup::clean_with_roots_policy_selector_guarded(
            roots,
            config.scan.recency_seconds,
            &config.cleanup.allowed_output_roots,
            mode,
            &cargo_cleanme::cleanup::SystemCleanupRunner,
            renderer,
            policy,
            selector.clone(),
            premise,
            selection,
        )
    };
    match attempt(&resolved.roots, premise.clone()) {
        Ok(report) => Ok(report),
        Err(AppError::InvalidRoot { path, reason }) if resolved.automatic => {
            let entries: cargo_cleanme::policy::CleanupCandidates = resolved
                .roots
                .iter()
                .cloned()
                .map(|r| (r, cargo_cleanme::policy::RootProvenance::Automatic))
                .collect();
            match cargo_cleanme::policy::classify_cleanup_roots(entries) {
                Ok(reclassified)
                    if reclassified.blocked.is_empty()
                        && reclassified
                            .omitted_paths()
                            .iter()
                            .any(|p| p == std::path::Path::new(&path)) =>
                {
                    let omitted = reclassified.omitted.clone();
                    let admitted = collapse_roots(reclassified.admitted);
                    if admitted.is_empty() {
                        let diagnostics = omitted.len();
                        return Ok(cargo_cleanme::cleanup::CleanReport {
                            results: Vec::new(),
                            diagnostics,
                            failed: 0,
                            mode,
                            counters: Default::default(),
                            scope_blocked: None,
                            unresolved_ownership: Vec::new(),
                            selected_roots: Vec::new(),
                            discovered_manifests: 0,
                            resolved_workspaces: 0,
                            units_considered: 0,
                            effective_policy: Some(policy.clone()),
                            selector: selector.clone(),
                        });
                    }
                    let rebuilt = cargo_cleanme::cleanup::AdmissionPremise { omitted };
                    attempt(&admitted, Some(rebuilt))
                }
                _ => Ok(cargo_cleanme::cleanup::CleanReport {
                    results: Vec::new(),
                    diagnostics: resolved.omitted.len(),
                    failed: 0,
                    mode,
                    counters: Default::default(),
                    scope_blocked: Some(cargo_cleanme::cleanup::ScopeBlock::new(
                        cargo_cleanme::cleanup::ScopeBlockReason::IncompleteDiscovery,
                        format!(
                            "cleanup root {path} became invalid during admission ({reason}); no cleanup commands were run"
                        ),
                    )),
                    unresolved_ownership: Vec::new(),
                    selected_roots: resolved.roots.clone(),
                    discovered_manifests: 0,
                    resolved_workspaces: 0,
                    units_considered: 0,
                    effective_policy: Some(policy.clone()),
                    selector: selector.clone(),
                }),
            }
        }
        Err(e) => Err(e),
    }
}

/// Resolve a cleanup scope into concrete bounded roots and its machine label.
///
/// The label always describes the scope that was actually resolved, never the
/// flags that were passed, because it is a machine contract.
fn resolve_cleanup_roots(
    scope: &CleanupScope,
    config_path: &std::path::Path,
    config: &config::Config,
    options: RunOptions,
) -> Result<ResolvedCleanup, AppError> {
    match scope {
        CleanupScope::Root(root) => {
            // Explicit roots stay authoritative: no omission, no fallback to
            // a smaller implicit set. The engine's strict validation reports
            // the defect as a fatal usage error.
            let absolute = cli::absolutize_root(root)?;
            let classified = cargo_cleanme::policy::classify_cleanup_roots(vec![(
                absolute,
                cargo_cleanme::policy::RootProvenance::Explicit,
            )])?;
            Ok(ResolvedCleanup {
                roots: collapse_roots(classified.admitted),
                scope_label: "explicit",
                state_generation: None,
                omitted_diagnostics: Vec::new(),
                omitted: Vec::new(),
                blocked: None,
                automatic: false,
            })
        }
        CleanupScope::Full => {
            // The Full reconciliation here is a *side effect of choosing cleanup
            // roots*, not something the user asked to see. Emitting its report
            // would put an unrelated document ahead of the cleanup report on
            // stdout and, in JSON mode, would emit two JSON documents — breaking
            // the one-document-per-invocation property the automation contract
            // depends on. Diagnostics and --stats still reach stderr.
            //
            // C028: roots come from the in-memory generation just reconciled,
            // never from a disk reload that could be an older generation when
            // publication failed, was unsupported, or was unavailable. No
            // fresh generation means no cleanup.
            let outcome = run_scan(ScanIntent::Full, config_path, options, EmitReport::No)?;
            if !outcome.publish_ok {
                eprintln!(
                    "cargo-cleanme: discovery state was not saved; cleaning the reconciled in-memory generation only"
                );
            }
            let (entries, generation) =
                cargo_cleanme::policy::full_cleanup_roots(outcome.code, outcome.full_state)?;
            admit_automatic(entries, "full", generation)
        }
        // Bare maintenance and `clean` with no scope selector land here and use
        // exactly the same maintenance policy: a configured legacy
        // `scan.root` is an exclusive Explicit override, otherwise bounded
        // seed roots plus active learned roots form the Routine scope.
        CleanupScope::Maintenance => {
            let policy = cargo_cleanme::policy::resolve(
                cargo_cleanme::domain::ScanRequest {
                    cli_root: None,
                    full: false,
                },
                &config.scan,
            )?;
            match policy.scope {
                // The configured-root override is the scope that gets
                // cleaned. Discarding it produced a bare maintenance run that
                // reported a successful Explicit no-op it never performed.
                ScanScope::Explicit(root) => {
                    let classified = cargo_cleanme::policy::classify_cleanup_roots(vec![(
                        root,
                        cargo_cleanme::policy::RootProvenance::Explicit,
                    )])?;
                    Ok(ResolvedCleanup {
                        roots: collapse_roots(classified.admitted),
                        scope_label: "explicit",
                        state_generation: match cargo_cleanme::discovery_state::load_default() {
                            cargo_cleanme::discovery_state::StateLoad::Loaded(state) => {
                                state.last_full_at
                            }
                            _ => None,
                        },
                        omitted_diagnostics: Vec::new(),
                        omitted: Vec::new(),
                        blocked: None,
                        automatic: false,
                    })
                }
                ScanScope::ExplicitRoots(roots) => {
                    let entries = roots
                        .into_iter()
                        .map(|r| (r, cargo_cleanme::policy::RootProvenance::Explicit))
                        .collect();
                    let classified = cargo_cleanme::policy::classify_cleanup_roots(entries)?;
                    Ok(ResolvedCleanup {
                        roots: collapse_roots(classified.admitted),
                        scope_label: "explicit",
                        state_generation: None,
                        omitted_diagnostics: Vec::new(),
                        omitted: Vec::new(),
                        blocked: None,
                        automatic: false,
                    })
                }
                ScanScope::Routine(_) => {
                    // C028: cleanup admission classifies the raw candidates —
                    // never the canonicalized `policy.scope` set, whose
                    // collapse would already have resolved a symlinked root
                    // into its target and hidden the invalid identity.
                    let home = directories::BaseDirs::new().map(|b| b.home_dir().to_path_buf());
                    let Some(home) = home else {
                        return admit_automatic(Vec::new(), "routine", None);
                    };
                    let (entries, warning) = cargo_cleanme::policy::routine_cleanup_candidates(
                        &home,
                        config.scan.learned_root_retention_days as u16,
                        cargo_cleanme::discovery_state::load_default(),
                    );
                    if let Some(warning) = warning {
                        eprintln!("cargo-cleanme: {warning}; using seed/configured Routine roots");
                    }
                    let generation = match cargo_cleanme::discovery_state::load_default() {
                        cargo_cleanme::discovery_state::StateLoad::Loaded(state) => {
                            state.last_full_at
                        }
                        _ => None,
                    };
                    admit_automatic(entries, "routine", generation)
                }
                // A non-Full resolve never produces Global. Failing closed
                // beats silently treating it as "nothing to do".
                ScanScope::Global(_) => Err(AppError::Config(
                    "maintenance scope resolved to a global scan, which is unreachable; \
                         refusing to treat it as an empty cleanup scope"
                        .into(),
                )),
            }
        }
    }
}

/// Admit one automatic (Routine/Full) candidate set: classify by provenance
/// before collapse, collapse admitted paths only, remember omissions for the
/// late pre-spawn recheck, and convert symlink/uncertain roots into a typed
/// whole-scope block instead of a fatal error or a silent scope reduction.
fn admit_automatic(
    entries: cargo_cleanme::policy::CleanupCandidates,
    scope_label: &'static str,
    state_generation: Option<u64>,
) -> Result<ResolvedCleanup, AppError> {
    // Automatic entries never produce a fatal classification error (only
    // Explicit does), but a panic would exit 101 outside the 0/1/2 contract.
    // Propagate as a usage error instead.
    let classified = cargo_cleanme::policy::classify_cleanup_roots(entries)
        .map_err(|e| AppError::Config(format!("automatic cleanup classification failed: {e}")))?;
    let omitted = classified.omitted.clone();
    let omitted_diagnostics = classified.omission_diagnostics();
    let blocked = if classified.blocked.is_empty() {
        None
    } else {
        let mut paths: Vec<String> = classified
            .blocked
            .iter()
            .map(|b| b.path.display().to_string())
            .collect();
        paths.sort();
        Some(cargo_cleanme::cleanup::ScopeBlock::new(
            cargo_cleanme::cleanup::ScopeBlockReason::IncompleteDiscovery,
            format!(
                "automatic cleanup scope is uncertain for {} root(s); no cleanup commands were run",
                paths.len(),
            ),
        ))
    };
    Ok(ResolvedCleanup {
        roots: collapse_roots(classified.admitted),
        scope_label,
        state_generation,
        omitted_diagnostics,
        omitted,
        blocked,
        automatic: true,
    })
}

/// Emit the resolved cleanup report in the selected format.
///
/// The scope label comes from the resolved scope, so a JSON consumer never has
/// to infer operation/scope/mode from argv spelling.
fn emit_cleanup(
    report: &cargo_cleanme::cleanup::CleanReport,
    resolved: &ResolvedCleanup,
    roots: &[std::path::PathBuf],
    options: RunOptions,
    empty_note: &str,
) -> Result<(), AppError> {
    if options.format == OutputFormat::Json {
        // Like scan: serialization failure is a usage error (exit 2), never a
        // panic (exit 101).
        let document = serde_json::to_string(&cargo_cleanme::output::cleanup(
            report,
            resolved.scope_label,
            resolved.state_generation,
        ))
        .map_err(|e| AppError::Config(format!("cannot serialize JSON report: {e}")))?;
        println!("{document}");
    } else if options.format == OutputFormat::Log {
        println!(
            "{}",
            cargo_cleanme::output::log::cleanup(report, resolved.scope_label)
        );
    } else if empty_note.is_empty() {
        println!(
            "combined roots {}\n{}",
            roots
                .iter()
                .map(|r| r.display().to_string())
                .collect::<Vec<_>>()
                .join(", "),
            report.render()
        );
    } else {
        println!("{empty_note}");
    }
    Ok(())
}

fn collapse_roots(roots: Vec<std::path::PathBuf>) -> Vec<std::path::PathBuf> {
    let mut roots: Vec<_> = roots
        .into_iter()
        .map(|p| std::fs::canonicalize(&p).unwrap_or(p))
        .collect();
    roots.sort();
    roots.dedup();
    let mut collapsed: Vec<std::path::PathBuf> = Vec::new();
    for path in roots {
        if !collapsed.iter().any(|parent| path.starts_with(parent)) {
            collapsed.push(path);
        }
    }
    collapsed
}

/// The JSON `scope` label must describe the scope that was actually resolved,
/// not the flags that were passed.
///
/// Deriving it from `full` / `root.is_some()` was wrong for a configured
/// `scan.root`: `policy::resolve` turns that into `ScanScope::Explicit`, so a
/// scan pinned to one root reported `"routine"`. The label is a machine
/// contract (`plans/output-schema-v1.md`), so it is derived from the resolved
/// policy — the single source of truth for what was scanned.
fn scope_label(scope: &ScanScope) -> &'static str {
    match scope {
        ScanScope::Global(_) => "full",
        ScanScope::Explicit(_) | ScanScope::ExplicitRoots(_) => "explicit",
        ScanScope::Routine(_) => "routine",
    }
}

/// Whether a scan writes its report to stdout.
///
/// Not a formatting choice: an *internal* scan — the Full reconciliation
/// `clean --full` runs to refresh learned state — must not write anything to
/// stdout, because the caller is about to write the report the user asked for.
/// Emitting both would put an unrelated document ahead of the cleanup report
/// and, in JSON mode, would emit two JSON documents in one invocation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum EmitReport {
    Yes,
    No,
}

/// The outcome of one scan: the process exit code plus, for a Full scan,
/// the in-memory reconciled generation and whether its publication survived.
///
/// C028: `clean --full` consumes the generation reconciled by the traversal
/// it just ran — never a disk reload that could be an older generation when
/// publication failed, was unsupported, or was unavailable. A failed save
/// stays a stderr warning for a read-only scan, but a Full cleanup without a
/// fresh in-memory generation is blocked.
struct ScanOutcome {
    code: i32,
    full_state: Option<cargo_cleanme::discovery_state::DiscoveryState>,
    publish_ok: bool,
}

fn run_scan(
    intent: ScanIntent,
    config_path: &std::path::Path,
    options: RunOptions,
    emit_report: EmitReport,
) -> Result<ScanOutcome, AppError> {
    use cargo_cleanme::{domain, progress};
    use std::time::SystemTime;

    let scan_start = SystemTime::now();
    let wall_start = std::time::Instant::now();
    let c = config::load_or_create(config_path)?;
    // Rootless `scan` is Full and never consults a configured `scan.root`:
    // configuration must not be able to silently narrow the canonical
    // reconciliation command. `scan ROOT` is the explicit CLI override, and
    // `scan --known` is the read-only maintenance scope.
    let (root, full) = match intent {
        ScanIntent::Full => (None, true),
        ScanIntent::Explicit(root) => (Some(root), false),
        ScanIntent::Maintenance => (None, false),
    };
    let policy = cargo_cleanme::policy::resolve(
        domain::ScanRequest {
            cli_root: root,
            full,
        },
        &c.scan,
    )?;
    let recency = policy.recency;

    // Inline progress is transient stderr state; final report remains stdout.
    // Non-TTY or `--no-progress` forces the no-op path without control noise.
    let show = options.format == OutputFormat::Human
        && progress::should_show_progress(options.no_progress);
    let renderer = progress::IndicatifRenderer::new(!show);
    // Progress-render failure must degrade to hidden rather than fail a scan.
    // Construction is infallible; refresh throttling bounds overhead.
    let observer: &dyn progress::ProgressObserver = &renderer;
    observer.phase(progress::ScanPhase::Discovery);

    // Manifest-first discovery (no sibling target required). A discovery
    // failure returns through `?`, which would drop the renderer with live
    // bars — and `BarState::drop` *finishes* a live bar into a retained line
    // instead of clearing it — so the bars come down first. (Hidden renderer:
    // no-op.)
    let discovery_start = std::time::Instant::now();
    let discovered = match cargo_cleanme::discovery::discover_manifests_with_attribution(
        &policy,
        observer,
        options.stats,
    ) {
        Ok(discovered) => discovered,
        Err(error) => {
            renderer.finish_and_clear();
            return Err(error);
        }
    };
    observer.discovery_issues(discovered.diagnostics.len() as u64);
    let discovery_elapsed = discovery_start.elapsed();
    let full_traversal_complete = discovered.coverage_complete
        && !discovered.diagnostics.iter().any(|d| {
            d.category == domain::DiagnosticCategory::PlatformRoot
                && d.severity == domain::DiagnosticSeverity::Error
        });
    let mut counters = discovered.counters.clone();
    counters.discovery_nanos = counters
        .discovery_nanos
        .saturating_add(cargo_cleanme::domain::elapsed_nanos(discovery_elapsed));
    let uncertainty: Vec<std::path::PathBuf> = discovered
        .diagnostics
        .iter()
        .filter(|d| {
            matches!(
                d.category,
                domain::DiagnosticCategory::PermissionDenied
                    | domain::DiagnosticCategory::Metadata
                    | domain::DiagnosticCategory::Vanished
            )
        })
        .filter_map(|d| d.path.clone())
        .collect();
    let mut diagnostics: Vec<domain::ScanDiagnostic> = discovered.diagnostics;
    let manifests = discovered.manifests;
    counters.manifests_found = manifests.len() as u64;

    observer.phase(progress::ScanPhase::Resolution);
    let resolution_start = std::time::Instant::now();
    let runner = cargo_cleanme::workspace::SystemCargoRunner;
    let workspaces = cargo_cleanme::workspace::resolve_workspaces(
        &manifests,
        &runner,
        &mut counters,
        &mut diagnostics,
        observer,
    );
    let _resolution_elapsed = resolution_start.elapsed();

    use cargo_cleanme::discovery_state::StateLoad;
    let loaded_state = cargo_cleanme::discovery_state::load_default();
    let mut full_state: Option<cargo_cleanme::discovery_state::DiscoveryState> = None;
    let mut publish_ok = true;
    // State notices are collected here and fanned out to stderr only after
    // `finish_and_clear`: a raw `eprintln!` while the bars are live bypasses
    // the coordinated draw target and corrupts the frame, orphaning bar lines
    // that survive the clear as stray terminal rows.
    let mut pending_notices: Vec<String> = Vec::new();
    if full {
        let selected = cargo_cleanme::discovery_state::full_reconciliation_prior(&loaded_state);
        if let Some((prior, replacing_invalid)) = selected {
            let now = cargo_cleanme::discovery_state::now_seconds();
            let mut resolved_by_manifest = std::collections::HashMap::new();
            for ws in &workspaces {
                for member in &ws.members {
                    resolved_by_manifest.insert(
                        std::fs::canonicalize(&member.manifest_path)
                            .unwrap_or_else(|_| member.manifest_path.clone()),
                        ws.root.clone(),
                    );
                }
            }
            let observations: Vec<_> = manifests
                .iter()
                .map(|manifest| {
                    let key = std::fs::canonicalize(manifest).unwrap_or_else(|_| manifest.clone());
                    cargo_cleanme::discovery_state::ProjectObservation {
                        manifest: key.clone(),
                        workspace: resolved_by_manifest.get(&key).cloned(),
                    }
                })
                .collect();
            let complete = full_traversal_complete;
            match cargo_cleanme::discovery_state::reconcile_full(
                &prior,
                &observations,
                &uncertainty,
                complete,
                now,
                c.scan.learned_root_retention_days as u16,
                directories::BaseDirs::new()
                    .map(|b| b.home_dir().to_path_buf())
                    .as_deref(),
            ) {
                cargo_cleanme::discovery_state::Reconciliation::Publish(next) => {
                    // The proven in-memory generation travels with this scan
                    // outcome regardless of what publication does next, so a
                    // Full cleanup can consume exactly what the traversal
                    // proved even when the save fails.
                    full_state = Some(next.clone());
                    match cargo_cleanme::discovery_state::publish(&next) {
                        Ok(()) => {
                            if replacing_invalid {
                                pending_notices.push(
                                    "replaced unusable discovery state after successful Full reconciliation"
                                        .into(),
                                );
                            }
                        }
                        Err(error) => {
                            publish_ok = false;
                            pending_notices.push(format!("discovery state was not saved: {error}"));
                        }
                    }
                }
                cargo_cleanme::discovery_state::Reconciliation::NoPublication(reason) => {
                    publish_ok = false;
                    pending_notices.push(format!("discovery state was not reconciled: {reason}"));
                }
            }
        } else {
            publish_ok = false;
            let message = loaded_state
                .diagnostic()
                .unwrap_or_else(|| "discovery state cannot be safely read".into());
            pending_notices.push(format!("{message}; Full state reconciliation was skipped"));
        }
    } else if let StateLoad::Loaded(prior) = loaded_state {
        let now = cargo_cleanme::discovery_state::now_seconds();
        let observed: Vec<_> = workspaces.iter().map(|w| w.root.clone()).collect();
        let mut next = prior;
        for project in &observed {
            for root in &mut next.learned_roots {
                if project.starts_with(&root.path) {
                    root.last_project_seen_at = root.last_project_seen_at.max(now);
                }
            }
        }
        if !observed.is_empty()
            && let Err(error) = cargo_cleanme::discovery_state::publish(&next)
        {
            pending_notices.push(format!("discovery state was not saved: {error}"));
        }
    }

    // Physical grouping before sizing; equal/nested output counted once.
    // Determinate analysis total is announced through the observer trait
    // (C002 §7.5); `analyze_groups` also announces it and advances via
    // `unit_completed`, so scan progress is genuinely determinate.
    // Phase first (re-scopes totals), then total (starts fresh scope).
    let groups = cargo_cleanme::workspace::build_groups(&workspaces);
    observer.phase(progress::ScanPhase::Analysis);
    observer.units_total(progress::ScanPhase::Analysis, groups.len() as u64);

    let clock_cutoff = match scan_start.checked_sub(recency) {
        Some(cutoff) => cutoff,
        // Same drop-finishes-bar hazard as the discovery error above: the
        // bars come down before the error escapes.
        None => {
            renderer.finish_and_clear();
            return Err(AppError::Config(
                "recency window exceeds system time range".into(),
            ));
        }
    };

    let physical = cargo_cleanme::workspace::analyze_groups(
        &workspaces,
        groups,
        scan_start,
        clock_cutoff,
        recency,
        &mut counters,
        &mut diagnostics,
        observer,
    );

    let full_incomplete = full && !full_traversal_complete;
    // Deterministic final report: every group, deduplicated total, stable order.
    let mut report = domain::ScanReport {
        groups: physical
            .into_iter()
            .map(|g| domain::EligibleOutputGroup {
                display_path: g.display_path,
                workspace_roots: g.owners.iter().map(|w| w.0.clone()).collect(),
                physical_paths: g.physical_paths,
                bytes: g.bytes,
                metric: g.metric,
                newest_mtime: g.newest_mtime,
                artifact_entries: g.artifact_entries,
                ownership: g.ownership,
            })
            .collect(),
        diagnostics,
        discovered: manifests.len() as u64,
        visited_entries: discovered.visited_entries,
        counters,
    };

    observer.phase(progress::ScanPhase::Reporting);
    renderer.finish_and_clear();

    // Deferred state notices: same stderr lines as before, but emitted only
    // once the coordinated frame is down, so they cannot orphan bar rows.
    for notice in &pending_notices {
        eprintln!("cargo-cleanme: {notice}");
    }

    // M005A total is an inventory estimate, never recovered bytes.
    if emit_report == EmitReport::No {
        // Suppressed: the report still existed and still drove every decision
        // below; only its rendering is withheld.
    } else if options.format == OutputFormat::Json {
        println!(
            "{}",
            serde_json::to_string(&cargo_cleanme::output::scan(
                &report,
                scope_label(&policy.scope),
            ))
            .map_err(|e| AppError::Config(format!("cannot serialize JSON report: {e}")))?
        );
    } else if options.format == OutputFormat::Log {
        println!(
            "{}",
            cargo_cleanme::output::log::scan(&report, scope_label(&policy.scope), full_incomplete)
        );
    } else {
        println!("{}", cargo_cleanme::report::render(&mut report));
    }
    // Normal diagnostic fan-out is human-readable detail on stderr. Log mode
    // carries `diagnostics=N` in its one line instead, so a retained history
    // tail is not ten paragraphs long.
    if !report.diagnostics.is_empty() && options.format != OutputFormat::Log {
        eprintln!(
            "{} filesystem diagnostics; rerun with a bounded root if needed",
            report.diagnostics.len()
        );
        // Cargo failures can repeat for hundreds of manifests. Keep their
        // complete per-manifest diagnostics in the report/JSON, but group the
        // human presentation by the bounded cause excerpt.
        let mut cargo_groups: BTreeMap<String, (usize, Vec<String>)> = BTreeMap::new();
        let mut other_diagnostics = Vec::new();
        for diagnostic in &report.diagnostics {
            let (stage, reason) = if let Some(reason) = diagnostic
                .message
                .strip_prefix("cargo locate-project failed:")
            {
                ("locate", reason)
            } else if let Some(reason) = diagnostic.message.strip_prefix("cargo metadata failed:") {
                ("metadata", reason)
            } else {
                other_diagnostics.push(diagnostic);
                continue;
            };
            let cause = reason.split(" | ").skip(1).collect::<Vec<_>>().join(" | ");
            let reason_key = if cause.is_empty() {
                reason.trim()
            } else {
                &cause
            };
            let group = cargo_groups
                .entry(format!("{stage}: {reason_key}"))
                .or_insert_with(|| (0, Vec::new()));
            group.0 += 1;
            if group.1.len() < 3
                && let Some(path) = &diagnostic.path
            {
                group.1.push(
                    path.display()
                        .to_string()
                        .chars()
                        .filter(|ch| !ch.is_control())
                        .take(200)
                        .collect(),
                );
            }
        }
        for (cause, (count, paths)) in cargo_groups.iter().take(8) {
            if let Some((stage, reason)) = cause.split_once(": ") {
                eprintln!("  {count} Cargo {stage} failure(s): {reason}");
            } else {
                eprintln!("  {count} Cargo resolution failure(s): {cause}");
            }
            if !paths.is_empty() {
                eprintln!("    examples: {}", paths.join(", "));
            }
        }
        let hidden_cargo_groups = cargo_groups.len().saturating_sub(8);
        if hidden_cargo_groups > 0 {
            eprintln!("  … {hidden_cargo_groups} additional Cargo failure cause(s)");
        }
        // Preserve other diagnostic detail, capped independently of Cargo's
        // repetition so the normal stderr path remains bounded.
        for diagnostic in other_diagnostics.iter().take(10) {
            eprintln!(
                "  {}: {}{}",
                diagnostic.severity.as_str(),
                diagnostic.message,
                diagnostic
                    .path
                    .as_ref()
                    .map(|p| format!(" ({})", p.display()))
                    .unwrap_or_default()
            );
        }
        if other_diagnostics.len() > 10 {
            eprintln!(
                "  … {} more non-Cargo diagnostic(s)",
                other_diagnostics.len() - 10
            );
        }
    }
    // C002 §7.8: detailed counters/timings are opt-in via `--stats` on
    // stderr (never stdout). Default scan emits no debug counter line.
    // `--no-progress --stats` is the canonical benchmark/debug combination.
    if options.stats {
        let elapsed = wall_start.elapsed();
        eprintln!(
            "scan stats: {} {} elapsed={:.2}s",
            report.counters.stats_line(),
            report.counters.timings_line(),
            elapsed.as_secs_f64(),
        );
        if !discovered.top_level_entries.is_empty() {
            let attribution = discovered
                .top_level_entries
                .iter()
                .map(|(path, count)| format!("{:?}={count}", path))
                .collect::<Vec<_>>()
                .join(" ");
            eprintln!("scan top-level entries: {attribution}");
        }
    }
    // Exit 1 means "the requested scan did not fully complete": either a Full
    // scan hit an unreadable platform root, or the caller asked for cleanup
    // and cleanup was blocked. It deliberately does NOT cover a failed
    // discovery-state save: `discovery_state` states that state is an
    // optimization only, the warning is already on stderr, and the Routine
    // branch has always ignored the identical failure. Failing the exit code
    // here made the two branches disagree about the same event.
    if full_incomplete {
        return Ok(ScanOutcome {
            code: 1,
            full_state,
            publish_ok,
        });
    }
    Ok(ScanOutcome {
        code: 0,
        full_state,
        publish_ok,
    })
}