autumn-cli 0.10.0

CLI tool for the Autumn web framework
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
//! Removal planning for `autumn plugin remove` — the mirror image of
//! [`super::install`] (issue #1631).
//!
//! Symmetry is the point: `plugin add` (issue #1606) made the install
//! machine-applied, so removal can be machine-reversed rather than the manual
//! scavenger hunt every comparable framework leaves behind. The same
//! discipline applies in both directions — every decision that can refuse the
//! removal is made *before* a single [`crate::generate::emit::Action`] is
//! queued, so a refusal leaves the app byte-identical, and a removal the CLI
//! cannot make confidently changes nothing at all.

use std::path::Path;

use crate::generate::emit::Plan;

use super::catalog::CatalogEntry;
use super::install::{PluginError, dependency_line, manifest_path};

/// One of the two wires `plugin add` writes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wire {
    /// The `[dependencies]` entry in `Cargo.toml`.
    Dependency,
    /// The `.plugin(...)` / `.with_blob_store(...)` call in `src/main.rs`.
    Mount,
}

impl Wire {
    /// How the wire is named in the report.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self {
            Self::Dependency => "the Cargo.toml dependency",
            Self::Mount => "the builder-chain mount",
        }
    }
}

/// Why a dependency this command found is still in `Cargo.toml` afterwards.
///
/// The distinction is the exit code: keeping a dependency the app still uses is
/// the *correct*, complete outcome, while a dependency written in a shape this
/// command will not rewrite leaves work for the user to do by hand — the same
/// situation [`RemoveOutcome::Manual`] reports, and it exits the same way.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DependencyKept {
    /// The app's own code still names the crate; removing the dependency would
    /// stop that code compiling. Nothing left for the user to do.
    StillUsed(String),
    /// Declared in a form the manifest rewriter does not touch. The user has to
    /// delete the line themselves.
    NotEditable(String),
}

impl DependencyKept {
    /// The message to print.
    #[must_use]
    pub fn reason(&self) -> &str {
        match self {
            Self::StillUsed(reason) | Self::NotEditable(reason) => reason,
        }
    }

    /// Whether this leaves the user something to do by hand.
    #[must_use]
    pub const fn needs_a_hand_edit(&self) -> bool {
        matches!(self, Self::NotEditable(_))
    }
}

/// What the plugin leaves behind in the database when its code is unwired.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DataResidue {
    /// Migration versions the plugin declares.
    pub migrations: Vec<String>,
    /// Tables the plugin creates and owns, in safe drop order (dependents
    /// first) so the statements can be applied top to bottom.
    pub tables: Vec<String>,
}

impl DataResidue {
    /// Whether the plugin owns any database state at all.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.migrations.is_empty() && self.tables.is_empty()
    }
}

/// What `plugin remove` decided to do.
#[derive(Debug)]
pub enum RemoveOutcome {
    /// At least one wire was found and can be removed.
    Removed {
        /// Filesystem actions to execute.
        plan: Box<Plan>,
        /// Wires this run removes.
        removed: Vec<Wire>,
        /// Wires `plugin add` writes that were not found — a partially wired
        /// app (a manual install, or a half-finished one).
        missing: Vec<Wire>,
        /// Set when the dependency is still in `Cargo.toml` afterwards, with
        /// the reason to print and whether it needs the user's attention.
        dependency_retained: Option<DependencyKept>,
        /// Database state the removal deliberately leaves in place.
        residue: DataResidue,
    },
    /// Neither wire is present — an idempotent no-op.
    NotInstalled {
        /// Database state a previous install may still have left behind.
        residue: DataResidue,
    },
    /// Nothing was changed; the user deletes the printed lines by hand.
    Manual {
        /// Why the automatic edit was declined.
        reason: String,
        /// The `[dependencies]` line to delete, when there is one.
        dependency_line: Option<String>,
        /// The builder-chain lines to delete.
        mount_snippet: String,
        /// Database state removal would leave in place either way.
        residue: DataResidue,
    },
}

/// The database state `entry` declares it owns.
#[must_use]
pub fn residue_for(entry: &CatalogEntry) -> DataResidue {
    DataResidue {
        migrations: entry.migrations.iter().map(|m| (*m).to_owned()).collect(),
        tables: entry.tables.iter().map(|t| (*t).to_owned()).collect(),
    }
}

/// The SQL `--drop-data` would run for `entry`, in application order.
#[must_use]
pub fn drop_data_statements(entry: &CatalogEntry) -> Vec<String> {
    let mut out = Vec::new();
    for table in entry.tables {
        out.push(format!("DROP TABLE IF EXISTS {table};"));
    }
    if !entry.migrations.is_empty() {
        let versions = entry
            .migrations
            .iter()
            .map(|version| format!("'{}'", version.split('_').next().unwrap_or(version)))
            .collect::<Vec<_>>()
            .join(", ");
        out.push(format!(
            "DELETE FROM __diesel_schema_migrations WHERE version IN ({versions});"
        ));
    }
    out
}

/// The marker comment `plugin add` writes above every mount it splices.
const MOUNT_MARKER: &str = "// added by `autumn plugin add";

/// The byte range of `entry`'s mount in `main_rs`, including the whole line it
/// starts on, the line its closing paren ends on, and any immediately
/// preceding "added by `autumn plugin add`" marker comment.
///
/// The scan runs against [`crate::rust_source::mask_non_code`], whose output is
/// byte-for-byte the same length as its input, so an offset found in the mask
/// is an offset into `main_rs` — and a commented-out or string-literal mount
/// can never be excised as if it were real code.
///
/// `None` when there is no such span, which is the whole safety story of AC #4:
///
/// - The plugin is mounted, but not through a literal
///   `mount_call(… mount_arg …)` — a plugin built into a variable and mounted
///   as `.plugin(configured)` is a real mount this code cannot see the type in,
///   and deleting the `let` that built it is far past what a line-oriented edit
///   can justify.
/// - The mount shares its line with other builder calls (a one-line chain).
///   Removing it would mean rewriting the line rather than deleting lines, and
///   a wrong rewrite leaves the app not compiling — exactly what `plugin add`
///   promises never to do, in reverse.
///
/// Both cases become the documented manual fallback: nothing is changed, and
/// the lines to delete are printed.
fn mount_span(main_rs: &str, entry: &CatalogEntry) -> Option<std::ops::Range<usize>> {
    let masked = crate::rust_source::mask_non_code(main_rs);
    // `starts_with`, not `contains`: the argument must BE this plugin, not
    // merely mention it. `.plugin(MyWrapper::new(admin::AdminPlugin::new(), …))`
    // contains the type path but is the user's wrapper mount, and excising it
    // would delete their code — and still compile, so nothing would surface
    // the loss.
    if let Some((open, close)) = super::install::mount_call_span(&masked, entry, |argument| {
        argument.trim_start().starts_with(entry.mount_arg)
    }) {
        let call_start = open + 1 - entry.mount_call.len();
        let line_start = masked[..call_start].rfind('\n').map_or(0, |at| at + 1);
        // Past the closing paren, up to and including the newline that ends
        // its line — a mount is removed by deleting whole lines.
        let line_end = masked[close..]
            .find('\n')
            .map_or(masked.len(), |at| close + at + 1);
        // Nothing but whitespace may share those lines: a `.routes(…)` before
        // or after this call would be deleted along with the mount.
        if masked[line_start..call_start].trim().is_empty()
            && masked[close + 1..line_end].trim().is_empty()
        {
            return Some(marker_start(main_rs, line_start, entry.crate_name)..line_end);
        }
        return None;
    }
    // Not found as `mount_call(mount_arg…)`. The one remaining shape this can
    // excise is the mount `plugin add` writes VERBATIM — `autumn-storage-s3`'s
    // is a `.with_blob_store({ … })` block whose argument is a brace expression,
    // not the type path — and only while it is still byte-identical to what was
    // written. An edited block is the user's code now, and goes to the manual
    // fallback rather than being guessed at.
    verbatim_mount_span(main_rs, &masked, entry)
}

