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
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
//! Provenance for generator-owned files (issue #1835).
//!
//! `autumn destroy` recomputes the plan a matching `autumn generate` would
//! build, then compares each owned file against that plan before deleting it.
//! The comparison answers "did the developer edit this file?" — but it asks
//! "does this file match what the CLI renders *today*?", and those are the same
//! question only while the template is unchanged. A newer CLI whose template
//! moved on therefore reports `Diverged` for every untouched file it wrote, and
//! `--force` — which also bypasses the genuine-edit guard — becomes routine.
//!
//! So `generate` records a digest of every file it owns as it writes it, in the
//! manifest at [`MANIFEST_PATH`], and `destroy` accepts a file that matches
//! either the current render or that recorded digest. A real edit matches
//! neither and is still refused.
//!
//! The same merge-base idea backs `autumn upgrade`'s scaffold manifest
//! (`.autumn/scaffold.toml`); this one covers `generate`'s output instead, and
//! is a separate file because the two are written by different commands with
//! different lifetimes.
//!
//! A project generated before this manifest existed has no baseline. That is
//! not an error: it falls back to comparing against the current render only —
//! exactly the previous behaviour, `--force` included.

use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::config::GENERATE_CONFIG_FILENAME;
use super::spelling;

/// Project-relative location of the generator provenance manifest.
///
/// Under `.autumn/` next to `scaffold.toml`: machine-written bookkeeping, kept
/// out of the one directory a developer reads. Meant to be committed — its
/// value is being the baseline a later checkout compares against.
pub const MANIFEST_PATH: &str = ".autumn/generated.toml";

/// Joins the parts of one argument list. No shell argument carries a unit
/// separator, so two lists cannot collide by concatenation.
const UNIT_SEPARATOR: char = '\u{1f}';

/// Joins the argument list to the config fingerprint and the backend, and one
/// config source's digest to the next.
const RECORD_SEPARATOR: char = '\u{1e}';

/// Line endings normalised, so a CRLF checkout is not read as an edit.
///
/// `git config core.autocrlf true` rewrites every text file on checkout. Hashing
/// the bytes as they sit on disk would report the developer had rewritten every
/// generated file — on exactly the platform least able to diagnose it.
fn normalize(contents: &str) -> String {
    contents.replace("\r\n", "\n")
}

/// Digest of a text file, over the LF-normalised bytes.
#[must_use]
pub fn text_digest(contents: &str) -> String {
    digest(normalize(contents).as_bytes())
}

/// Digest of a binary file, over the bytes exactly as written.
///
/// No normalisation: a `CreateBytes` asset is opaque, and rewriting CRLF inside
/// a PNG would make two different files hash alike.
#[must_use]
pub fn bytes_digest(bytes: &[u8]) -> String {
    digest(bytes)
}

/// SHA-256, hex encoded. Not used for security — it only has to tell "these are
/// the bytes Autumn wrote" from "these are not", stably across hosts.
fn digest(bytes: &[u8]) -> String {
    use sha2::{Digest as _, Sha256};
    hex::encode(Sha256::digest(bytes))
}

/// How a recorded file relates to the resource that wrote it (issue #2557).
///
/// Only a plan that claims to be the sole resource of its invocation records
/// a scope (see `Plan::claim_sole_resource`). No scope means an older CLI or
/// an unclaimed plan wrote the entry. `destroy` never sweeps such an entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Scope {
    /// A `Create`/`CreateBytes` file. Only this resource uses it.
    Owned,
    /// A `CreateIfAbsent` file. Sibling resources can use it too.
    Shared,
}

/// One entry, as the orphan sweep reads it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Recorded<'a> {
    /// Project-relative, forward-slashed key. Not validated: it is manifest
    /// data.
    pub key: &'a str,
    /// Digest of the file as it was written.
    pub digest: &'a str,
    /// See [`Scope`].
    pub scope: Option<Scope>,
}

/// One recorded file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct Entry {
    /// Digest of the file as it was written.
    digest: String,
    /// The command that wrote it, normalised by [`current_invocation`].
    ///
    /// `destroy` honours the digest only for the same command with the same
    /// arguments — the contract its help text already states. Without this the
    /// digest is keyed by path alone, so `autumn destroy model Post` with the
    /// fields omitted would delete the model file it can no longer render
    /// while the `schema.rs` and `Cargo.toml` reverts, which ARE derived from
    /// those fields, silently do nothing: a half-destroyed project where the
    /// pre-#1835 code refused outright. It also keeps one command from
    /// claiming another's output — `autumn new --starter` writes files through
    /// this same engine, and `autumn destroy auth` must not delete them.
    invocation: String,
    /// See [`Scope`]. Absent in manifests from 0.8.0 and from unclaimed plans.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "lenient_scope"
    )]
    scope: Option<Scope>,
}

/// Read a `scope`, and read a value this CLI does not know as no scope.
///
/// A strict parse would fail the whole manifest on one unknown value (from a
/// newer CLI, or a hand edit). `load` reads a failed parse as empty, and the
/// next `save` would then drop every other entry.
fn lenient_scope<'de, D>(deserializer: D) -> Result<Option<Scope>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<toml::Value>::deserialize(deserializer)?;
    Ok(match value.as_ref().and_then(toml::Value::as_str) {
        Some("owned") => Some(Scope::Owned),
        Some("shared") => Some(Scope::Shared),
        _ => None,
    })
}

/// The stored description of one shared-file edit that a run made (issue
/// #2560).
///
/// `destroy` compares anchors with the reverts of its own plan. An anchor holds
/// no template text, so a template change does not alter it.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RevertAnchor {
    /// Project-relative, forward-slashed path of the edited file.
    pub path: String,
    /// The revert kind and the values that name the edit, as `Kind(values)`.
    pub revert: String,
}

impl RevertAnchor {
    /// The revert kind: the text before the first `(`.
    #[must_use]
    pub fn kind(&self) -> &str {
        self.revert.split('(').next().unwrap_or(&self.revert)
    }

    /// Whether the path names a file inside the project.
    ///
    /// The path comes from the manifest. Only plain components qualify: an
    /// absolute path or a `..` is not a target.
    #[must_use]
    pub fn is_project_relative(&self) -> bool {
        Path::new(&self.path)
            .components()
            .all(|c| matches!(c, Component::Normal(_)))
    }
}

impl std::fmt::Display for RevertAnchor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.path, self.revert)
    }
}