/// The span of a byte-identical copy of `entry.mount` that is real code.
///
/// The literal search runs over the ORIGINAL source, because the marker comment
/// is part of `entry.mount` and the mask has blanked it. That alone would let a
/// commented-out or quoted copy of the mount — Autumn's own docs ship these
/// snippets — be excised while the live mount below it survived, and the report
/// would still say the plugin was removed. So every candidate is confirmed
/// against the mask: the call and the type path must still be *there* in the
/// masked text, which they are not inside a comment or a string literal.
fn verbatim_mount_span(
    main_rs: &str,
    masked: &str,
    entry: &CatalogEntry,
) -> Option<std::ops::Range<usize>> {
    let mut from = 0usize;
    while let Some(found) = main_rs[from..].find(entry.mount) {
        let at = from + found;
        let end = at + entry.mount.len();
        let starts_a_line = at == 0 || main_rs.as_bytes()[at - 1] == b'\n';
        if starts_a_line
            && masked[at..end].contains(entry.mount_call)
            && masked[at..end].contains(entry.mount_arg)
        {
            return Some(at..end);
        }
        from = at + 1;
    }
    None
}

/// `line_start`, extended back over the "added by `autumn plugin add
/// <crate>`" marker comment line when the install wrote one.
///
/// Read from the ORIGINAL source, not the mask: the marker is a comment, and
/// the mask has blanked its text away. Matched on the crate name too, so a
/// marker belonging to a different plugin — two mounts stacked with no blank
/// line between them — is never swallowed with this one.
fn marker_start(main_rs: &str, line_start: usize, crate_name: &str) -> usize {
    if line_start == 0 {
        return line_start;
    }
    let before = &main_rs[..line_start - 1];
    let previous_start = before.rfind('\n').map_or(0, |at| at + 1);
    let previous = main_rs[previous_start..line_start].trim();
    // Byte-exact, not `starts_with`: a marker the user annotated
    // (`… autumn-admin-plugin` — KEEP, see ticket 42`) is their comment now,
    // and taking it with the mount would delete a note they left on purpose.
    if previous == format!("{MOUNT_MARKER} {crate_name}`") {
        previous_start
    } else {
        line_start
    }
}

/// `main_rs` with every excisable mount of `entry` removed, or `None` when
/// there is none to remove.
///
/// Loops rather than removing the first: a chain can carry the same plugin
/// twice (a copy-paste, or two `plugin add` runs against a chain that was
/// edited in between), and stopping at the first would leave the plugin mounted
/// while the report said it had been removed.
///
/// A user's trailing comment on a mount line goes with the line, by design —
/// a mount is removed by deleting whole lines, and half a line is not a
/// removal.
#[must_use]
pub fn remove_mount(main_rs: &str, entry: &CatalogEntry) -> Option<String> {
    let mut current = main_rs.to_owned();
    let mut removed_any = false;
    while let Some(span) = mount_span(&current, entry) {
        current.replace_range(span, "");
        removed_any = true;
    }
    removed_any.then_some(current)
}

/// The first file that still names `crate_name`, across every tree a Cargo
/// target can be built from.
///
/// Wider than [`crate::generate::emit::crate_reference_site`]'s
/// `src`/`tests`/`benches`, because this is the only gate standing between a
/// user-facing destructive edit and a build that stops working: a plugin used
/// solely from `build.rs` or an example is still a plugin the manifest entry is
/// holding up.
fn still_referenced(
    root: &Path,
    crate_name: &str,
    overrides: &std::collections::HashMap<std::path::PathBuf, String>,
) -> Option<std::path::PathBuf> {
    if let Some(site) =
        crate::generate::emit::crate_reference_site(root, crate_name, &[], overrides)
    {
        return Some(site);
    }
    // The SAME marker set the conventional sweep uses — a spelling honoured in
    // one scan but not the other is a dependency stripped from under a target
    // that still needs it.
    let markers = crate::generate::emit::crate_reference_markers(crate_name);
    super::install::explicit_target_sources(root)
        .into_iter()
        .find(|path| {
            // The post-removal text wins over disk, as in the first scan.
            let src = overrides.get(path).map_or_else(
                || {
                    std::fs::read_to_string(path)
                        .ok()
                        .map(std::borrow::Cow::Owned)
                },
                |src| Some(std::borrow::Cow::Borrowed(src.as_str())),
            );
            src.is_some_and(|src| markers.iter().any(|marker| src.contains(marker.as_str())))
        })
}

/// Whether `remove_cargo_dependencies` actually took `crate_name` out of
/// `manifest_src` cleanly.
///
/// [`crate::generate::model::remove_cargo_dependencies`] is line-based, while
/// [`super::install::dependency_present`] parses the manifest — so a
/// dependency written as a MULTI-LINE inline table
/// (`foo = { version = "1", features = [\n  "bar",\n] }`) reads as present but
/// has only its first line deleted, leaving a `Cargo.toml` Cargo can no longer
/// parse. Nothing may be written unless the result still parses AND no longer
/// declares the crate; anything else is reported as a dependency the user has
/// to delete by hand.
fn dependency_cleanly_removed(updated: &str, crate_name: &str) -> bool {
    toml::from_str::<toml::Table>(updated).is_ok()
        && !super::install::dependency_present(updated, crate_name)
}

/// The reason text for a dependency this command declines to rewrite.
fn undeletable_dependency_reason(crate_name: &str) -> DependencyKept {
    DependencyKept::NotEditable(format!(
        "The {crate_name} dependency was left in Cargo.toml: it is not declared as a \
         plain `{crate_name} = \"…\"` line (a `[dependencies.{crate_name}]` subtable, or a \
         multi-line inline table), and rewriting that shape safely is beyond this \
         command. Delete it by hand"
    ))
}

/// Plan the removal of `entry` from the project at `root`.
///
/// Ordering is the contract, mirrored from [`super::install::plan_add`]. Every
/// refusal is decided before a single [`crate::generate::emit::Action`] exists,
/// so a refusal leaves the app byte-identical. The two writes are queued
/// **mount first**, exactly as the install queues them: `Plan::execute` writes
/// in order with no rollback, so a mid-execute I/O failure leaves a dependency
/// with no mount — an unused dependency, which still compiles — rather than a
/// mount with no dependency, which does not.
///
/// The database is never touched here, at all. `--drop-data` is a separate,
/// confirmed step on top of this plan (AC #2).
///
/// # Errors
///
/// [`PluginError::NotInProject`] when `root` has no `Cargo.toml`, or an I/O
/// error reading the manifest.
pub fn plan_remove(root: &Path, entry: &CatalogEntry) -> Result<RemoveOutcome, PluginError> {
    let manifest = manifest_path(root);
    if !manifest.is_file() {
        return Err(PluginError::NotInProject);
    }
    let manifest_src = std::fs::read_to_string(&manifest)?;
    let main_path = root.join("src").join("main.rs");
    let main_src = std::fs::read_to_string(&main_path).unwrap_or_default();

    let residue = residue_for(entry);
    let has_dependency = super::install::dependency_present(&manifest_src, entry.crate_name);
    let is_mounted = super::install::mount_present(&main_src, entry);

    // AC #5: removing something that was never installed is a no-op that says
    // so, mirroring `add`'s idempotency in the other direction.
    if !has_dependency && !is_mounted {
        return Ok(RemoveOutcome::NotInstalled { residue });
    }

    let unmounted_src = if is_mounted {
        match remove_mount(&main_src, entry) {
            Some(updated) => Some(updated),
            // AC #4: the builder chain cannot be edited confidently, so NOTHING
            // is edited — not even the dependency, whose removal would turn a
            // mount this command could not reach into a compile error.
            None => {
                return Ok(RemoveOutcome::Manual {
                    reason: format!(
                        "could not identify `{}`'s mount in {} as a single builder-chain call — nothing was changed",
                        entry.crate_name,
                        crate::generate::emit::relative_display(&main_path, root)
                    ),
                    dependency_line: has_dependency
                        .then(|| declared_dependency_line(&manifest_src, entry.crate_name)),
                    mount_snippet: entry.mount.trim_end_matches('\n').to_owned(),
                    residue,
                });
            }
        }
    } else {
        None
    };

    // Would stripping the dependency break code the user wrote by hand? The
    // check runs against the POST-removal `main.rs`, so this command's own
    // mount never counts as a reason to keep the dependency it is removing.
    let mut overrides = std::collections::HashMap::new();
    if let Some(updated) = &unmounted_src {
        overrides.insert(main_path.clone(), updated.clone());
    }
    let retained_by = if has_dependency {
        still_referenced(root, entry.crate_name, &overrides)
    } else {
        None
    };

    let mut plan = Plan::new(root);
    let mut removed = Vec::new();
    let mut missing = Vec::new();

    if let Some(updated) = unmounted_src {
        plan.modify(main_path, updated);
        removed.push(Wire::Mount);
    } else {
        missing.push(Wire::Mount);
    }

    let dependency_retained = match (has_dependency, &retained_by) {
        (true, None) => {
            let updated = crate::generate::model::remove_cargo_dependencies(
                &manifest_src,
                &[entry.crate_name],
            );
            if updated != manifest_src && dependency_cleanly_removed(&updated, entry.crate_name) {
                plan.modify(manifest, updated);
                removed.push(Wire::Dependency);
                None
            } else {
                Some(undeletable_dependency_reason(entry.crate_name))
            }
        }
        (true, Some(site)) => Some(DependencyKept::StillUsed(format!(
            "The {} dependency was kept: {} still names the crate, and removing it would \
             stop that code compiling",
            entry.crate_name,
            crate::generate::emit::relative_display(site, root)
        ))),
        (false, _) => {
            missing.push(Wire::Dependency);
            None
        }
    };

    Ok(RemoveOutcome::Removed {
        plan: Box::new(plan),
        removed,
        missing,
        dependency_retained,
        residue,
    })
}

/// The `[dependencies]` line `plugin remove` reports deleting, rendered from
/// what the manifest actually declares.
fn declared_dependency_line(manifest: &str, crate_name: &str) -> String {
    super::install::declared_dependency_version(manifest, crate_name).map_or_else(
        || format!("{crate_name} = …"),
        |version| dependency_line(crate_name, &version),
    )
}

/// What `--drop-data` decided to do, worked out before anything runs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DropDataDecision {
    /// The plugin declares no database state — there is nothing to drop.
    NothingToDrop,
    /// Apply these statements to the database at the resolved URL.
    Run {
        /// The database to apply them to.
        url: String,
        /// The statements, in application order.
        statements: Vec<String>,
    },
    /// The statements are printed for the user to apply: either no database is
    /// configured, or it is a backend this command will not drive blind.
    PrintOnly {
        /// Why the command is not applying them itself.
        reason: String,
        /// The statements, in application order.
        statements: Vec<String>,
    },
}

/// Decide what `--drop-data` does for `entry` against `database_url`.
///
/// Every reason not to run the statements is settled *here*, before the
/// confirmation prompt — asking "are you sure?" and then failing to connect is
/// the worst possible order for a destructive command.
#[must_use]
pub fn decide_drop_data(entry: &CatalogEntry, database_url: Option<&str>) -> DropDataDecision {
    let statements = drop_data_statements(entry);
    if statements.is_empty() {
        return DropDataDecision::NothingToDrop;
    }
    let Some(url) = database_url else {
        return DropDataDecision::PrintOnly {
            reason: "no database is configured here, so there is nothing to connect to".to_owned(),
            statements,
        };
    };
    if !is_postgres_url(url) {
        return DropDataDecision::PrintOnly {
            // Naming the backend, not just refusing: a SQLite app's owner needs
            // to know this is a "run it yourself" answer, not a broken URL.
            reason: format!(
                "`--drop-data` drives Postgres only, and this app's database is {}",
                backend_label(url)
            ),
            statements,
        };
    }
    DropDataDecision::Run {
        url: url.to_owned(),
        statements,
    }
}

/// Whether `url` names a Postgres database, by the schemes Diesel accepts.
fn is_postgres_url(url: &str) -> bool {
    let lowered = url.to_ascii_lowercase();
    lowered.starts_with("postgres://") || lowered.starts_with("postgresql://")
}

/// A human name for the backend `url` points at, for the refusal message.
fn backend_label(url: &str) -> String {
    let lowered = url.to_ascii_lowercase();
    lowered.split_once("://").map_or_else(
        || "not a recognisable database URL".to_owned(),
        |(scheme, _)| scheme.to_owned(),
    )
}