/// The on-disk shape of [`MANIFEST_PATH`].
#[derive(Default, Serialize, Deserialize)]
struct ManifestFile {
    /// Project-relative path → what was written there, and by what.
    #[serde(default)]
    files: BTreeMap<String, Entry>,
    /// Maps a run id ([`run_id`]) to the shared-file edits of that run.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    runs: BTreeMap<String, Vec<RevertAnchor>>,
}

/// The run id of an invocation. The invocation has control characters, so the
/// id is its hash. A hash is a valid TOML key.
fn run_id(invocation: &str) -> String {
    digest(invocation.as_bytes())
}

/// What identifies the generator inputs of this run, for a project at `root`.
///
/// Two parts, because the arguments alone are not the whole input:
///
/// - This process's command line, reduced to what names the resource. Stable
///   across CLI versions, unlike anything derived from the argument structs:
///   it is the user's own words. The `generate`/`destroy` verb drops out so the
///   two spellings of one resource agree, and `--force`/`--dry-run` drop out
///   because they legitimately differ between the two runs.
/// - A digest of the generator config those arguments resolve from — the
///   auto-discovered [`GENERATE_CONFIG_FILENAME`], which does not appear in the
///   arguments at all, and any file a `--config` names.
/// - The resolved database backend, which the arguments do not name either and
///   which decides the SQL a migration holds and the `schema.rs` block a
///   [`Revert::SchemaTable`](super::emit::Revert::SchemaTable) expects.
///
/// Without the last two, an input the arguments cannot see would change the
/// plan while the identity looked unchanged: `destroy` would accept the old
/// owned files by digest and then apply shared-file reverts the original
/// generation never made — removing the model and its migration while silently
/// leaving its `schema.rs` entry behind.
///
/// Changing the recipe or the backend therefore drops the baseline for every
/// resource, back to comparing against the current render. Deliberate: a stale
/// baseline is worse than no baseline.
#[must_use]
pub fn current_invocation(root: &Path) -> String {
    let args: Vec<String> = std::env::args_os()
        .skip(1)
        .map(|arg| arg.to_string_lossy().into_owned())
        .collect();
    let inputs = normalize_invocation(args.iter().cloned());
    let config = config_fingerprint(root, &args);
    let backend = backend_fingerprint(root);
    format!("{inputs}{RECORD_SEPARATOR}{config}{RECORD_SEPARATOR}{backend}")
}

/// An identity built from a generator's RESOLVED inputs instead of its raw
/// arguments.
///
/// For the generators that recover omitted arguments on the destroy path:
/// `autumn destroy webhook <provider> <Name>` reads a `--path`/`--secret-env`
/// used at generation time back out of `autumn.toml`, so the recomputed plan is
/// right while the arguments differ. Keyed on the raw arguments, the baseline
/// would then be refused for a file nobody has touched — the very case this
/// manifest exists to serve.
///
/// No config fingerprint: `parts` already carries every resolved input, so
/// there is nothing left for a config file to change. The backend still
/// counts — it decides what a migration in the plan holds — so `root` is
/// taken for it.
#[must_use]
pub fn resolved_invocation(root: &Path, parts: &[&str]) -> String {
    let inputs = parts.join(&UNIT_SEPARATOR.to_string());
    let backend = backend_fingerprint(root);
    format!("{inputs}{RECORD_SEPARATOR}{backend}")
}

/// The project's resolved database backend, as a stable name.
///
/// Resolved rather than fingerprinted from its sources: `autumn.toml`, the
/// profile overlays, `.env` and the database environment variables all feed
/// [`detect_backend`](super::detect_backend), and only the answer changes what
/// a generator emits. Hashing the sources instead would drop the baseline on
/// every unrelated config edit.
fn backend_fingerprint(root: &Path) -> &'static str {
    match super::detect_backend(root) {
        autumn_web::config::DatabaseBackend::Postgres => "postgres",
        autumn_web::config::DatabaseBackend::Sqlite => "sqlite",
    }
}

/// A digest over every generator config file this run could have read.
fn config_fingerprint(root: &Path, args: &[String]) -> String {
    // The auto-discovered file first, then every `--config` in the order it was
    // given. A fixed order rather than a sorted one, and CONTENTS only — no
    // path: `root` is an absolute path, so naming the sources would tie the
    // identity to where the project happens to sit on disk, and a manifest
    // written in `/home/alice/app` would be refused after a clone to
    // `/work/app`. The later checkout is exactly what this manifest is
    // committed for. The `--config` path itself is already in the arguments,
    // which are part of the identity, so nothing is lost by leaving it out.
    let mut sources = vec![root.join(GENERATE_CONFIG_FILENAME)];
    let mut next_is_path = false;
    for arg in args {
        if next_is_path {
            sources.push(PathBuf::from(arg));
            next_is_path = false;
        } else if let Some(path) = arg.strip_prefix("--config=") {
            sources.push(PathBuf::from(path));
        } else if arg == "--config" {
            next_is_path = true;
        }
    }

    let mut material = String::new();
    let mut seen: Vec<&Path> = Vec::new();
    for source in &sources {
        if seen.contains(&source.as_path()) {
            continue; // named twice; one contribution is enough.
        }
        seen.push(source);
        // LF-normalised like every other text digest here: a CRLF checkout of a
        // committed recipe parses identically as TOML, and must not read as a
        // different input. Non-UTF-8 bytes are hashed as they lie.
        let contents = std::fs::read(source).map_or_else(
            |_| "absent".to_owned(),
            |bytes| std::str::from_utf8(&bytes).map_or_else(|_| digest(&bytes), text_digest),
        );
        material.push_str(&contents);
        material.push(RECORD_SEPARATOR);
    }
    digest(material.as_bytes())
}

fn normalize_invocation(args: impl Iterator<Item = String>) -> String {
    let mut verb_seen = false;
    let mut parts = Vec::new();
    for arg in args {
        if !verb_seen && (arg == "generate" || arg == "destroy") {
            verb_seen = true;
            continue;
        }
        if matches!(arg.as_str(), "--force" | "--dry-run") {
            continue;
        }
        parts.push(arg);
    }
    parts.join(&UNIT_SEPARATOR.to_string())
}

/// What `autumn generate` recorded about the files it owns.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Provenance {
    entries: BTreeMap<String, Entry>,
    runs: BTreeMap<String, Vec<RevertAnchor>>,
}