/// Apply `statements` to the Postgres database at `url`, in order.
///
/// # Errors
///
/// The connection or statement error, as a message ready to print.
pub fn execute_drop_data(url: &str, statements: &[String]) -> Result<(), String> {
    use diesel::connection::SimpleConnection as _;
    use diesel::{Connection as _, PgConnection};

    let mut conn = PgConnection::establish(url)
        .map_err(|err| format!("could not connect to the database: {err}"))?;
    // One transaction for the whole set. Postgres has transactional DDL, so
    // this costs nothing and removes the state no repair path covers: tables
    // dropped while `__diesel_schema_migrations` still records their migration
    // as applied, which makes `diesel migration run` refuse to recreate them.
    conn.transaction(|conn| {
        for statement in statements {
            conn.batch_execute(statement).map_err(|err| {
                diesel::result::Error::QueryBuilderError(
                    format!("`{statement}` failed: {err}").into(),
                )
            })?;
        }
        Ok(())
    })
    .map_err(|err: diesel::result::Error| err.to_string())
}

/// Plan the removal of a community crate from the project at `root`.
///
/// Dependency-only, because `plugin add` is dependency-only for a community
/// crate: nothing outside that crate can verify it exposes `<Name>Plugin`, so
/// the mount was printed for the user to paste, never spliced — and what was
/// never written cannot be confidently unwritten.
///
/// The reference check does the real work here. A hand-pasted mount *is* a
/// reference to the crate, so it keeps the dependency alive on its own: the
/// removal degrades to "delete your mount first", instead of stripping a
/// dependency the builder chain still needs.
///
/// # Errors
///
/// [`PluginError::NotInProject`] when `root` has no `Cargo.toml`, or an I/O
/// error reading the manifest.
pub fn plan_remove_community(root: &Path, crate_name: &str) -> Result<RemoveOutcome, PluginError> {
    let manifest = manifest_path(root);
    if !manifest.is_file() {
        return Err(PluginError::NotInProject);
    }
    let manifest_src = std::fs::read_to_string(&manifest)?;
    if !super::install::dependency_present(&manifest_src, crate_name) {
        return Ok(RemoveOutcome::NotInstalled {
            // A community crate declares nothing about its schema, so nothing
            // can be reported here. `run_remove` says as much in prose rather
            // than letting an empty list read as "owns no data".
            residue: DataResidue::default(),
        });
    }

    let overrides = std::collections::HashMap::new();
    if let Some(site) = still_referenced(root, crate_name, &overrides) {
        return Ok(RemoveOutcome::Removed {
            plan: Box::new(Plan::new(root)),
            removed: Vec::new(),
            missing: Vec::new(),
            dependency_retained: Some(DependencyKept::StillUsed(format!(
                "The {crate_name} dependency was kept: {} still names the crate. `plugin add` \
                 never wrote that mount, so `remove` will not delete it — delete it yourself, \
                 then re-run",
                crate::generate::emit::relative_display(&site, root)
            ))),
            residue: DataResidue::default(),
        });
    }

    let updated = crate::generate::model::remove_cargo_dependencies(&manifest_src, &[crate_name]);
    let mut plan = Plan::new(root);
    let mut removed = Vec::new();
    let mut dependency_retained = None;
    if updated != manifest_src && dependency_cleanly_removed(&updated, crate_name) {
        plan.modify(manifest, updated);
        removed.push(Wire::Dependency);
    } else {
        dependency_retained = Some(undeletable_dependency_reason(crate_name));
    }
    Ok(RemoveOutcome::Removed {
        plan: Box::new(plan),
        removed,
        missing: Vec::new(),
        dependency_retained,
        residue: DataResidue::default(),
    })
}

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

    const SCAFFOLD_MAIN: &str = r"use autumn_web::prelude::*;

#[autumn_web::main]
async fn main() {
    let app = autumn_web::app()
        // added by `autumn plugin add autumn-admin-plugin`
        .plugin(autumn_admin_plugin::AdminPlugin::new())
        .routes(routes![index])
        .migrations(MIGRATIONS);

    app
        .run()
        .await;
}
";

    /// The scaffold `plugin add` splices into, with no plugin mounted yet.
    const SCAFFOLD_MAIN_BARE: &str = r"use autumn_web::prelude::*;

#[autumn_web::main]
async fn main() {
    let app = autumn_web::app()
        .routes(routes![index])
        .migrations(MIGRATIONS);

    app
        .run()
        .await;
}
";

    const SCAFFOLD_CARGO: &str = r#"[package]
name = "demo"
version = "0.1.0"
edition = "2024"

[dependencies]
autumn-web = "0.7.0"
autumn-admin-plugin = "0.7.0"
maud = { version = "0.27", features = ["axum"] }
"#;

    fn admin() -> &'static CatalogEntry {
        catalog::lookup("autumn-admin-plugin").expect("admin entry")
    }

    fn media() -> &'static CatalogEntry {
        catalog::lookup("autumn-media-plugin").expect("media entry")
    }

    fn fake_project(main_rs: &str, cargo: &str) -> tempfile::TempDir {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("Cargo.toml"), cargo).unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(tmp.path().join("src/main.rs"), main_rs).unwrap();
        tmp
    }

    // ── AC #1: remove reverses both wires ────────────────────────────────────

    #[test]
    fn the_mount_and_its_marker_comment_are_excised_together() {
        let out = remove_mount(SCAFFOLD_MAIN, admin()).expect("excisable");
        assert!(!out.contains("AdminPlugin"), "{out}");
        assert!(!out.contains("added by `autumn plugin add"), "{out}");
        // Everything else survives byte-for-byte.
        assert!(out.contains(".routes(routes![index])"), "{out}");
        assert!(out.contains("let app = autumn_web::app()"), "{out}");
        assert!(out.contains(".migrations(MIGRATIONS)"), "{out}");
    }

    /// A configured mount spans several lines; excising one line would leave a
    /// dangling paren. The whole balanced-paren span goes.
    #[test]
    fn a_configured_multi_line_mount_is_excised_whole() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        .plugin(\n            autumn_admin_plugin::AdminPlugin::new()\n                .require_role(\"staff\"),\n        )\n        .routes(routes![index]);\n}\n";
        let out = remove_mount(main, admin()).expect("excisable");
        assert!(!out.contains("AdminPlugin"), "{out}");
        assert!(!out.contains("require_role"), "{out}");
        assert!(out.contains(".routes(routes![index]);"), "{out}");
        assert!(!out.contains(".plugin("), "{out}");
    }

    /// The `autumn-storage-s3` mount is a whole block with an `.await` inside;
    /// it must come out in one piece.
    #[test]
    fn the_storage_block_mount_is_excised_whole() {
        let entry = catalog::lookup("autumn-storage-s3").unwrap();
        let main = format!(
            "#[autumn_web::main]\nasync fn main() {{\n    let app = autumn_web::app()\n{}        .routes(routes![index]);\n}}\n",
            entry.mount
        );
        let out = remove_mount(&main, entry).expect("excisable");
        assert!(!out.contains("S3BlobStore"), "{out}");
        assert!(!out.contains("with_blob_store"), "{out}");
        assert!(out.contains(".routes(routes![index]);"), "{out}");
    }

    // ── AC #4: safe degradation ──────────────────────────────────────────────

    /// A mount built into a variable is a real mount that this code cannot
    /// excise: the `.plugin(configured)` call does not name the type. Nothing
    /// is changed.
    #[test]
    fn a_mount_through_a_variable_is_not_excised() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    let configured = autumn_admin_plugin::AdminPlugin::new().require_role(\"staff\");\n    let app = autumn_web::app()\n        .plugin(configured)\n        .routes(routes![index]);\n}\n";
        assert!(remove_mount(main, admin()).is_none());
    }

    /// A mount sharing its line with other builder calls cannot be excised by
    /// deleting lines, and rewriting the line is exactly the kind of guess
    /// that leaves an app not compiling.
    #[test]
    fn a_mount_sharing_a_line_with_other_calls_is_not_excised() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    autumn_web::app().plugin(autumn_admin_plugin::AdminPlugin::new()).routes(routes![index]).run().await;\n}\n";
        assert!(remove_mount(main, admin()).is_none());
    }

    /// A comment that merely *mentions* the mount is not a mount.
    #[test]
    fn a_commented_out_mount_is_not_excised() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        // .plugin(autumn_admin_plugin::AdminPlugin::new())\n        .routes(routes![index]);\n}\n";
        assert!(remove_mount(main, admin()).is_none());
    }

    // ── AC #1 end-to-end planning ────────────────────────────────────────────

    #[test]
    fn a_fully_wired_plugin_has_both_wires_removed() {
        let tmp = fake_project(SCAFFOLD_MAIN, SCAFFOLD_CARGO);
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            removed, missing, ..
        } = outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(removed.contains(&Wire::Dependency), "{removed:?}");
        assert!(removed.contains(&Wire::Mount), "{removed:?}");
        assert!(missing.is_empty(), "{missing:?}");
    }

    // ── AC #5: idempotent no-op ──────────────────────────────────────────────

    #[test]
    fn removing_a_plugin_that_is_not_installed_is_a_no_op() {
        let tmp = fake_project(
            "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app();\n}\n",
            "[package]\nname = \"demo\"\n\n[dependencies]\nautumn-web = \"0.7.0\"\n",
        );
        assert!(matches!(
            plan_remove(tmp.path(), admin()).unwrap(),
            RemoveOutcome::NotInstalled { .. }
        ));
    }

    // ── AC #4: partial installs ──────────────────────────────────────────────

    #[test]
    fn a_dependency_without_a_mount_is_removed_and_the_mount_reported_missing() {
        let tmp = fake_project(
            "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        .routes(routes![index]);\n}\n",
            SCAFFOLD_CARGO,
        );
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            removed, missing, ..
        } = outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert_eq!(removed, vec![Wire::Dependency]);
        assert_eq!(missing, vec![Wire::Mount]);
    }

    #[test]
    fn a_mount_without_a_dependency_is_removed_and_the_dependency_reported_missing() {
        let tmp = fake_project(
            SCAFFOLD_MAIN,
            "[package]\nname = \"demo\"\n\n[dependencies]\nautumn-web = \"0.7.0\"\n",
        );
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            removed, missing, ..
        } = outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert_eq!(removed, vec![Wire::Mount]);
        assert_eq!(missing, vec![Wire::Dependency]);
    }

    /// The app is never left non-compiling: a mount the CLI cannot excise
    /// means the dependency stays too, and nothing at all is written.
    #[test]
    fn an_unexcisable_mount_leaves_the_dependency_alone() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    let configured = autumn_admin_plugin::AdminPlugin::new();\n    let app = autumn_web::app()\n        .plugin(configured);\n}\n";
        let tmp = fake_project(main, SCAFFOLD_CARGO);
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Manual {
            dependency_line,
            mount_snippet,
            ..
        } = &outcome
        else {
            panic!("expected Manual, got {outcome:?}");
        };
        assert!(
            dependency_line
                .as_ref()
                .is_some_and(|line| line.contains("autumn-admin-plugin")),
            "{dependency_line:?}"
        );
        assert!(mount_snippet.contains("AdminPlugin"), "{mount_snippet}");
    }

    /// A dependency the app still names elsewhere must survive: stripping it
    /// would break a build the user's own code depends on.
    #[test]
    fn a_dependency_still_used_elsewhere_is_retained() {
        let tmp = fake_project(SCAFFOLD_MAIN, SCAFFOLD_CARGO);
        std::fs::write(
            tmp.path().join("src/support.rs"),
            "pub fn role() -> autumn_admin_plugin::AdminPlugin { todo!() }\n",
        )
        .unwrap();
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            removed,
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert_eq!(removed, &vec![Wire::Mount]);
        assert!(
            dependency_retained
                .as_ref()
                .is_some_and(|kept| kept.reason().contains("support.rs")),
            "{dependency_retained:?}"
        );
    }

    // ── AC #2: data safety ───────────────────────────────────────────────────

    #[test]
    fn a_plugin_that_owns_tables_reports_them_as_residue() {
        let residue = residue_for(media());
        assert!(
            residue.tables.iter().any(|t| t == "media_rooms"),
            "{residue:?}"
        );
        assert!(!residue.migrations.is_empty(), "{residue:?}");
    }

    #[test]
    fn a_plugin_that_owns_no_tables_has_no_residue() {
        assert!(residue_for(admin()).is_empty());
        assert!(residue_for(catalog::lookup("autumn-cache-redis").unwrap()).is_empty());
    }

    /// The declared drop plan must drop dependents before their parents, so it
    /// can be applied top to bottom — the same order the plugin's own
    /// `down.sql` uses.
    #[test]
    fn the_drop_plan_drops_dependents_first_and_forgets_the_migrations() {
        let statements = drop_data_statements(media());
        let participants = statements
            .iter()
            .position(|s| s.contains("media_room_participants"))
            .expect("participants drop");
        let rooms = statements
            .iter()
            .position(|s| s.contains("DROP TABLE IF EXISTS media_rooms"))
            .expect("rooms drop");
        assert!(participants < rooms, "{statements:?}");
        assert!(
            statements
                .iter()
                .any(|s| s.contains("__diesel_schema_migrations")),
            "{statements:?}"
        );
    }

    #[test]
    fn a_plugin_with_no_data_has_an_empty_drop_plan() {
        assert!(drop_data_statements(admin()).is_empty());
    }

    // ── AC #2: what `--drop-data` decides, before anything runs ──────────────

    #[test]
    fn a_plugin_with_no_declared_data_has_nothing_to_drop() {
        assert_eq!(
            decide_drop_data(admin(), Some("postgres://localhost/app")),
            DropDataDecision::NothingToDrop
        );
    }

    #[test]
    fn a_postgres_url_gets_the_statements_applied() {
        let decision = decide_drop_data(media(), Some("postgres://localhost/app"));
        let DropDataDecision::Run { url, statements } = decision else {
            panic!("expected Run, got {decision:?}");
        };
        assert_eq!(url, "postgres://localhost/app");
        assert_eq!(statements, drop_data_statements(media()));
    }

    /// No database configured is not an error — it is a reason to print the
    /// statements instead of guessing at a connection.
    #[test]
    fn no_database_url_prints_the_statements_instead() {
        let decision = decide_drop_data(media(), None);
        let DropDataDecision::PrintOnly { statements, .. } = decision else {
            panic!("expected PrintOnly, got {decision:?}");
        };
        assert_eq!(statements, drop_data_statements(media()));
    }

    /// The dropper speaks Postgres. A `SQLite` app gets the statements to run
    /// itself rather than a connection error after the confirmation prompt.
    #[test]
    fn a_non_postgres_backend_prints_the_statements_instead() {
        let decision = decide_drop_data(media(), Some("sqlite://app.db"));
        let DropDataDecision::PrintOnly { reason, statements } = decision else {
            panic!("expected PrintOnly, got {decision:?}");
        };
        assert!(reason.to_lowercase().contains("sqlite"), "{reason}");
        assert_eq!(statements, drop_data_statements(media()));
    }

    // ── Community crates: dependency-only, in both directions ────────────────

    const COMMUNITY_CARGO: &str = r#"[package]