impl Provenance {
    /// Read the manifest under `root`. A missing, unreadable, or malformed
    /// manifest is an empty one: no baseline is the safe answer, never an error
    /// that would abort a generator run.
    ///
    /// A symlinked manifest reads as empty too. Read through one and whoever
    /// controls the target supplies the digests that decide what `destroy`
    /// deletes — from outside the repository, where no diff shows it.
    #[must_use]
    pub fn load(root: &Path) -> Self {
        if refuse_symlink(root, &root.join(MANIFEST_PATH)).is_err() {
            return Self::default();
        }
        let text = std::fs::read_to_string(root.join(MANIFEST_PATH)).unwrap_or_default();
        let file: ManifestFile = toml::from_str(&text).unwrap_or_default();
        Self {
            entries: file.files,
            runs: file.runs,
        }
    }

    /// Whether an entry is recorded for this project-relative key.
    #[cfg(test)]
    pub fn contains(&self, key: &str) -> bool {
        self.entries.contains_key(key)
    }

    /// Whether nothing is recorded — a project with no baseline.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Whether `invocation` wrote exactly `digest` to `path`.
    ///
    /// False when nothing is recorded — an unproven file is never assumed ours
    /// — and false when a different command recorded it (see [`Entry`]).
    /// Reads the entry of another spelling when there is no exact entry
    /// (issue #3382).
    #[must_use]
    pub fn is_ours(&self, root: &Path, path: &Path, digest: &str, invocation: &str) -> bool {
        self.owners(root, path)
            .iter()
            .any(|e| e.digest == digest && e.invocation == invocation)
    }

    /// Whether ANY command wrote exactly `digest` to `path`.
    ///
    /// For a file several resources share: only the first writer is recorded,
    /// so requiring the destroying command to be that writer would strand the
    /// file the moment a template change stopped the content compare from
    /// matching. Sound only where the caller has already established that no
    /// sibling still needs the file — which is what the `CreateIfAbsent` pass
    /// does before it asks.
    #[must_use]
    pub fn was_written(&self, root: &Path, path: &Path, digest: &str) -> bool {
        self.owners(root, path).iter().any(|e| e.digest == digest)
    }

    /// Every entry `invocation` wrote, for the orphan sweep (issue #2557).
    pub fn recorded_by<'a>(&'a self, invocation: &'a str) -> impl Iterator<Item = Recorded<'a>> {
        self.entries
            .iter()
            .filter(move |(_, e)| e.invocation == invocation)
            .map(|(key, e)| Recorded {
                key,
                digest: &e.digest,
                scope: e.scope,
            })
    }

    /// Record `digest` as the content `invocation` wrote to `path`.
    ///
    /// `scope` is `None` for an unclaimed writer. `destroy` never sweeps such
    /// an entry.
    ///
    /// A path outside `root` cannot be keyed and is dropped: the manifest
    /// describes one project, and destroy would never look it up.
    pub fn record(
        &mut self,
        root: &Path,
        path: &Path,
        digest: String,
        invocation: &str,
        scope: Option<Scope>,
    ) {
        if let Some(k) = key(root, path) {
            // Keyed by path, so the newest writer replaces the previous one:
            // a file has exactly one owner, and the manifest cannot grow an
            // entry per regeneration. Another spelling of the file goes too.
            self.forget(root, path);
            self.entries.insert(
                k,
                Entry {
                    digest,
                    invocation: invocation.to_owned(),
                    scope,
                },
            );
        }
    }

    /// Record the shared-file edits `invocation` made.
    ///
    /// Add to the earlier record, do not replace it. An earlier run made its
    /// edits, and they stay in the files.
    pub fn record_reverts(&mut self, invocation: &str, anchors: Vec<RevertAnchor>) {
        if anchors.is_empty() {
            return;
        }
        let run = self.runs.entry(run_id(invocation)).or_default();
        run.extend(anchors);
        run.sort();
        run.dedup();
    }

    /// The recorded edits that a destroy with `planned` would leave behind
    /// (issue #2560).
    ///
    /// An anchor counts when all three hold:
    ///
    /// - its target file still exists;
    /// - `planned` has no equal anchor;
    /// - `planned` has an anchor of the same kind. The revert moved, so an
    ///   input changed. A kind that is missing from `planned` is a skip that
    ///   depends on file state, such as an append that was already done.
    ///
    /// A revert in `planned` that was not recorded is fine: it only cleans
    /// more. Empty when nothing was recorded. A manifest from an older CLI keeps
    /// the old behaviour.
    #[must_use]
    pub fn dropped_reverts(
        &self,
        root: &Path,
        invocation: &str,
        planned: &[RevertAnchor],
    ) -> Vec<RevertAnchor> {
        self.runs
            .get(&run_id(invocation))
            .into_iter()
            .flatten()
            .filter(|anchor| !planned.contains(anchor))
            .filter(|anchor| planned.iter().any(|p| p.kind() == anchor.kind()))
            .filter(|anchor| anchor.is_project_relative() && root.join(&anchor.path).exists())
            .cloned()
            .collect()
    }

    /// Forget the run of `invocation`: its edits were reverted, or the user
    /// chose `--force`.
    pub fn forget_run(&mut self, invocation: &str) {
        self.runs.remove(&run_id(invocation));
    }

    /// Drop the entries of [`Self::keys_for`].
    ///
    /// Another spelling resolves only while the file exists. After a delete,
    /// use [`Self::forget_key`] with the keys you read before the delete.
    pub fn forget(&mut self, root: &Path, path: &Path) {
        for k in self.keys_for(root, path) {
            self.entries.remove(&k);
        }
    }

    /// Every recorded key for the file at `path` (issue #3382).
    ///
    /// The key of `path`, and each key that is another spelling of the same
    /// directory entry (see [`spelling::one_entry`]). For example, on a
    /// case-insensitive file system, `foo.rs` finds the entry for `Foo.rs`.
    /// On a case-sensitive host, only the exact key matches.
    #[must_use]
    pub fn keys_for(&self, root: &Path, path: &Path) -> Vec<String> {
        let Some(own) = key(root, path) else {
            return Vec::new();
        };
        self.entries
            .keys()
            .filter(|k| **k == own || is_alias(root, k, &own, path))
            .cloned()
            .collect()
    }