name = "demo"
version = "0.1.0"

[dependencies]
autumn-web = "0.7.0"
autumn-plugin-live-feed = "0.3.1"
"#;

    /// `plugin add` never writes a community mount, so `remove` only has the
    /// dependency to take back — and only when nothing still uses it.
    #[test]
    fn a_community_dependency_is_removed_when_nothing_uses_it() {
        let tmp = fake_project(
            "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app();\n}\n",
            COMMUNITY_CARGO,
        );
        let outcome = plan_remove_community(tmp.path(), "autumn-plugin-live-feed").unwrap();
        let RemoveOutcome::Removed { removed, .. } = &outcome else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert_eq!(removed, &vec![Wire::Dependency]);
    }

    /// The user pasted the derived mount by hand. Stripping the dependency now
    /// would leave an app that does not compile, so the dependency stays and
    /// the report says why.
    #[test]
    fn a_community_dependency_with_a_hand_written_mount_is_retained() {
        let tmp = fake_project(
            "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        .plugin(autumn_plugin_live_feed::LiveFeedPlugin::new());\n}\n",
            COMMUNITY_CARGO,
        );
        let outcome = plan_remove_community(tmp.path(), "autumn-plugin-live-feed").unwrap();
        let RemoveOutcome::Removed {
            removed,
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(removed.is_empty(), "{removed:?}");
        assert!(dependency_retained.is_some(), "{outcome:?}");
    }

    #[test]
    fn removing_an_absent_community_dependency_is_a_no_op() {
        let tmp = fake_project(
            "#[autumn_web::main]\nasync fn main() {}\n",
            "[package]\nname = \"demo\"\n\n[dependencies]\nautumn-web = \"0.7.0\"\n",
        );
        assert!(matches!(
            plan_remove_community(tmp.path(), "autumn-plugin-live-feed").unwrap(),
            RemoveOutcome::NotInstalled { .. }
        ));
    }

    /// The strongest statement of AC #1, for every plugin in the catalog: what
    /// `plugin add` splices in, `plugin remove` takes back out — byte for
    /// byte, marker comment included. A mount whose shape drifts from its
    /// removal is caught here rather than in a user's `git diff`.
    #[test]
    fn every_first_party_mount_round_trips_through_insert_and_remove() {
        for entry in catalog::FIRST_PARTY {
            let installed = crate::plugin::install::insert_mount(SCAFFOLD_MAIN_BARE, entry.mount)
                .unwrap_or_else(|| panic!("{} could not be mounted", entry.crate_name));
            assert_ne!(installed, SCAFFOLD_MAIN_BARE, "{}", entry.crate_name);
            let removed = remove_mount(&installed, entry)
                .unwrap_or_else(|| panic!("{} could not be unmounted", entry.crate_name));
            assert_eq!(
                removed, SCAFFOLD_MAIN_BARE,
                "{} did not round-trip",
                entry.crate_name
            );
        }
    }

    /// Two plugins stacked in one chain: removing either leaves the other —
    /// and the other's marker comment — completely intact.
    #[test]
    fn removing_one_of_two_stacked_mounts_leaves_the_other_whole() {
        let admin = admin();
        let search = catalog::lookup("autumn-search").unwrap();
        let with_search =
            crate::plugin::install::insert_mount(SCAFFOLD_MAIN_BARE, search.mount).unwrap();
        let both = crate::plugin::install::insert_mount(&with_search, admin.mount).unwrap();

        let without_admin = remove_mount(&both, admin).expect("excisable");
        assert_eq!(without_admin, with_search);

        let without_search = remove_mount(&both, search).expect("excisable");
        assert!(
            without_search.contains("AdminPlugin::new()"),
            "{without_search}"
        );
        assert!(
            without_search.contains("added by `autumn plugin add autumn-admin-plugin`"),
            "{without_search}"
        );
        assert!(!without_search.contains("SearchPlugin"), "{without_search}");
        assert!(
            !without_search.contains("added by `autumn plugin add autumn-search`"),
            "{without_search}"
        );
    }

    // ── Review follow-ups: code this command must NOT delete ─────────────────

    /// A plugin wrapped inside ANOTHER plugin's constructor. The type path is
    /// inside the `.plugin(...)` argument, but the argument is not that
    /// plugin — excising it would delete the user's wrapper mount and still
    /// compile, so nothing would ever surface the loss.
    #[test]
    fn a_mount_nested_inside_another_plugins_argument_is_not_excised() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        .plugin(MyWrapperPlugin::new(autumn_admin_plugin::AdminPlugin::new(), my_setting()))\n        .routes(routes![index]);\n}\n";
        assert!(remove_mount(main, admin()).is_none());
    }

    /// A blob store chosen at runtime: the `else` branch has nothing to do with
    /// the plugin, and deleting it with the mount also still compiles.
    #[test]
    fn a_conditional_blob_store_is_not_excised() {
        let entry = catalog::lookup("autumn-storage-s3").unwrap();
        let main = "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        .with_blob_store(if use_s3 {\n            Box::new(autumn_storage_s3::S3BlobStore::from_config(&c).await.unwrap())\n        } else {\n            Box::new(LocalBlobStore::new(\"./uploads\"))\n        })\n        .routes(routes![index]);\n}\n";
        assert!(remove_mount(main, entry).is_none());
    }

    /// An annotated marker comment is the user's note, not this command's
    /// bookkeeping — the mount goes, the note stays.
    #[test]
    fn an_annotated_marker_comment_is_left_alone() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        // added by `autumn plugin add autumn-admin-plugin` -- KEEP: see ticket 42\n        .plugin(autumn_admin_plugin::AdminPlugin::new())\n        .routes(routes![index]);\n}\n";
        let out = remove_mount(main, admin()).expect("excisable");
        assert!(!out.contains("AdminPlugin"), "{out}");
        assert!(out.contains("KEEP: see ticket 42"), "{out}");
    }

    /// The verbatim fallback (the shape `autumn-storage-s3`'s block mount takes)
    /// must respect the mask too. A commented-out copy of the mount — Autumn's
    /// own docs ship these snippets — must never be gutted while the live mount
    /// below it survives and the report claims a removal.
    #[test]
    fn a_commented_out_copy_of_a_block_mount_is_never_excised_instead_of_the_real_one() {
        let entry = catalog::lookup("autumn-storage-s3").unwrap();
        let main = format!(
            "#[autumn_web::main]\nasync fn main() {{\n    let app = autumn_web::app()\n/*\n{}*/\n{}        .routes(routes![index]);\n}}\n",
            entry.mount, entry.mount
        );
        let out = remove_mount(&main, entry).expect("the live mount is excisable");
        // The live mount is gone; the commented-out copy is untouched.
        assert!(out.contains("/*\n"), "{out}");
        assert_eq!(
            out.matches("S3BlobStore::from_config(").count(),
            1,
            "only the commented-out copy should remain:\n{out}"
        );
        assert!(!crate::plugin::install::mount_present(&out, entry), "{out}");
    }

    /// Two copies of the same mount: removing one and reporting success would
    /// leave the plugin mounted and running.
    #[test]
    fn every_copy_of_a_repeated_mount_is_removed() {
        let main = "#[autumn_web::main]\nasync fn main() {\n    let app = autumn_web::app()\n        .plugin(autumn_admin_plugin::AdminPlugin::new())\n        .plugin(autumn_admin_plugin::AdminPlugin::new())\n        .routes(routes![index]);\n}\n";
        let out = remove_mount(main, admin()).expect("excisable");
        assert!(!out.contains("AdminPlugin"), "{out}");
        assert!(out.contains(".routes(routes![index])"), "{out}");
    }

    /// A dependency written as a multi-line inline table parses as present but
    /// is not a plain `name = "…"` line. Deleting only its first line leaves a
    /// `Cargo.toml` Cargo cannot parse, so nothing is written and the report
    /// says to delete it by hand.
    #[test]
    fn a_multi_line_inline_table_dependency_is_never_half_deleted() {
        let cargo = "[package]\nname = \"demo\"\n\n[dependencies]\nautumn-web = \"0.7.0\"\nautumn-admin-plugin = { version = \"0.7.0\", features = [\n    \"extra\",\n] }\nmaud = \"0.27\"\n";
        let tmp = fake_project(SCAFFOLD_MAIN, cargo);
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            plan,
            removed,
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert_eq!(removed, &vec![Wire::Mount]);
        assert!(
            dependency_retained
                .as_ref()
                .is_some_and(DependencyKept::needs_a_hand_edit),
            "{dependency_retained:?}"
        );
        for action in &plan.actions {
            assert!(
                !action.path().ends_with("Cargo.toml"),
                "Cargo.toml must not be rewritten: {action:?}"
            );
        }
    }

    /// A `[dependencies.<crate>]` subtable is the same story.
    #[test]
    fn a_dependency_subtable_is_never_half_deleted() {
        let cargo = "[package]\nname = \"demo\"\n\n[dependencies]\nautumn-web = \"0.7.0\"\n\n[dependencies.autumn-admin-plugin]\nversion = \"0.7.0\"\n";
        let tmp = fake_project(SCAFFOLD_MAIN, cargo);
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(
            dependency_retained
                .as_ref()
                .is_some_and(DependencyKept::needs_a_hand_edit),
            "{outcome:?}"
        );
    }

    /// A plugin used only from `build.rs` still needs its dependency: the
    /// build script is a Cargo target, and stripping the line stops it
    /// compiling just as surely as stripping one `src/` uses.
    #[test]
    fn a_dependency_used_only_from_a_build_script_is_retained() {
        let tmp = fake_project(SCAFFOLD_MAIN, SCAFFOLD_CARGO);
        std::fs::write(
            tmp.path().join("build.rs"),
            "fn main() { let _ = autumn_admin_plugin::VERSION; }\n",
        )
        .unwrap();
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(
            dependency_retained
                .as_ref()
                .is_some_and(|kept| kept.reason().contains("build.rs")),
            "{dependency_retained:?}"
        );
    }

    /// Codex review: Cargo lets a target live anywhere. A `[[bin]] path =
    /// "cmd/server.rs"` that still uses the plugin is invisible to a
    /// `src`/`tests`/`benches`/`examples` sweep, and stripping the dependency
    /// stops that target compiling.
    #[test]
    fn a_dependency_used_only_from_a_custom_target_path_is_retained() {
        let cargo =
            format!("{SCAFFOLD_CARGO}\n[[bin]]\nname = \"server\"\npath = \"cmd/server.rs\"\n");
        let tmp = fake_project(SCAFFOLD_MAIN, &cargo);
        std::fs::create_dir_all(tmp.path().join("cmd")).unwrap();
        std::fs::write(
            tmp.path().join("cmd/server.rs"),
            "fn main() { let _ = autumn_admin_plugin::AdminPlugin::new(); }\n",
        )
        .unwrap();

        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(
            dependency_retained
                .as_ref()
                .is_some_and(|kept| kept.reason().contains("server.rs")),
            "{dependency_retained:?}"
        );
    }

    /// What removing the admin plugin from a project whose manifest names
    /// `src/main.rs` as an explicit `[[bin]]` removes and keeps (#2476).
    fn removal_with_bin_path(
        path: &str,
        main_rs: &str,
        sibling: Option<(&str, &str)>,
    ) -> (Vec<Wire>, Option<DependencyKept>) {
        let cargo = format!("{SCAFFOLD_CARGO}\n[[bin]]\nname = \"app\"\npath = \"{path}\"\n");
        let tmp = fake_project(main_rs, &cargo);
        if let Some((name, src)) = sibling {
            std::fs::write(tmp.path().join("src").join(name), src).unwrap();
        }
        match plan_remove(tmp.path(), admin()).unwrap() {
            RemoveOutcome::Removed {
                removed,
                dependency_retained,
                ..
            } => (removed, dependency_retained),
            other => panic!("expected Removed, got {other:?}"),
        }
    }

    /// The explicit-target scan sees `src/main.rs` without the mount this
    /// command removes, not the copy on disk. `./src/main.rs` is the same file.
    #[test]
    fn an_explicit_main_target_does_not_retain_the_mount_being_removed() {
        for path in ["src/main.rs", "./src/main.rs"] {
            let (removed, kept) = removal_with_bin_path(path, SCAFFOLD_MAIN, None);
            assert!(kept.is_none(), "{path}: {kept:?}");
            assert!(removed.contains(&Wire::Dependency), "{path}: {removed:?}");
        }
    }

    /// A second use of the crate in the post-removal `main.rs` keeps it.
    #[test]
    fn an_explicit_main_target_that_still_uses_the_plugin_retains_it() {
        let main =
            format!("{SCAFFOLD_MAIN}\nfn extra() {{ let _ = autumn_admin_plugin::Other; }}\n");
        let (_, kept) = removal_with_bin_path("src/main.rs", &main, None);
        assert!(kept.is_some());
    }

    /// A sibling file under `src/` is still read from disk.
    #[test]
    fn an_explicit_main_target_with_a_using_sibling_module_retains_it() {
        let sibling = (
            "extra.rs",
            "pub fn f() { let _ = autumn_admin_plugin::Other; }\n",
        );
        let (_, kept) = removal_with_bin_path("src/main.rs", SCAFFOLD_MAIN, Some(sibling));
        assert!(kept.is_some_and(|kept| kept.reason().contains("extra.rs")));
    }

    /// A sibling module of such a target counts too — the target's own tree is
    /// swept, not just the file the manifest names.
    #[test]
    fn a_dependency_used_from_a_custom_targets_sibling_module_is_retained() {
        let cargo =
            format!("{SCAFFOLD_CARGO}\n[[bin]]\nname = \"server\"\npath = \"cmd/server.rs\"\n");
        let tmp = fake_project(SCAFFOLD_MAIN, &cargo);
        std::fs::create_dir_all(tmp.path().join("cmd")).unwrap();
        std::fs::write(
            tmp.path().join("cmd/server.rs"),
            "mod panel;\nfn main() {}\n",
        )
        .unwrap();
        std::fs::write(
            tmp.path().join("cmd/panel.rs"),
            "pub use autumn_admin_plugin::AdminPlugin;\n",
        )
        .unwrap();

        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(dependency_retained.is_some(), "{outcome:?}");
    }

    /// A custom build-script path (`[package] build = "…"`) replaces
    /// `build.rs`, and is scanned in its place.
    #[test]
    fn a_dependency_used_only_from_a_custom_build_script_is_retained() {
        let cargo = SCAFFOLD_CARGO.replace(
            "edition = \"2024\"",
            "edition = \"2024\"\nbuild = \"tools/build.rs\"",
        );
        let tmp = fake_project(SCAFFOLD_MAIN, &cargo);
        std::fs::create_dir_all(tmp.path().join("tools")).unwrap();
        std::fs::write(
            tmp.path().join("tools/build.rs"),
            "fn main() { let _ = autumn_admin_plugin::VERSION; }\n",
        )
        .unwrap();

        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(dependency_retained.is_some(), "{outcome:?}");
    }

    /// The widened scan must not become "retain everything": an ordinary
    /// project with a custom target that does NOT use the plugin still gets its
    /// dependency removed.
    #[test]
    fn a_custom_target_that_does_not_use_the_plugin_does_not_retain_it() {
        let cargo =
            format!("{SCAFFOLD_CARGO}\n[[bin]]\nname = \"server\"\npath = \"cmd/server.rs\"\n");
        let tmp = fake_project(SCAFFOLD_MAIN, &cargo);
        std::fs::create_dir_all(tmp.path().join("cmd")).unwrap();
        std::fs::write(tmp.path().join("cmd/server.rs"), "fn main() {}\n").unwrap();

        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            removed,
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(dependency_retained.is_none(), "{dependency_retained:?}");
        assert!(removed.contains(&Wire::Dependency), "{removed:?}");
    }

    /// Codex review: `extern crate autumn_admin_plugin as admin;` followed by
    /// `admin::…` is the one spelling that carries neither `{ident}::` nor
    /// `use {ident}` anywhere in the file. Missing it strips the dependency out
    /// from under code that still compiles against it.
    #[test]
    fn a_dependency_reached_through_an_extern_crate_alias_is_retained() {
        let tmp = fake_project(SCAFFOLD_MAIN, SCAFFOLD_CARGO);
        std::fs::write(
            tmp.path().join("src/support.rs"),
            "extern crate autumn_admin_plugin as admin;\n\npub fn panel() -> admin::AdminPlugin { todo!() }\n",
        )
        .unwrap();
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            removed,
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert_eq!(removed, &vec![Wire::Mount]);
        assert!(
            dependency_retained
                .as_ref()
                .is_some_and(|kept| kept.reason().contains("support.rs")),
            "{dependency_retained:?}"
        );
    }

    /// The same spelling in a custom Cargo target path, since that scan carries
    /// its own copy of the marker set.
    #[test]
    fn an_extern_crate_alias_in_a_custom_target_path_is_retained() {
        let cargo =
            format!("{SCAFFOLD_CARGO}\n[[bin]]\nname = \"server\"\npath = \"cmd/server.rs\"\n");
        let tmp = fake_project(SCAFFOLD_MAIN, &cargo);
        std::fs::create_dir_all(tmp.path().join("cmd")).unwrap();
        std::fs::write(
            tmp.path().join("cmd/server.rs"),
            "extern crate autumn_admin_plugin as admin;\nfn main() { let _ = admin::AdminPlugin::new(); }\n",
        )
        .unwrap();
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(dependency_retained.is_some(), "{outcome:?}");
    }

    /// `use <crate> as alias;` was already covered by the `use {ident}` prefix
    /// — pinned so a future edit to the marker set cannot quietly drop it.
    #[test]
    fn a_dependency_reached_through_a_use_alias_is_retained() {
        let tmp = fake_project(SCAFFOLD_MAIN, SCAFFOLD_CARGO);
        std::fs::write(
            tmp.path().join("src/support.rs"),
            "use autumn_admin_plugin as admin;\n\npub fn panel() -> admin::AdminPlugin { todo!() }\n",
        )
        .unwrap();
        let outcome = plan_remove(tmp.path(), admin()).unwrap();
        let RemoveOutcome::Removed {
            dependency_retained,
            ..
        } = &outcome
        else {
            panic!("expected Removed, got {outcome:?}");
        };
        assert!(dependency_retained.is_some(), "{outcome:?}");
    }
}