    /// The entries that tell who wrote `path`.
    ///
    /// The exact entry, when there is one: the newest writer is recorded
    /// under it. Otherwise, the entries of [`Self::keys_for`].
    fn owners(&self, root: &Path, path: &Path) -> Vec<&Entry> {
        let Some(own) = key(root, path) else {
            return Vec::new();
        };
        if let Some(entry) = self.entries.get(&own) {
            return vec![entry];
        }
        self.entries
            .iter()
            .filter(|(k, _)| is_alias(root, k, &own, path))
            .map(|(_, e)| e)
            .collect()
    }

    /// Drop the entry with exactly the key `k`, if any.
    pub fn forget_key(&mut self, k: &str) {
        self.entries.remove(k);
    }

    /// Drop every entry for a file under `dir` — what removing a whole
    /// generated directory (a migration) leaves behind.
    pub fn forget_dir(&mut self, root: &Path, dir: &Path) {
        let Some(prefix) = key(root, dir) else { return };
        let prefix = format!("{prefix}/");
        self.entries.retain(|k, _| !k.starts_with(&prefix));
    }

    /// Write the manifest under `root`, removing it once it holds nothing.
    ///
    /// # Errors
    /// Filesystem failures, and a symlinked manifest path — writing or
    /// unlinking through one could reach outside the project.
    pub fn save(&self, root: &Path) -> std::io::Result<()> {
        let path = root.join(MANIFEST_PATH);
        // Before the removal below as well as the write: `unlink` resolves the
        // directories on the way to its target, so a symlinked `.autumn/` would
        // delete a file outside the project.
        refuse_symlink(root, &path)?;
        if self.entries.is_empty() {
            return match std::fs::remove_file(&path) {
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
                other => other,
            };
        }
        // A run lives as long as one file it wrote does.
        let live: std::collections::BTreeSet<String> = self
            .entries
            .values()
            .map(|e| run_id(&e.invocation))
            .collect();
        let runs = self
            .runs
            .iter()
            .filter(|(id, _)| live.contains(*id))
            .map(|(id, anchors)| (id.clone(), anchors.clone()))
            .collect();
        let body = toml::to_string(&ManifestFile {
            files: self.entries.clone(),
            runs,
        })
        .map_err(std::io::Error::other)?;
        let directory = path
            .parent()
            .ok_or_else(|| std::io::Error::other("manifest path has no parent directory"))?;
        std::fs::create_dir_all(directory)?;
        write_atomically(directory, &path, &body)
    }
}

/// Publish `body` at `path` through a temp file in the same directory, so a
/// concurrent reader sees either the old manifest or the new one, never a
/// half-written file.
///
/// This makes each save atomic, not the read-modify-write around it: two
/// generators running in one project at once can still lose one run's entries.
/// Accepted — the loser's files fall back to comparing against the current
/// render, which is what `destroy` did before the manifest existed.
fn write_atomically(directory: &Path, path: &Path, body: &str) -> std::io::Result<()> {
    use std::io::Write as _;

    // Created through ordinary `0o666` open semantics so the process umask
    // applies, as it does to the `fs::write` the generator itself uses;
    // `tempfile`'s own constructor would create `0600`.
    let mut temp = tempfile::Builder::new()
        .prefix(".autumn-generated-")
        .suffix(".tmp")
        .make_in(directory, |p| {
            std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(p)
        })?;
    temp.as_file_mut().write_all(body.as_bytes())?;
    temp.as_file_mut().sync_all()?;
    temp.persist(path).map_err(|e| e.error)?;
    Ok(())
}

/// Reject a manifest path reached through a symlink, at any component.
///
/// `symlink_metadata` does not follow, which is the point: a link's own
/// metadata is what says it is a link.
fn refuse_symlink(root: &Path, path: &Path) -> std::io::Result<()> {
    let mut cursor = root.to_path_buf();
    for component in MANIFEST_PATH.split('/') {
        cursor.push(component);
        match std::fs::symlink_metadata(&cursor) {
            // Not there yet — creating it is exactly what a first save does.
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            // Anything else is unknown, which is not the same as absent.
            Err(e) => return Err(e),
            Ok(m) if m.file_type().is_symlink() => {
                return Err(std::io::Error::other(format!(
                    "{} is a symlink; reading or writing through it could reach \
                     outside the project",
                    path.display()
                )));
            }
            Ok(_) => {}
        }
    }
    Ok(())
}

/// Whether the recorded key `k` is another spelling of `own`, the key of
/// `path` (issue #3382).
fn is_alias(root: &Path, k: &str, own: &str, path: &Path) -> bool {
    k.eq_ignore_ascii_case(own) && spelling::one_entry(&root.join(k), path)
}

/// `path` as a project-relative, forward-slashed manifest key.
///
/// Built from ordinary components only. `strip_prefix` is lexical, so
/// `<root>/../secret` strips to `../secret` — a key naming a file outside the
/// project. Rejecting anything but [`Component::Normal`] keeps every key
/// project-relative, and joining the parts spells a key the same way on Windows
/// as on Unix without rewriting a separator a filename may legitimately hold.
pub(super) fn key(root: &Path, path: &Path) -> Option<String> {
    let relative = path.strip_prefix(root).ok()?;
    let mut parts = Vec::new();
    for component in relative.components() {
        match component {
            Component::Normal(part) => parts.push(part.to_str()?),
            Component::Prefix(_)
            | Component::RootDir
            | Component::CurDir
            | Component::ParentDir => return None,
        }
    }
    (!parts.is_empty()).then(|| parts.join("/"))
}

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

    fn tmp() -> tempfile::TempDir {
        tempfile::TempDir::new().unwrap()
    }

    const OWNER: &str = "model\u{1f}Post\u{1f}title:String";

    #[test]
    fn records_and_reloads_a_digest() {
        let dir = tmp();
        let file = dir.path().join("src/models/post.rs");
        let mut p = Provenance::default();
        p.record(dir.path(), &file, text_digest("// model\n"), OWNER, None);
        p.save(dir.path()).unwrap();

        let reloaded = Provenance::load(dir.path());
        assert!(reloaded.is_ours(dir.path(), &file, &text_digest("// model\n"), OWNER));
        assert!(!reloaded.is_ours(dir.path(), &file, &text_digest("// edited\n"), OWNER));
    }

    #[test]
    fn a_different_command_never_owns_a_recorded_file() {
        let dir = tmp();
        let file = dir.path().join("src/models/post.rs");
        let mut p = Provenance::default();
        p.record(dir.path(), &file, text_digest("// model\n"), OWNER, None);

        assert!(!p.is_ours(
            dir.path(),
            &file,
            &text_digest("// model\n"),
            "model\u{1f}Post"
        ));
    }

    #[test]
    fn the_invocation_drops_the_verb_and_the_run_only_flags() {
        let normalize = |args: &[&str]| normalize_invocation(args.iter().map(|a| (*a).to_owned()));
        assert_eq!(
            normalize(&["generate", "model", "Post", "title:String"]),
            normalize(&["destroy", "model", "Post", "title:String", "--force"]),
        );
        assert_eq!(
            normalize(&["generate", "model", "Post", "--dry-run"]),
            normalize(&["generate", "model", "Post"]),
        );
        assert_ne!(
            normalize(&["generate", "model", "Post", "title:String"]),
            normalize(&["destroy", "model", "Post"]),
            "omitted fields are different arguments"
        );
        assert_ne!(
            normalize(&["new", "--starter", "saas", "app"]),
            normalize(&["destroy", "auth", "User"]),
            "a starter scaffold never owns a generator's output"
        );
    }

    #[test]
    fn arguments_cannot_collide_by_concatenation() {
        let normalize = |args: &[&str]| normalize_invocation(args.iter().map(|a| (*a).to_owned()));
        assert_ne!(
            normalize(&["model", "Post Tag"]),
            normalize(&["model", "Post", "Tag"])
        );
    }

    #[test]
    fn crlf_hashes_the_same_as_lf() {
        assert_eq!(text_digest("a\r\nb\r\n"), text_digest("a\nb\n"));
    }

    #[test]
    fn bytes_are_hashed_verbatim() {
        assert_ne!(bytes_digest(b"a\r\nb"), bytes_digest(b"a\nb"));
    }

    #[test]
    fn an_unrecorded_file_is_never_ours() {
        let dir = tmp();
        let p = Provenance::default();
        assert!(!p.is_ours(
            dir.path(),
            &dir.path().join("x.rs"),
            &text_digest(""),
            OWNER
        ));
    }

    #[test]
    fn a_path_outside_the_project_is_dropped() {
        let dir = tmp();
        let mut p = Provenance::default();
        p.record(
            dir.path(),
            Path::new("/etc/passwd"),
            text_digest(""),
            OWNER,
            None,
        );
        assert_eq!(p, Provenance::default());
    }

    #[test]
    fn a_path_escaping_through_parent_segments_is_dropped() {
        let dir = tmp();
        let mut p = Provenance::default();
        p.record(
            dir.path(),
            &dir.path().join("../secret.toml"),
            text_digest(""),
            OWNER,
            None,
        );
        assert_eq!(p, Provenance::default());
    }

    #[test]
    fn the_identity_does_not_depend_on_where_the_project_sits() {
        // The manifest is committed so a LATER CHECKOUT has a baseline. An
        // identity that named its absolute config paths would refuse every
        // clone that landed on a different path (Codex review of PR #2551).
        let here = tmp();
        let there = tmp();
        for root in [here.path(), there.path()] {
            std::fs::write(
                root.join(GENERATE_CONFIG_FILENAME),
                "[scaffold.Post]\nfields = [\"title:String\"]\n",
            )
            .unwrap();
        }

        assert_eq!(
            current_invocation(here.path()),
            current_invocation(there.path())
        );
    }

    #[test]
    fn a_crlf_checkout_of_the_config_is_the_same_input() {
        // `core.autocrlf` rewrites the committed recipe on checkout. It parses
        // identically as TOML, so it must not drop the baseline — the same rule
        // the generated-file digests follow (Codex review of PR #2551).
        let lf = tmp();
        let crlf = tmp();
        std::fs::write(
            lf.path().join(GENERATE_CONFIG_FILENAME),
            "[scaffold.Post]\nfields = [\"title:String\"]\n",
        )
        .unwrap();
        std::fs::write(
            crlf.path().join(GENERATE_CONFIG_FILENAME),
            "[scaffold.Post]\r\nfields = [\"title:String\"]\r\n",
        )
        .unwrap();

        assert_eq!(
            current_invocation(lf.path()),
            current_invocation(crlf.path())
        );
    }

    #[test]
    fn the_identity_still_moves_when_the_config_contents_differ() {
        let here = tmp();
        let there = tmp();
        std::fs::write(
            here.path().join(GENERATE_CONFIG_FILENAME),
            "[scaffold.Post]\n",
        )
        .unwrap();
        std::fs::write(
            there.path().join(GENERATE_CONFIG_FILENAME),
            "[scaffold.Tag]\n",
        )
        .unwrap();

        assert_ne!(
            current_invocation(here.path()),
            current_invocation(there.path())
        );
    }

    #[test]
    fn an_absent_config_is_distinguishable_from_a_present_one() {
        let absent = tmp();
        let present = tmp();
        std::fs::write(
            present.path().join(GENERATE_CONFIG_FILENAME),
            "[scaffold.Post]\n",
        )
        .unwrap();

        assert_ne!(
            current_invocation(absent.path()),
            current_invocation(present.path())
        );
    }

    /// Clears the database environment so a project's own `autumn.toml`
    /// decides the backend, matching the emit tests' `no_db_env`.
    fn no_db_env<R>(f: impl FnOnce() -> R) -> R {
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            f,
        )
    }

    #[test]
    fn the_identity_moves_with_the_database_backend() {
        // The backend appears in no argument, and it decides the SQL a
        // migration holds and the `schema.rs` block a `SchemaTable` revert
        // expects — so a project moved between SQLite and Postgres must lose
        // its baseline rather than half-destroy (Codex review of PR #2551).
        let sqlite = tmp();
        let postgres = tmp();
        std::fs::write(
            sqlite.path().join("autumn.toml"),
            "[database]\nurl = \"sqlite://app.db\"\n",
        )
        .unwrap();
        std::fs::write(
            postgres.path().join("autumn.toml"),
            "[database]\nurl = \"postgres://localhost/app\"\n",
        )
        .unwrap();

        no_db_env(|| {
            assert_ne!(
                current_invocation(sqlite.path()),
                current_invocation(postgres.path())
            );
        });
    }

    #[test]
    fn two_projects_on_the_same_backend_share_an_identity() {
        let here = tmp();
        let there = tmp();
        for root in [here.path(), there.path()] {
            std::fs::write(
                root.join("autumn.toml"),
                "[database]\nurl = \"sqlite://app.db\"\n",
            )
            .unwrap();
        }

        no_db_env(|| {
            assert_eq!(
                current_invocation(here.path()),
                current_invocation(there.path())
            );
        });
    }

    #[test]
    fn a_malformed_manifest_reads_as_no_baseline() {
        let dir = tmp();
        std::fs::create_dir_all(dir.path().join(".autumn")).unwrap();
        std::fs::write(dir.path().join(MANIFEST_PATH), "not : toml [[[").unwrap();
        assert_eq!(Provenance::load(dir.path()), Provenance::default());
    }

    #[test]
    fn saving_an_empty_manifest_removes_it() {
        let dir = tmp();
        let file = dir.path().join("a.rs");
        let mut p = Provenance::default();
        p.record(dir.path(), &file, text_digest("x"), OWNER, None);
        p.save(dir.path()).unwrap();
        assert!(dir.path().join(MANIFEST_PATH).is_file());

        p.forget(dir.path(), &file);
        p.save(dir.path()).unwrap();
        assert!(!dir.path().join(MANIFEST_PATH).exists());
    }

    #[test]
    fn forget_dir_drops_only_that_directory() {
        let dir = tmp();
        let mut p = Provenance::default();
        p.record(
            dir.path(),
            &dir.path().join("migrations/a/up.sql"),
            "1".to_owned(),
            OWNER,
            None,
        );
        p.record(
            dir.path(),
            &dir.path().join("migrations/ab/up.sql"),
            "2".to_owned(),
            OWNER,
            None,
        );
        p.forget_dir(dir.path(), &dir.path().join("migrations/a"));

        assert!(!p.contains("migrations/a/up.sql"));
        assert!(p.contains("migrations/ab/up.sql"));
    }

    #[test]
    fn a_scope_survives_a_save_and_load() {
        let dir = tmp();
        let owned = dir.path().join("src/a.rs");
        let shared = dir.path().join("templates/_layout.html");
        let mut p = Provenance::default();
        p.record(
            dir.path(),
            &owned,
            "1".to_owned(),
            OWNER,
            Some(Scope::Owned),
        );
        p.record(
            dir.path(),
            &shared,
            "2".to_owned(),
            OWNER,
            Some(Scope::Shared),
        );
        p.save(dir.path()).unwrap();

        let reloaded = Provenance::load(dir.path());
        let mut seen: Vec<_> = reloaded.recorded_by(OWNER).collect();
        seen.sort_by_key(|r| r.key);
        assert_eq!(
            seen,
            vec![
                Recorded {
                    key: "src/a.rs",
                    digest: "1",
                    scope: Some(Scope::Owned)
                },
                Recorded {
                    key: "templates/_layout.html",
                    digest: "2",
                    scope: Some(Scope::Shared)
                },
            ]
        );
    }

    #[test]
    fn an_entry_without_a_scope_writes_no_scope_key() {
        // A 0.8.0 CLI reads this manifest too. It must see the shape it wrote.
        let dir = tmp();
        let mut p = Provenance::default();
        p.record(
            dir.path(),
            &dir.path().join("a.rs"),
            "1".to_owned(),
            OWNER,
            None,
        );
        p.save(dir.path()).unwrap();
        let text = std::fs::read_to_string(dir.path().join(MANIFEST_PATH)).unwrap();
        assert!(!text.contains("scope"), "{text}");
    }

    #[test]
    fn a_legacy_entry_loads_with_no_scope() {
        let dir = tmp();
        std::fs::create_dir_all(dir.path().join(".autumn")).unwrap();
        std::fs::write(
            dir.path().join(MANIFEST_PATH),
            "[files.\"src/a.rs\"]\ndigest = \"1\"\ninvocation = \"x\"\n",
        )
        .unwrap();
        let p = Provenance::load(dir.path());
        let seen: Vec<_> = p.recorded_by("x").collect();
        assert_eq!(
            seen,
            vec![Recorded {
                key: "src/a.rs",
                digest: "1",
                scope: None
            }]
        );
    }

    #[test]
    fn an_unknown_scope_reads_as_none_and_keeps_the_other_entries() {
        let dir = tmp();
        std::fs::create_dir_all(dir.path().join(".autumn")).unwrap();
        std::fs::write(
            dir.path().join(MANIFEST_PATH),
            "[files.\"a.rs\"]\ndigest = \"1\"\ninvocation = \"x\"\nscope = \"Owned\"\n\n\
             [files.\"b.rs\"]\ndigest = \"2\"\ninvocation = \"x\"\nscope = 7\n\n\
             [files.\"c.rs\"]\ndigest = \"3\"\ninvocation = \"x\"\nscope = \"owned\"\n",
        )
        .unwrap();
        let p = Provenance::load(dir.path());
        let mut seen: Vec<_> = p.recorded_by("x").map(|r| (r.key, r.scope)).collect();
        seen.sort_unstable();
        assert_eq!(
            seen,
            vec![("a.rs", None), ("b.rs", None), ("c.rs", Some(Scope::Owned))]
        );
    }

    #[test]
    fn recorded_by_lists_only_that_invocation() {
        let dir = tmp();
        let mut p = Provenance::default();
        p.record(
            dir.path(),
            &dir.path().join("a.rs"),
            "1".to_owned(),
            OWNER,
            None,
        );
        p.record(
            dir.path(),
            &dir.path().join("b.rs"),
            "2".to_owned(),
            "other",
            None,
        );
        let keys: Vec<_> = p.recorded_by(OWNER).map(|r| r.key).collect();
        assert_eq!(keys, vec!["a.rs"]);
    }

    fn anchor(path: &str, revert: &str) -> RevertAnchor {
        RevertAnchor {
            path: path.to_owned(),
            revert: revert.to_owned(),
        }
    }

    fn recorded_run(dir: &Path, anchors: Vec<RevertAnchor>) -> Provenance {
        let mut p = Provenance::default();
        p.record(dir, &dir.join("a.rs"), text_digest("x"), OWNER, None);
        p.record_reverts(OWNER, anchors);
        p.save(dir).unwrap();
        Provenance::load(dir)
    }

    #[test]
    fn reverts_survive_a_save_and_load() {
        let dir = tmp();
        let a = anchor("i18n/en.ftl", "I18nFtlKeys(Post)");
        let p = recorded_run(dir.path(), vec![a.clone()]);
        std::fs::create_dir_all(dir.path().join("i18n")).unwrap();
        std::fs::write(dir.path().join("i18n/en.ftl"), "").unwrap();

        let moved = anchor("elsewhere", "I18nFtlKeys(Post)");
        assert_eq!(p.dropped_reverts(dir.path(), OWNER, &[moved]), vec![a]);
    }

    #[test]
    fn a_revert_that_vanished_is_a_skip_not_a_drop() {
        let dir = tmp();
        let p = recorded_run(
            dir.path(),
            vec![anchor(
                "autumn.toml",
                "SubmitTokenValidateExempt(posts, validate)",
            )],
        );
        std::fs::write(dir.path().join("autumn.toml"), "").unwrap();

        // The plan holds no revert of that kind: the append was a no-op.
        assert!(
            p.dropped_reverts(dir.path(), OWNER, &[anchor("src/main.rs", "ModDecl(post)")])
                .is_empty()
        );
    }

    #[test]
    fn a_revert_that_moved_within_its_kind_is_a_drop() {
        let dir = tmp();
        let old = anchor("i18n/en.ftl", "I18nFtlKeys(Post)");
        let p = recorded_run(dir.path(), vec![old.clone()]);
        std::fs::create_dir_all(dir.path().join("i18n")).unwrap();
        std::fs::write(dir.path().join("i18n/en.ftl"), "").unwrap();

        assert_eq!(
            p.dropped_reverts(
                dir.path(),
                OWNER,
                &[anchor("translations/en.ftl", "I18nFtlKeys(Post)")]
            ),
            vec![old]
        );
    }

    #[test]
    fn a_recorded_path_that_leaves_the_project_is_ignored() {
        let dir = tmp();
        let outside = tmp();
        std::fs::write(outside.path().join("x"), "").unwrap();
        let absolute = outside.path().join("x").to_string_lossy().into_owned();
        let parent = format!(
            "../{}/x",
            outside.path().file_name().unwrap().to_string_lossy()
        );
        for path in [absolute, parent] {
            let p = recorded_run(dir.path(), vec![anchor(&path, "A(x)")]);
            let planned = [anchor("elsewhere", "A(y)")];
            assert!(
                p.dropped_reverts(dir.path(), OWNER, &planned).is_empty(),
                "{path}"
            );
        }
    }

    #[test]
    fn the_kind_is_the_text_before_the_first_paren() {
        assert_eq!(anchor("a", "ModDecl(post)").kind(), "ModDecl");
        assert_eq!(
            anchor("a", "PwaMainRsInjection").kind(),
            "PwaMainRsInjection"
        );
    }

    #[test]
    fn forgetting_a_run_leaves_another_invocations_run() {
        let dir = tmp();
        let mut p = recorded_run(dir.path(), vec![anchor("a", "A(x)")]);
        p.record(
            dir.path(),
            &dir.path().join("b.rs"),
            "2".to_owned(),
            "other",
            None,
        );
        p.record_reverts("other", vec![anchor("b", "B(y)")]);
        p.forget_run(OWNER);
        p.save(dir.path()).unwrap();

        let text = std::fs::read_to_string(dir.path().join(MANIFEST_PATH)).unwrap();
        assert!(text.contains("B(y)") && !text.contains("A(x)"), "{text}");
    }

    #[test]
    fn a_recorded_revert_that_is_still_planned_is_not_dropped() {
        let dir = tmp();
        let a = anchor("i18n/en.ftl", "I18nFtlKeys(Post)");
        let p = recorded_run(dir.path(), vec![a.clone()]);
        std::fs::create_dir_all(dir.path().join("i18n")).unwrap();
        std::fs::write(dir.path().join("i18n/en.ftl"), "").unwrap();

        assert!(p.dropped_reverts(dir.path(), OWNER, &[a]).is_empty());
    }

    #[test]
    fn an_extra_planned_revert_is_not_a_drop() {
        let dir = tmp();
        let a = anchor("i18n/en.ftl", "I18nFtlKeys(Post)");
        let extra = anchor("i18n/fr.ftl", "I18nFtlKeys(Post)");
        let p = recorded_run(dir.path(), vec![a.clone()]);
        std::fs::create_dir_all(dir.path().join("i18n")).unwrap();
        std::fs::write(dir.path().join("i18n/en.ftl"), "").unwrap();

        assert!(p.dropped_reverts(dir.path(), OWNER, &[a, extra]).is_empty());
    }

    #[test]
    fn a_dropped_revert_whose_target_is_gone_is_not_reported() {
        let dir = tmp();
        let p = recorded_run(dir.path(), vec![anchor("i18n/en.ftl", "I18nFtlKeys(Post)")]);

        assert!(p.dropped_reverts(dir.path(), OWNER, &[]).is_empty());
    }

    #[test]
    fn another_invocations_reverts_are_not_this_ones() {
        let dir = tmp();
        let p = recorded_run(dir.path(), vec![anchor("i18n/en.ftl", "I18nFtlKeys(Post)")]);
        std::fs::create_dir_all(dir.path().join("i18n")).unwrap();
        std::fs::write(dir.path().join("i18n/en.ftl"), "").unwrap();

        let moved = [anchor("elsewhere", "I18nFtlKeys(Post)")];
        assert!(p.dropped_reverts(dir.path(), "other", &moved).is_empty());
    }

    #[test]
    fn a_manifest_without_runs_records_no_reverts() {
        let dir = tmp();
        std::fs::create_dir_all(dir.path().join(".autumn")).unwrap();
        std::fs::write(
            dir.path().join(MANIFEST_PATH),
            "[files.\"a.rs\"]\ndigest = \"1\"\ninvocation = \"x\"\n",
        )
        .unwrap();
        let p = Provenance::load(dir.path());

        assert!(p.dropped_reverts(dir.path(), "x", &[]).is_empty());
    }

    #[test]
    fn a_run_with_no_entries_is_pruned_on_save() {
        let dir = tmp();
        let mut p = recorded_run(dir.path(), vec![anchor("a", "A")]);
        p.forget(dir.path(), &dir.path().join("a.rs"));
        p.record(
            dir.path(),
            &dir.path().join("b.rs"),
            "2".to_owned(),
            "other",
            None,
        );
        p.save(dir.path()).unwrap();

        let text = std::fs::read_to_string(dir.path().join(MANIFEST_PATH)).unwrap();
        assert!(!text.contains("runs"), "{text}");
    }

    #[test]
    fn a_run_without_reverts_writes_no_runs_key() {
        let dir = tmp();
        let _ = recorded_run(dir.path(), Vec::new());

        let text = std::fs::read_to_string(dir.path().join(MANIFEST_PATH)).unwrap();
        assert!(!text.contains("runs"), "{text}");
    }

    #[test]
    fn a_later_record_adds_to_the_earlier_one() {
        let dir = tmp();
        let mut p = recorded_run(dir.path(), vec![anchor("old", "Old(a)")]);
        std::fs::write(dir.path().join("old"), "").unwrap();
        p.record_reverts(OWNER, vec![anchor("new", "Old(b)")]);

        assert_eq!(
            p.dropped_reverts(dir.path(), OWNER, &[anchor("new", "Old(b)")]),
            vec![anchor("old", "Old(a)")],
            "the first run's edit is still in its file"
        );
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_manifest_is_refused() {
        let dir = tmp();
        let outside = tmp();
        std::fs::create_dir_all(dir.path().join(".autumn")).unwrap();
        std::os::unix::fs::symlink(
            outside.path().join("escaped.toml"),
            dir.path().join(MANIFEST_PATH),
        )
        .unwrap();

        let mut p = Provenance::default();
        p.record(
            dir.path(),
            &dir.path().join("a.rs"),
            text_digest("x"),
            OWNER,
            None,
        );

        assert!(p.save(dir.path()).is_err());
        assert!(!outside.path().join("escaped.toml").exists());
    }

    /// Write `contents` at `rel` and record it for [`OWNER`].
    fn written(p: &mut Provenance, root: &Path, rel: &str, contents: &str) -> PathBuf {
        let path = root.join(rel);
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, contents).unwrap();
        p.record(
            root,
            &path,
            text_digest(contents),
            OWNER,
            Some(Scope::Owned),
        );
        path
    }

    #[test]
    fn a_case_only_alias_is_ours_only_when_it_is_one_entry() {
        // Issue #3382: a template renamed `Foo.rs` to `foo.rs`.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        let one_entry = new.exists();
        let digest = text_digest("// v1\n");

        assert_eq!(p.is_ours(root, &new, &digest, OWNER), one_entry);
        assert_eq!(p.was_written(root, &new, &digest), one_entry);
        assert!(!p.is_ours(root, &new, &digest, "other"), "another command");
        let aliases: Vec<String> = if one_entry {
            vec!["src/Foo.rs".to_owned()]
        } else {
            Vec::new()
        };
        assert_eq!(p.keys_for(root, &new), aliases);
        assert_eq!(p.keys_for(root, &old), vec!["src/Foo.rs".to_owned()]);
    }

    #[test]
    fn a_second_file_with_a_case_only_name_is_not_an_alias() {
        // A case-sensitive host holds two files. Each keeps its own entry.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        if new.exists() {
            return; // case-insensitive: one entry, not two.
        }
        std::fs::write(&new, "// v1\n").unwrap();
        let digest = text_digest("// v1\n");

        assert!(!p.is_ours(root, &new, &digest, OWNER));
        assert!(!p.was_written(root, &new, &digest));
        assert!(p.keys_for(root, &new).is_empty());
        p.forget(root, &new);
        assert!(p.contains("src/Foo.rs"));
    }

    #[test]
    fn a_hard_linked_case_only_name_is_not_an_alias() {
        // Two hard-linked names are two entries to remove.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        if new.exists() || std::fs::hard_link(&old, &new).is_err() {
            return; // case-insensitive, or no hard links: nothing to test.
        }

        assert!(!p.is_ours(root, &new, &text_digest("// v1\n"), OWNER));
        assert!(p.keys_for(root, &new).is_empty());
    }

    #[test]
    fn forget_drops_a_case_only_alias_while_the_file_exists() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        if !new.exists() {
            return; // case-sensitive: `foo.rs` is no alias.
        }

        p.forget(root, &new);

        assert!(!p.contains("src/Foo.rs"));
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_case_only_name_is_not_an_alias() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        if new.exists() {
            return; // case-insensitive: one name, no room for a link.
        }
        std::os::unix::fs::symlink(&old, &new).unwrap();

        assert!(!p.is_ours(root, &new, &text_digest("// v1\n"), OWNER));
        assert!(p.keys_for(root, &new).is_empty());
    }

    #[test]
    fn the_exact_entry_decides_when_both_spellings_are_recorded() {
        // An older manifest can hold `Foo.rs` and `foo.rs` for one file. The
        // newest writer is under the exact key, so only it owns the file.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        if !new.exists() {
            return; // case-sensitive: two files, see the tests above.
        }
        p.entries.insert(
            "src/foo.rs".to_owned(),
            Entry {
                digest: text_digest("// v1\n"),
                invocation: "newer".to_owned(),
                scope: None,
            },
        );
        let digest = text_digest("// v1\n");

        assert!(p.is_ours(root, &new, &digest, "newer"));
        assert!(!p.is_ours(root, &new, &digest, OWNER), "a stale alias");
        let mut keys = p.keys_for(root, &new);
        keys.sort();
        assert_eq!(keys, vec!["src/Foo.rs".to_owned(), "src/foo.rs".to_owned()]);
    }

    #[test]
    fn record_replaces_the_entry_of_another_spelling() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        let one_entry = new.exists();
        if !one_entry {
            std::fs::write(&new, "// v2\n").unwrap(); // a second file.
        }

        p.record(root, &new, text_digest("// v2\n"), OWNER, None);

        assert!(p.contains("src/foo.rs"));
        assert_eq!(p.contains("src/Foo.rs"), !one_entry);
    }

    #[test]
    fn forget_after_the_delete_finds_only_the_exact_key() {
        // Why `destroy` reads the keys before it deletes a file.
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        let old = written(&mut p, root, "src/Foo.rs", "// v1\n");
        let new = root.join("src/foo.rs");
        std::fs::remove_file(&old).unwrap();

        p.forget(root, &new);
        assert!(p.contains("src/Foo.rs"));
        p.forget_key("src/Foo.rs");
        assert!(!p.contains("src/Foo.rs"));
    }

    #[test]
    fn forget_key_drops_only_that_key() {
        let dir = tmp();
        let root = dir.path();
        let mut p = Provenance::default();
        written(&mut p, root, "src/a.rs", "a");
        written(&mut p, root, "src/b.rs", "b");

        p.forget_key("src/a.rs");

        assert!(!p.contains("src/a.rs"));
        assert!(p.contains("src/b.rs"));
    }
}