rustango 0.61.13

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
//! Generate the next migration file from a registry diff.
//!
//! [`make_migrations`] is the entry point. It loads the latest
//! snapshot in `dir`, builds the current one from the model registry,
//! diffs them and writes a new file. [`make_migrations_from`] takes
//! the current snapshot as an argument, so a test can pass a fixture
//! instead of using the global registry.
//!
//! Auto-naming heuristic (used when `name_override` is `None`):
//!
//! | shape of changes                       | suffix                    |
//! |----------------------------------------|---------------------------|
//! | empty dir + all `CreateTable`          | `initial`                 |
//! | single `CreateTable("foo")`            | `create_foo`              |
//! | single `DropTable("foo")`              | `drop_foo`                |
//! | single `AddColumn { table, column }`   | `add_<column>_to_<table>` |
//! | single `DropColumn { table, column }`  | `drop_<column>_from_<table>` |
//! | anything else                          | `auto`                    |

use std::path::Path;

use super::diff::{detect_changes, detect_unsupported_field_changes, SchemaChange};
use super::error::MigrateError;
use super::file::{self, extract_index, Migration, Operation};
use super::snapshot::SchemaSnapshot;

/// What `makemigrations` does when a table loses a column and gains one
/// of the same type: likely a renamed field, whose drop + add deletes the
/// column's data.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum DropAndAdd {
    /// Write nothing; name the columns and the `RenameColumn` route.
    #[default]
    Refuse,
    /// Write the drop + add as asked (`makemigrations --drop-and-add`).
    Allow,
}

/// Produce the next migration file in `dir` by diffing the inventory
/// registry against the latest snapshot on disk.
///
/// Returns `Ok(None)` if the registry matches the latest snapshot (no
/// migration needed).
///
/// # Errors
/// Anything [`make_migrations_from`] can return.
pub fn make_migrations(
    dir: &Path,
    name_override: Option<&str>,
) -> Result<Option<Migration>, MigrateError> {
    make_migrations_with(dir, name_override, DropAndAdd::Refuse)
}

/// [`make_migrations`] with an explicit [`DropAndAdd`] policy.
///
/// # Errors
/// As [`make_migrations`].
pub fn make_migrations_with(
    dir: &Path,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Option<Migration>, MigrateError> {
    check_models()?;
    let current = SchemaSnapshot::from_registry();
    make_migrations_from_with(dir, &current, name_override, drops)
}

/// [`make_migrations`] for one scope. Diffs only the models whose
/// [`crate::core::ModelSchema::scope`] matches, and tags the new file
/// with the matching [`super::MigrationScope`]. This keeps registry
/// tables such as `Org` out of tenant-scoped migrations.
///
/// Both the current snapshot and the prior on-disk one are filtered
/// to `scope` first. Filtering the prior one matters: older bootstrap
/// migrations hold every framework table in one snapshot whatever
/// their scope. A table no longer in the inventory counts as
/// [`crate::core::ModelScope::Tenant`]; see
/// [`SchemaSnapshot::filtered_to_scope`].
///
/// Returns `Ok(None)` when nothing in this scope changed.
///
/// # Errors
/// As [`make_migrations_from`].
pub fn make_migrations_for_scope(
    dir: &Path,
    scope: crate::core::ModelScope,
    name_override: Option<&str>,
) -> Result<Option<Migration>, MigrateError> {
    make_migrations_for_scope_with(dir, scope, name_override, DropAndAdd::Refuse)
}

/// [`make_migrations_for_scope`] with an explicit [`DropAndAdd`] policy.
///
/// # Errors
/// As [`make_migrations_for_scope`].
pub fn make_migrations_for_scope_with(
    dir: &Path,
    scope: crate::core::ModelScope,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Option<Migration>, MigrateError> {
    check_models()?;
    let current = SchemaSnapshot::from_registry_for_scope(scope);
    let migration_scope = migration_scope(scope);
    make_migrations_scoped_with(dir, &current, scope, migration_scope, name_override, drops)
}

/// [`make_migrations`] for one app. Diffs only the models whose app
/// label is `app` and writes to `<project_root>/<app>/migrations/`.
/// This backs `manage makemigrations <app>`.
///
/// `project_root` is usually the project's `src/`. Returns `Ok(None)`
/// when nothing changed or no model carries that app label.
///
/// # Errors
/// Anything [`make_migrations_from`] can return, plus
/// [`MigrateError::Io`] if the per-app migrations dir can't be
/// created.
pub fn make_migrations_for_app(
    project_root: &Path,
    app: &str,
    name_override: Option<&str>,
) -> Result<Option<Migration>, MigrateError> {
    make_migrations_for_app_with(project_root, app, name_override, DropAndAdd::Refuse)
}

/// [`make_migrations_for_app`] with an explicit [`DropAndAdd`] policy.
///
/// # Errors
/// As [`make_migrations_for_app`].
pub fn make_migrations_for_app_with(
    project_root: &Path,
    app: &str,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Option<Migration>, MigrateError> {
    let app_dir = project_root.join(app).join("migrations");
    if !app_dir.exists() {
        std::fs::create_dir_all(&app_dir)?;
    }
    check_models()?;
    let current = SchemaSnapshot::from_registry_for_app(app);
    make_migrations_from_with(&app_dir, &current, name_override, drops)
}

/// [`make_migrations_from`] for one scope, used by
/// [`make_migrations_for_scope`]. Builds the previous snapshot from
/// prior migrations of the same `migration_scope`, then filters it to
/// `model_scope` so an older bootstrap migration holding every
/// framework table does not pollute the diff.
///
/// # Errors
/// As [`make_migrations_from`].
pub fn make_migrations_scoped(
    dir: &Path,
    current: &SchemaSnapshot,
    model_scope: crate::core::ModelScope,
    migration_scope: super::MigrationScope,
    name_override: Option<&str>,
) -> Result<Option<Migration>, MigrateError> {
    make_migrations_scoped_with(
        dir,
        current,
        model_scope,
        migration_scope,
        name_override,
        DropAndAdd::Refuse,
    )
}

/// [`make_migrations_scoped`] with an explicit [`DropAndAdd`] policy.
///
/// # Errors
/// As [`make_migrations_scoped`].
pub fn make_migrations_scoped_with(
    dir: &Path,
    current: &SchemaSnapshot,
    model_scope: crate::core::ModelScope,
    migration_scope: super::MigrationScope,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Option<Migration>, MigrateError> {
    let prior = file::list_dir(dir)?;
    let Some(mig) = plan_scoped(
        &prior,
        current,
        model_scope,
        migration_scope,
        name_override,
        drops,
    )?
    else {
        return Ok(None);
    };
    write_planned(dir, &mig)?;
    Ok(Some(mig))
}

/// The files a flagless `makemigrations` would write into `dir`, unwritten:
/// one per scope in a tenancy project, else one. Empty when models match.
///
/// # Errors
/// As [`make_migrations`].
pub(crate) fn planned_migrations(
    dir: &Path,
    tenancy: bool,
) -> Result<Vec<Migration>, MigrateError> {
    check_models()?;
    let prior = file::list_dir(dir)?;
    if !tenancy {
        return Ok(plan_from(
            &prior,
            &SchemaSnapshot::from_registry(),
            None,
            DropAndAdd::Allow,
        )?
        .into_iter()
        .collect());
    }
    Ok(
        plan_scopes(&prior, &registry_scopes(), None, DropAndAdd::Allow)?
            .into_iter()
            .flatten()
            .collect(),
    )
}

/// Today's models split by scope, registry first, as tenancy writes them.
fn registry_scopes() -> [(crate::core::ModelScope, SchemaSnapshot); 2] {
    use crate::core::ModelScope;
    [ModelScope::Registry, ModelScope::Tenant]
        .map(|scope| (scope, SchemaSnapshot::from_registry_for_scope(scope)))
}

/// One file per scope after `prior`, unwritten. Each planned file joins
/// the chain, so the next scope numbers after it.
fn plan_scopes(
    prior: &[Migration],
    scopes: &[(crate::core::ModelScope, SchemaSnapshot)],
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Vec<Option<Migration>>, MigrateError> {
    let mut chain = prior.to_vec();
    let mut out = Vec::new();
    for (scope, current) in scopes {
        let mig = plan_scoped(
            &chain,
            current,
            *scope,
            migration_scope(*scope),
            name_override,
            drops,
        )?;
        chain.extend(mig.clone());
        out.push(mig);
    }
    Ok(out)
}

fn migration_scope(scope: crate::core::ModelScope) -> super::MigrationScope {
    match scope {
        crate::core::ModelScope::Registry => super::MigrationScope::Registry,
        crate::core::ModelScope::Tenant => super::MigrationScope::Tenant,
    }
}

/// What a flagless tenancy `makemigrations` wrote: the framework's system
/// steps, then one app file (or none) per scope, registry first.
#[derive(Debug)]
pub(crate) struct TenancyRun {
    pub(crate) system: Vec<(crate::core::ModelScope, Migration)>,
    pub(crate) app: Vec<(crate::core::ModelScope, Option<Migration>)>,
}

/// A flagless tenancy `makemigrations`: every scope's file is planned
/// before any is written, so a refused scope leaves both dirs as they were.
///
/// # Errors
/// As [`make_migrations`].
pub(crate) fn make_migrations_tenancy(
    dir: &Path,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<TenancyRun, MigrateError> {
    check_models()?;
    make_tenancy_from(dir, &registry_scopes(), name_override, drops)
}

/// [`make_migrations_tenancy`] with the app snapshots passed in.
fn make_tenancy_from(
    dir: &Path,
    scopes: &[(crate::core::ModelScope, SchemaSnapshot)],
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<TenancyRun, MigrateError> {
    let project_root = dir.parent().unwrap_or(dir);
    let sys_dir = project_root.join("system").join("migrations");
    let mut sys_chain = if sys_dir.exists() {
        file::list_dir(&sys_dir)?
    } else {
        Vec::new()
    };
    let mut system = Vec::new();
    for scope in [
        crate::core::ModelScope::Registry,
        crate::core::ModelScope::Tenant,
    ] {
        if let Some(m) = plan_system_step(scope, name_override, &sys_chain)? {
            sys_chain.push(m.clone());
            system.push((scope, m));
        }
    }
    let app = plan_scopes(&file::list_dir(dir)?, scopes, name_override, drops)?;
    for (_, m) in &system {
        write_planned(&sys_dir, m)?;
    }
    for m in app.iter().flatten() {
        write_planned(dir, m)?;
    }
    Ok(TenancyRun {
        system,
        app: scopes.iter().map(|(s, _)| *s).zip(app).collect(),
    })
}

fn write_planned(dir: &Path, mig: &Migration) -> Result<(), MigrateError> {
    if !dir.exists() {
        std::fs::create_dir_all(dir)?;
    }
    file::write(&dir.join(format!("{}.json", mig.name)), mig)
}

/// The file [`make_migrations_scoped`] would write after `prior`, unwritten.
fn plan_scoped(
    prior: &[Migration],
    current: &SchemaSnapshot,
    model_scope: crate::core::ModelScope,
    migration_scope: super::MigrationScope,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Option<Migration>, MigrateError> {
    // Each scope has its own chain, so keep only this scope's prior
    // migrations. Both chains start at `0001_`, since each has its
    // own head.
    let prior_scoped: Vec<&Migration> = prior
        .iter()
        .filter(|m| m.scope == migration_scope)
        .collect();
    refuse_branched(&prior_scoped)?;
    // The last migration's snapshot is the obvious baseline, but it
    // is incomplete when a scope has more than one head. For example
    // `init-tenancy` writes its own `0001_` beside the user's, and
    // later user migrations chain off the user's head only, so the
    // framework tables fall out of the baseline. The diff then
    // re-emits `CreateTable` for them and the run fails with
    // `relation already exists`.
    //
    // So build the baseline in two extra steps:
    //   1. Fold in the snapshots of side-chain heads.
    //   2. Add every `rustango_*` table the registry knows. The
    //      framework owns that prefix, so an app migration must
    //      never create one of those tables.
    let mut prev_snapshot = prior_scoped
        .last()
        .map_or_else(empty_snapshot, |m| effective_snapshot(&prior_scoped, m));
    let in_chain = chain_membership(&prior_scoped);
    for m in &prior_scoped {
        if !in_chain.contains(m.name.as_str()) {
            fold_in_missing_tables(&mut prev_snapshot, &m.snapshot);
        }
    }
    fold_in_framework_tables(&mut prev_snapshot, current);
    let prev_snapshot = prev_snapshot.filtered_to_scope(model_scope);
    let mut current = current.clone();
    current.keep_unmanaged(&prev_snapshot);
    let current = &current;
    let prev_name = prior_scoped.last().map(|m| m.name.clone());
    // Numbering looks at the whole directory, so a tenant `0002` and
    // a registry `0002` cannot collide as filenames.
    let next_index = prior
        .last()
        .and_then(|m| extract_index(&m.name))
        .map_or(1, |n| n + 1);

    let unsupported = detect_unsupported_field_changes(&prev_snapshot, current);
    if !unsupported.is_empty() {
        return Err(MigrateError::Validation(format!(
            "field metadata changed in a way no migration operation expresses \
             yet; write these changes by hand:\n  - {}",
            unsupported.join("\n  - "),
        )));
    }

    refuse_unkeyed_composite_fks(&prev_snapshot, current)?;
    warn_untracked_table_comments(current);
    let changes = detect_changes(&prev_snapshot, current);
    if changes.is_empty() {
        return Ok(None);
    }
    check_drops(&prev_snapshot, current, &changes, drops)?;

    let suffix = name_override.map_or_else(
        || auto_name(&changes, prior_scoped.is_empty()),
        str::to_owned,
    );
    let name = format!("{next_index:04}_{suffix}");
    let created_at = chrono::Utc::now().to_rfc3339();

    Ok(Some(Migration {
        name,
        created_at,
        prev: prev_name,
        atomic: true,
        scope: migration_scope,
        replaces: Vec::new(),
        merges: Vec::new(),
        snapshot: current.clone(),
        forward: changes.into_iter().map(Operation::Schema).collect(),
    }))
}

/// A composite FK must point at a primary or unique key; catch it here,
/// not when PG refuses the written migration.
fn refuse_unkeyed_composite_fks(
    prev: &SchemaSnapshot,
    current: &SchemaSnapshot,
) -> Result<(), MigrateError> {
    let bad = current.unkeyed_composite_fks(prev);
    if bad.is_empty() {
        return Ok(());
    }
    Err(MigrateError::Validation(format!(
        "composite foreign keys need a unique target:\n  - {}",
        bad.join("\n  - ")
    )))
}

/// Warn for every dropped column; refuse a drop beside a same-type add
/// unless `drops` allows it, as it empties what is likely a renamed field.
fn check_drops(
    prev: &SchemaSnapshot,
    current: &SchemaSnapshot,
    changes: &[SchemaChange],
    drops: DropAndAdd,
) -> Result<(), MigrateError> {
    let renames = super::diff::suspected_renames(prev, current, changes);
    if drops == DropAndAdd::Refuse && !renames.is_empty() {
        let pairs: Vec<String> = renames
            .iter()
            .map(|(t, old, new)| format!("`{t}.{old}` dropped, `{t}.{new}` added"))
            .collect();
        let (t, old, new) = &renames[0];
        return Err(MigrateError::Validation(format!(
            "makemigrations: refused, a renamed field would lose its data:\n  - {}\n\
             A drop + add deletes every value in the old column. To keep the data, write \
             the rename by hand:\n  \
             cargo run -- makemigrations --empty rename_{old}\n  \
             then put {{\"schema\": {{\"RenameColumn\": {{\"table\": \"{t}\", \
             \"old_column\": \"{old}\", \"new_column\": \"{new}\"}}}}}} in its `forward` \
             and run makemigrations again.\n\
             To drop the old column and add the new one on purpose, run \
             `makemigrations --drop-and-add`.",
            pairs.join("\n  - "),
        )));
    }
    for w in super::diff::irreversible_drops(prev, changes) {
        tracing::warn!(target: "rustango::migrate", "{w}");
    }
    Ok(())
}

/// Snapshots do not carry `db_table_comment` yet, so file migrations
/// never write it; say so instead of dropping it silently.
fn warn_untracked_table_comments(current: &SchemaSnapshot) {
    for e in crate::core::inventory::iter::<crate::core::ModelEntry> {
        let Some(comment) = e.schema.db_table_comment else {
            continue;
        };
        if current.tables.iter().any(|t| t.name == e.schema.table) {
            tracing::warn!(
                target: "rustango::migrate",
                "`{}`: db_table_comment {comment:?} is not written by file migrations yet; \
                 add it with a data migration",
                e.schema.table,
            );
        }
    }
}

/// Generate the framework's own **system-app** migrations into
/// `<project_root>/system/migrations/`.
///
/// Diffs the framework's own `rustango_*` models for `scope` against
/// the prior system migrations of that scope.
///
/// Unlike [`make_migrations_scoped`], this does **not** fold
/// framework tables into the baseline: here they are the subject. A
/// fresh project gets `CreateTable` for each of them, and later runs
/// get `AddColumn` or `DropColumn` as the framework models change.
///
/// Returns `Ok(None)` when the framework's schema for this scope is
/// unchanged.
///
/// # Errors
/// As [`make_migrations_from`], plus [`MigrateError::Io`] if the
/// `system/migrations/` dir can't be created.
pub fn make_migrations_system(
    project_root: &Path,
    scope: crate::core::ModelScope,
    name_override: Option<&str>,
) -> Result<Option<Migration>, MigrateError> {
    let dir = project_root.join("system").join("migrations");
    let prior = if dir.exists() {
        file::list_dir(&dir)?
    } else {
        Vec::new()
    };
    let Some(mig) = plan_system_step(scope, name_override, &prior)? else {
        return Ok(None);
    };
    if !dir.exists() {
        std::fs::create_dir_all(&dir)?;
    }
    let path = dir.join(format!("{}.json", mig.name));
    file::write(&path, &mig)?;
    Ok(Some(mig))
}

/// The step [`make_migrations_system`] would write after `prior`, unwritten,
/// so a `--dry-run` can show it.
///
/// # Errors
/// As [`make_migrations_system`], minus the write.
pub(crate) fn plan_system_step(
    scope: crate::core::ModelScope,
    name_override: Option<&str>,
    prior: &[Migration],
) -> Result<Option<Migration>, MigrateError> {
    // Skip the registry scope when no model declares it, which means
    // this build has no registry database. Its snapshot is still
    // non-empty, because the shared tables are copied into every
    // scope, so without this guard we write a registry `0001` that
    // creates tables the tenant migration also creates. Nothing
    // applies it until the project turns on tenancy, and then it
    // fails with `relation already exists`.
    //
    // Registry only, on purpose. In a single-database project the
    // tenant scope is the one that runs, and it carries the shared
    // tables, so skipping it would leave nothing to create them.
    if scope == crate::core::ModelScope::Registry
        && !super::snapshot::scope_owns_system_tables(scope)
    {
        return Ok(None);
    }
    let migration_scope = migration_scope(scope);
    super::snapshot::check_registry_junctions()?;
    let current = SchemaSnapshot::from_registry_system_for_scope(scope);
    let prior_scoped: Vec<&Migration> = prior
        .iter()
        .filter(|m| m.scope == migration_scope)
        .collect();
    let prev_snapshot = prior_scoped
        .last()
        .map_or_else(empty_snapshot, |m| m.snapshot.clone());
    let prev_name = prior_scoped.last().map(|m| m.name.clone());
    let next_index = prior
        .last()
        .and_then(|m| extract_index(&m.name))
        .map_or(1, |n| n + 1);

    let unsupported = detect_unsupported_field_changes(&prev_snapshot, &current);
    if !unsupported.is_empty() {
        return Err(MigrateError::Validation(format!(
            "framework schema change needs an operation the engine can't yet emit \
             (author manually or wait for the AlterField op):\n  - {}",
            unsupported.join("\n  - "),
        )));
    }
    let changes = detect_changes(&prev_snapshot, &current);
    if changes.is_empty() {
        return Ok(None);
    }
    let suffix = name_override.map_or_else(
        || auto_name(&changes, prior_scoped.is_empty()),
        str::to_owned,
    );
    let name = format!("{next_index:04}_{suffix}");
    let created_at = chrono::Utc::now().to_rfc3339();
    Ok(Some(Migration {
        name,
        created_at,
        prev: prev_name,
        atomic: true,
        scope: migration_scope,
        replaces: Vec::new(),
        merges: Vec::new(),
        snapshot: current,
        forward: changes.into_iter().map(Operation::Schema).collect(),
    }))
}

/// The framework's `system/migrations/` dir and where its files came from.
///
/// Built only by [`SystemChain::prepare`], so a tenant cannot re-probe a dir
/// the registry or an earlier tenant filled and take it for shipped (#1988).
#[derive(Debug, Clone)]
pub(crate) struct SystemChain {
    dir: std::path::PathBuf,
    origin: super::runner::ChainOrigin,
}

impl SystemChain {
    /// [`Self::prepare`] for the project whose `migrations/` dir is `dir`.
    ///
    /// # Errors
    /// As [`Self::prepare`].
    pub(crate) fn for_migrations_dir(
        dir: &Path,
        scopes: &[crate::core::ModelScope],
    ) -> Result<Self, MigrateError> {
        Self::prepare(Self::project_root(dir), scopes)
    }

    /// The project root for a `migrations/` dir. A bare dir not named
    /// `migrations` keeps `system/` inside it.
    fn project_root(dir: &Path) -> &Path {
        file::project_root_of(dir)
    }

    /// The chain's dir for that project, as is: a preview reads it
    /// without generating anything.
    pub(crate) fn dir_for(dir: &Path) -> std::path::PathBuf {
        Self::project_root(dir).join("system").join("migrations")
    }

    /// Generate the chain for `scopes` from today's models. A dir that was
    /// empty when this process first saw it stays `Regenerated`: its names
    /// may already sit in a ledger for other content.
    ///
    /// # Errors
    /// A generation error, so `migrate` never applies a stale chain (#2014).
    pub(crate) fn prepare(
        project_root: &Path,
        scopes: &[crate::core::ModelScope],
    ) -> Result<Self, MigrateError> {
        use super::runner::ChainOrigin;
        static REGENERATED: std::sync::OnceLock<
            std::sync::Mutex<std::collections::HashSet<std::path::PathBuf>>,
        > = std::sync::OnceLock::new();
        let dir = project_root.join("system").join("migrations");
        // Held across probe and write, so a concurrent caller can't see half a dir.
        let mut regenerated = REGENERATED
            .get_or_init(Default::default)
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let shipped = file::list_dir(&dir).is_ok_and(|m| !m.is_empty());
        let generated = scopes
            .iter()
            .try_for_each(|&scope| make_migrations_system(project_root, scope, None).map(drop));
        let key = std::fs::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
        let origin = if !shipped {
            regenerated.insert(key);
            ChainOrigin::Regenerated
        } else if regenerated.contains(&key) {
            ChainOrigin::Regenerated
        } else {
            ChainOrigin::OnDisk
        };
        // After the origin is recorded: a half-written dir is still regenerated.
        generated?;
        Ok(Self { dir, origin })
    }

    /// A shipped chain in `dir`, as is: no catch-up step from today's models.
    #[cfg(all(test, feature = "sqlite"))]
    pub(crate) fn shipped(dir: std::path::PathBuf) -> Self {
        Self {
            dir,
            origin: super::runner::ChainOrigin::OnDisk,
        }
    }

    pub(crate) fn dir(&self) -> &Path {
        &self.dir
    }

    pub(super) fn origin(&self) -> super::runner::ChainOrigin {
        self.origin
    }
}

/// [`make_migrations`] with the current snapshot passed in, instead
/// of read from the registry.
///
/// # Errors
/// Returns [`MigrateError::Io`] or [`MigrateError::Json`] on a file
/// problem, and [`MigrateError::Validation`] if a prior migration is
/// corrupt.
pub fn make_migrations_from(
    dir: &Path,
    current: &SchemaSnapshot,
    name_override: Option<&str>,
) -> Result<Option<Migration>, MigrateError> {
    make_migrations_from_with(dir, current, name_override, DropAndAdd::Refuse)
}

/// [`make_migrations_from`] with an explicit [`DropAndAdd`] policy.
///
/// # Errors
/// As [`make_migrations_from`].
pub fn make_migrations_from_with(
    dir: &Path,
    current: &SchemaSnapshot,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Option<Migration>, MigrateError> {
    let prior = file::list_dir(dir)?;
    let Some(mig) = plan_from(&prior, current, name_override, drops)? else {
        return Ok(None);
    };
    write_planned(dir, &mig)?;
    Ok(Some(mig))
}

/// The file [`make_migrations_from`] would write after `prior`, unwritten.
fn plan_from(
    prior: &[Migration],
    current: &SchemaSnapshot,
    name_override: Option<&str>,
    drops: DropAndAdd,
) -> Result<Option<Migration>, MigrateError> {
    let chain: Vec<&Migration> = prior.iter().collect();
    refuse_branched(&chain)?;
    let mut prev_snapshot = prior
        .last()
        .map_or_else(empty_snapshot, |m| effective_snapshot(&chain, m));
    // The framework owns its `rustango_*` tables: `migrate` creates
    // them from its own system migration chain on the first run. An
    // app diff must treat them as already present, or the next
    // `makemigrations` emits `CreateTable` for each one and the
    // following `migrate` fails on `already exists`.
    //
    // `make_migrations_system` does not fold: there those tables are
    // the subject.
    fold_in_framework_tables(&mut prev_snapshot, current);
    let mut current = current.clone();
    current.keep_unmanaged(&prev_snapshot);
    let current = &current;
    let prev_name = prior.last().map(|m| m.name.clone());
    let next_index = prior
        .last()
        .and_then(|m| extract_index(&m.name))
        .map_or(1, |n| n + 1);

    // Reject metadata changes no `SchemaChange` can express. Without
    // this the function would return `Ok(None)` and the user would
    // believe the schema was already up to date.
    let unsupported = detect_unsupported_field_changes(&prev_snapshot, current);
    if !unsupported.is_empty() {
        return Err(MigrateError::Validation(format!(
            "field metadata changed in a way no migration operation expresses \
             yet; write these changes by hand:\n  - {}",
            unsupported.join("\n  - "),
        )));
    }

    refuse_unkeyed_composite_fks(&prev_snapshot, current)?;
    warn_untracked_table_comments(current);
    let changes = detect_changes(&prev_snapshot, current);
    if changes.is_empty() {
        return Ok(None);
    }
    check_drops(&prev_snapshot, current, &changes, drops)?;

    let suffix = name_override.map_or_else(|| auto_name(&changes, prior.is_empty()), str::to_owned);
    let name = format!("{next_index:04}_{suffix}");
    let created_at = chrono::Utc::now().to_rfc3339();

    Ok(Some(Migration {
        name,
        created_at,
        prev: prev_name,
        atomic: true,
        scope: super::MigrationScope::default(),
        replaces: Vec::new(),
        merges: Vec::new(),
        snapshot: current.clone(),
        forward: changes.into_iter().map(Operation::Schema).collect(),
    }))
}

/// Whether today's models hold a change no file in `prior` has yet; one
/// diff per scope when `scoped`, as a plain `makemigrations` splits it.
///
/// # Errors
/// As [`make_migrations`].
pub(crate) fn models_ahead_of(prior: &[Migration], scoped: bool) -> Result<bool, MigrateError> {
    use crate::core::ModelScope;
    check_models()?;
    if !scoped {
        let current = SchemaSnapshot::from_registry();
        return Ok(plan_from(prior, &current, None, DropAndAdd::Allow)?.is_some());
    }
    for (model, file) in [
        (ModelScope::Registry, super::MigrationScope::Registry),
        (ModelScope::Tenant, super::MigrationScope::Tenant),
    ] {
        let current = SchemaSnapshot::from_registry_for_scope(model);
        if plan_scoped(prior, &current, model, file, None, DropAndAdd::Allow)?.is_some() {
            return Ok(true);
        }
    }
    Ok(false)
}

/// The registry checks every `makemigrations` runs: `--squash` runs them
/// before it deletes the files it regenerates.
fn check_models() -> Result<(), MigrateError> {
    super::snapshot::check_registry_junctions()?;
    super::snapshot::check_relation_targets()
}

/// Names reachable from the last in-scope migration through every
/// parent (`prev` and merged branches). A name missing from this set
/// belongs to a side chain whose tables would otherwise drop out of the
/// baseline. See `make_migrations_scoped`.
fn chain_membership(prior_scoped: &[&Migration]) -> std::collections::HashSet<String> {
    let mut seen = std::collections::HashSet::new();
    let mut todo: Vec<&str> = prior_scoped
        .last()
        .map(|m| m.name.as_str())
        .into_iter()
        .collect();
    while let Some(name) = todo.pop() {
        // `insert` fails on a revisit, so a cyclic chain still ends.
        if !seen.insert(name.to_owned()) {
            continue;
        }
        if let Some(m) = prior_scoped.iter().find(|m| m.name == name) {
            todo.extend(m.prev.as_deref());
            todo.extend(merged_branches(prior_scoped, m));
        }
    }
    seen
}

/// The branch leaves `m` merges. A merge file written before `merges`
/// existed (0.60.5) joined every sibling of its `prev` named before it.
fn merged_branches<'a>(chain: &[&'a Migration], m: &'a Migration) -> Vec<&'a str> {
    if !m.merges.is_empty() {
        return m.merges.iter().map(String::as_str).collect();
    }
    let legacy = m.forward.is_empty() && m.name.ends_with("_merge") && m.replaces.is_empty();
    let Some(head) = m
        .prev
        .as_deref()
        .and_then(|p| chain.iter().find(|c| c.name == p))
        .filter(|_| legacy)
    else {
        return Vec::new();
    };
    chain
        .iter()
        .filter(|c| c.name != head.name && c.name < m.name && c.prev == head.prev)
        .map(|c| c.name.as_str())
        .collect()
}

/// `head`'s snapshot plus the renames hand-written into it and the copies
/// before it: `--empty` copies its parent's snapshot and the edit never
/// updates it (#2573). A snapshot that differs from its parent's already
/// holds its ops, so the walk stops there.
pub(super) fn effective_snapshot(chain: &[&Migration], head: &Migration) -> SchemaSnapshot {
    let parent = |m: &Migration| {
        m.prev
            .as_deref()
            .and_then(|p| chain.iter().copied().find(|c| c.name == p))
    };
    let mut copies = vec![];
    let mut m = head;
    while let Some(p) = parent(m).filter(|p| p.snapshot == m.snapshot) {
        copies.push(m);
        if copies.len() > chain.len() {
            break; // a cyclic `prev`
        }
        m = p;
    }
    let mut snap = head.snapshot.clone();
    for op in copies.iter().rev().flat_map(|m| &m.forward) {
        if let Operation::Schema(change) = op {
            snap.apply_rename(change);
        }
    }
    snap
}

/// `m` and its `prev` ancestors, newest first.
fn ancestry<'a>(chain: &[&'a Migration], m: &'a Migration) -> Vec<&'a Migration> {
    let mut out = vec![m];
    while let Some(p) = out
        .last()
        .and_then(|c| c.prev.as_deref())
        .and_then(|p| chain.iter().copied().find(|c| c.name == p))
    {
        if out.iter().any(|o| o.name == p.name) {
            break; // a cyclic `prev`
        }
        out.push(p);
    }
    out
}

/// The schema rolling back `target` leaves: `prev` (its parent's snapshot)
/// plus the other branches still applied, which `prev` does not know. Falls
/// back to `prev` when those branches cannot be merged into it.
pub(super) fn rollback_snapshot(
    all: &[Migration],
    applied: &std::collections::HashSet<String>,
    target: &Migration,
    prev: SchemaSnapshot,
) -> SchemaSnapshot {
    let chain: Vec<&Migration> = all
        .iter()
        .filter(|m| m.name != target.name && applied.contains(&m.name))
        .collect();
    let Some(parent) = target
        .prev
        .as_deref()
        .and_then(|p| chain.iter().copied().find(|m| m.name == p))
    else {
        return prev;
    };
    with_other_branches(
        &chain,
        parent,
        Some(&target.name),
        prev,
        "unapplying",
        &target.name,
    )
}

/// The schema applying `mig` leaves: its own snapshot plus the other branches
/// already applied, so a SQLite rebuild keeps their columns.
pub(super) fn apply_snapshot(
    all: &[Migration],
    applied: &std::collections::HashSet<String>,
    mig: &Migration,
) -> SchemaSnapshot {
    let chain: Vec<&Migration> = all
        .iter()
        .filter(|m| m.name == mig.name || applied.contains(&m.name))
        .collect();
    let Some(tip) = chain.iter().copied().find(|m| m.name == mig.name) else {
        return mig.snapshot.clone();
    };
    with_other_branches(
        &chain,
        tip,
        None,
        mig.snapshot.clone(),
        "applying",
        &mig.name,
    )
}

/// `own` (the schema along `tip`'s line) merged with every other leaf of
/// `chain`, skipping leaves built on `skip`. Falls back to `own` on a conflict.
fn with_other_branches(
    chain: &[&Migration],
    tip: &Migration,
    skip: Option<&str>,
    own: SchemaSnapshot,
    verb: &str,
    name: &str,
) -> SchemaSnapshot {
    let line = ancestry(chain, tip);
    let mut snap = own.clone();
    for leaf in leaves(chain) {
        let reach = reachable(chain, leaf);
        if leaf.name == tip.name || skip.is_some_and(|s| reach.contains(s)) {
            continue;
        }
        let Some(base) = line.iter().find(|a| reach.contains(&a.name)) else {
            continue;
        };
        let theirs = effective_snapshot(chain, leaf);
        if let Err(conflicts) = snap.merge_branch(&effective_snapshot(chain, base), &theirs) {
            tracing::warn!(
                target: "rustango::migrate",
                "{verb} `{name}`: branch `{}` conflicts ({}); rebuilding from `{}` alone",
                leaf.name,
                conflicts.join("; "),
                tip.name,
            );
            return own;
        }
    }
    snap
}

/// Names reachable from `m` through `prev` and merged branches, `m`'s own
/// and names missing from `chain` included.
fn reachable(chain: &[&Migration], m: &Migration) -> std::collections::HashSet<String> {
    let mut seen = std::collections::HashSet::new();
    let mut todo = vec![m.name.as_str()];
    while let Some(name) = todo.pop() {
        if !seen.insert(name.to_owned()) {
            continue;
        }
        if let Some(c) = chain.iter().find(|c| c.name == name) {
            todo.extend(c.prev.as_deref());
            todo.extend(merged_branches(chain, c));
        }
    }
    seen
}

/// Migrations no `prev`, merged branch or `replaces` names.
fn leaves<'a>(chain: &[&'a Migration]) -> Vec<&'a Migration> {
    let joined: std::collections::HashSet<&str> = chain
        .iter()
        .flat_map(|m| {
            let named = m.prev.iter().chain(&m.replaces).map(String::as_str);
            named.chain(merged_branches(chain, m))
        })
        .collect();
    chain
        .iter()
        .copied()
        .filter(|m| !joined.contains(m.name.as_str()))
        .collect()
}

/// Leaves that branch from one history, grouped per root, each sorted by
/// name. Side chains with their own root are not branches (#2574).
fn branched_leaves<'a>(chain: &[&'a Migration]) -> Vec<Vec<&'a Migration>> {
    let mut groups: std::collections::BTreeMap<&str, Vec<&Migration>> = Default::default();
    for leaf in leaves(chain) {
        let root = ancestry(chain, leaf).last().map_or("", |r| r.name.as_str());
        groups.entry(root).or_default().push(leaf);
    }
    groups
        .into_values()
        .filter(|g| g.len() > 1)
        .map(|mut g| {
            g.sort_by(|a, b| a.name.cmp(&b.name));
            g
        })
        .collect()
}

/// Refuse to diff a branched chain: its last file holds one branch only.
fn refuse_branched(chain: &[&Migration]) -> Result<(), MigrateError> {
    let Some(branch) = branched_leaves(chain).into_iter().next() else {
        return Ok(());
    };
    let names: Vec<&str> = branch.iter().map(|m| m.name.as_str()).collect();
    Err(MigrateError::Validation(format!(
        "makemigrations: the chain has branched ({}); run `makemigrations --merge` first",
        names.join(", ")
    )))
}

/// Set every `rustango_*` table in `into` to its current shape. The
/// prefix is reserved: the system chain creates and changes those tables,
/// so an app diff must never emit a `CreateTable` or `AddColumn` for one.
fn fold_in_framework_tables(into: &mut SchemaSnapshot, current: &SchemaSnapshot) {
    let framework = |name: &str| name.starts_with("rustango_");
    into.tables.retain(|t| !framework(&t.name));
    into.tables.extend(
        current
            .tables
            .iter()
            .filter(|t| framework(&t.name))
            .cloned(),
    );
    into.m2m_tables.retain(|m| !framework(&m.through));
    into.m2m_tables.extend(
        current
            .m2m_tables
            .iter()
            .filter(|m| framework(&m.through))
            .cloned(),
    );
    into.indexes.retain(|i| !framework(&i.table));
    into.indexes.extend(
        current
            .indexes
            .iter()
            .filter(|i| framework(&i.table))
            .cloned(),
    );
    into.checks.retain(|c| !framework(&c.table));
    into.checks.extend(
        current
            .checks
            .iter()
            .filter(|c| framework(&c.table))
            .cloned(),
    );
}

/// Copy every table, m2m, index and check from `from` into `into`
/// that `into` does not already name. Used to fold a side chain's
/// snapshot into the baseline. Adding only what is missing keeps a
/// `DropTable` in the main chain from being undone.
fn fold_in_missing_tables(into: &mut SchemaSnapshot, from: &SchemaSnapshot) {
    for t in &from.tables {
        if !into.tables.iter().any(|x| x.name == t.name) {
            into.tables.push(t.clone());
        }
    }
    for m2m in &from.m2m_tables {
        if !into.m2m_tables.iter().any(|x| x.through == m2m.through) {
            into.m2m_tables.push(m2m.clone());
        }
    }
    for idx in &from.indexes {
        if !into.indexes.iter().any(|x| x.name == idx.name) {
            into.indexes.push(idx.clone());
        }
    }
    for c in &from.checks {
        if !into.checks.iter().any(|x| x.name == c.name) {
            into.checks.push(c.clone());
        }
    }
}

fn empty_snapshot() -> SchemaSnapshot {
    SchemaSnapshot {
        tables: vec![],
        m2m_tables: vec![],
        indexes: vec![],
        checks: vec![],
        excludes: vec![],
    }
}

fn auto_name(changes: &[SchemaChange], is_first: bool) -> String {
    match changes {
        [SchemaChange::CreateTable(t)] => {
            if is_first {
                "initial".into()
            } else {
                format!("create_{t}")
            }
        }
        [SchemaChange::DropTable(t)] => format!("drop_{t}"),
        [SchemaChange::AddColumn { table, column }] => format!("add_{column}_to_{table}"),
        [SchemaChange::DropColumn { table, column }] => format!("drop_{column}_from_{table}"),
        [SchemaChange::AlterColumnType {
            table,
            column,
            from,
            to,
        }] => format!("alter_{column}_on_{table}_{from}_to_{to}"),
        [SchemaChange::AlterColumnNullable {
            table,
            column,
            nullable,
        }] => {
            if *nullable {
                format!("make_{column}_on_{table}_nullable")
            } else {
                format!("make_{column}_on_{table}_not_null")
            }
        }
        [SchemaChange::AlterColumnDefault { table, column, .. }] => {
            format!("alter_default_of_{column}_on_{table}")
        }
        [SchemaChange::AlterColumnMaxLength { table, column, .. }] => {
            format!("alter_max_length_of_{column}_on_{table}")
        }
        [SchemaChange::AlterColumnComment { table, column, .. }] => {
            format!("alter_comment_of_{column}_on_{table}")
        }
        [SchemaChange::AlterFkOnDelete { table, column, .. }] => {
            format!("alter_on_delete_of_{column}_on_{table}")
        }
        [SchemaChange::RenameTable { old_name, new_name }] => {
            format!("rename_{old_name}_to_{new_name}")
        }
        [SchemaChange::RenameColumn {
            table,
            old_column,
            new_column,
        }] => format!("rename_{old_column}_to_{new_column}_on_{table}"),
        [SchemaChange::CreateIndex { name, .. }] => format!("create_index_{name}"),
        [SchemaChange::DropIndex { name, .. }] => format!("drop_index_{name}"),
        [SchemaChange::AddCheckConstraint { name, .. }] => format!("add_check_{name}"),
        [SchemaChange::DropCheckConstraint { name, .. }] => format!("drop_check_{name}"),
        [SchemaChange::CreateM2MTable { through, .. }] => format!("create_m2m_{through}"),
        [SchemaChange::DropM2MTable { through }] => format!("drop_m2m_{through}"),
        many if is_first
            && many
                .iter()
                .all(|c| matches!(c, SchemaChange::CreateTable(_))) =>
        {
            "initial".into()
        }
        // When every op just creates tables (plus their indexes),
        // name the file after those tables instead of `auto`. At
        // most 3 names, joined with `_and_`.
        many if many.iter().all(|c| {
            matches!(
                c,
                SchemaChange::CreateTable(_)
                    | SchemaChange::CreateIndex { .. }
                    | SchemaChange::CreateM2MTable { .. }
            )
        }) =>
        {
            let mut tables: Vec<&str> = many
                .iter()
                .filter_map(|c| match c {
                    SchemaChange::CreateTable(t) => Some(t.as_str()),
                    _ => None,
                })
                .collect();
            tables.sort_unstable();
            tables.dedup();
            if tables.is_empty() {
                "auto".into()
            } else if tables.len() <= 3 {
                format!("create_{}", tables.join("_and_"))
            } else {
                format!("create_{}_etc", tables[..3].join("_and_"))
            }
        }
        _ => "auto".into(),
    }
}

/// Reconcile a branched migration history. Backs
/// `makemigrations --merge`.
///
/// A *leaf* is a migration no other migration names as its `prev`. A
/// linear chain has one. Two people each running `makemigrations` on
/// their own branch create a second leaf with the same parent, and
/// after both merge the next `makemigrations` would pick one of them
/// at random as its `prev`.
///
/// This writes a new `NNNN_merge.json` with an empty `forward` whose
/// `prev` is the last leaf and whose `merges` names the others, so the
/// chain has one head again. Its snapshot joins the branches' snapshots,
/// not the models, so unmigrated edits still reach the next
/// `makemigrations`. An already-linear chain returns `Ok(None)`.
///
/// # Errors
/// Returns [`MigrateError::Validation`] when the chain cannot be
/// merged, or [`MigrateError::Io`] / [`MigrateError::Json`] on file
/// problems.
pub fn make_merge_migration(dir: &Path) -> Result<Option<Migration>, MigrateError> {
    let prior = file::list_dir(dir)?;
    if prior.is_empty() {
        return Err(MigrateError::Validation(
            "makemigrations --merge: no migrations in directory — nothing to merge".into(),
        ));
    }
    let chain: Vec<&Migration> = prior.iter().collect();
    let Some(branch) = branched_leaves(&chain).into_iter().next() else {
        let heads: Vec<&str> = leaves(&chain).iter().map(|m| m.name.as_str()).collect();
        if heads.len() < 2 {
            return Ok(None);
        }
        // Separate roots are side chains, not branches of one history.
        return Err(MigrateError::Validation(format!(
            "makemigrations --merge: leaves don't share a common parent — \
             can't auto-reconcile. Leaves: {}",
            heads.join(", ")
        )));
    };

    // The newest migration every leaf descends from.
    let paths: Vec<Vec<&Migration>> = branch.iter().map(|l| ancestry(&chain, l)).collect();
    let base = paths[0]
        .iter()
        .find(|a| {
            paths[1..]
                .iter()
                .all(|p| p.iter().any(|m| m.name == a.name))
        })
        .map_or_else(empty_snapshot, |a| effective_snapshot(&chain, a));
    let (head, others) = branch.split_last().expect("a branch has 2+ leaves");
    let mut snapshot = effective_snapshot(&chain, head);
    for leaf in others {
        if let Err(conflicts) = snapshot.merge_branch(&base, &effective_snapshot(&chain, leaf)) {
            return Err(MigrateError::Validation(format!(
                "makemigrations --merge: `{}` and `{}` both changed: {}. \
                 Reconcile the branches by hand, then merge again",
                head.name,
                leaf.name,
                conflicts.join("; "),
            )));
        }
    }

    // Point the merge node at the last leaf. Name order already applies
    // the other leaves first, and `forward` is empty, so running this
    // file does nothing.
    let merge_prev = head.name.clone();

    // Number from the highest index in the whole directory, not
    // just among the leaves.
    let next_index = prior
        .iter()
        .filter_map(|m| extract_index(&m.name))
        .max()
        .map_or(1, |n| n + 1);

    let name = format!("{next_index:04}_merge");
    let created_at = chrono::Utc::now().to_rfc3339();

    let mig = Migration {
        name: name.clone(),
        created_at,
        prev: Some(merge_prev),
        atomic: true,
        scope: head.scope,
        // A merge joins two branches, it does not collapse history.
        replaces: Vec::new(),
        merges: others.iter().map(|m| m.name.clone()).collect(),
        snapshot,
        forward: Vec::new(),
    };

    let path = dir.join(format!("{name}.json"));
    file::write(&path, &mig)?;
    Ok(Some(mig))
}

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

    #[test]
    fn auto_name_initial_for_first_migration_with_create_tables() {
        let changes = vec![
            SchemaChange::CreateTable("a".into()),
            SchemaChange::CreateTable("b".into()),
        ];
        assert_eq!(auto_name(&changes, true), "initial");
    }

    #[test]
    fn auto_name_single_create_table_after_initial() {
        let changes = vec![SchemaChange::CreateTable("foo".into())];
        assert_eq!(auto_name(&changes, false), "create_foo");
    }

    #[test]
    fn auto_name_single_drop_table() {
        let changes = vec![SchemaChange::DropTable("ghost".into())];
        assert_eq!(auto_name(&changes, false), "drop_ghost");
    }

    #[test]
    fn auto_name_add_column() {
        let changes = vec![SchemaChange::AddColumn {
            table: "article".into(),
            column: "slug".into(),
        }];
        assert_eq!(auto_name(&changes, false), "add_slug_to_article");
    }

    #[test]
    fn auto_name_drop_column() {
        let changes = vec![SchemaChange::DropColumn {
            table: "article".into(),
            column: "deprecated".into(),
        }];
        assert_eq!(auto_name(&changes, false), "drop_deprecated_from_article");
    }

    #[test]
    fn auto_name_mixed_falls_back_to_auto() {
        let changes = vec![
            SchemaChange::CreateTable("foo".into()),
            SchemaChange::AddColumn {
                table: "bar".into(),
                column: "baz".into(),
            },
        ];
        assert_eq!(auto_name(&changes, false), "auto");
    }

    // ============================================================ scope-aware
    //
    // Diffs must split by `ModelScope`: registry models into a file
    // tagged `MigrationScope::Registry`, tenant models into one
    // tagged `MigrationScope::Tenant`. Mixing them puts a registry
    // ALTER in a tenant migration, where `search_path` resolves it
    // to the registry copy and the run fails.
    //
    // These tests drive the split helpers without touching the
    // global inventory.

    use crate::core::ModelScope;
    use crate::migrate::snapshot::{FieldSnapshot, SchemaSnapshot, TableSnapshot};
    use crate::migrate::MigrationScope;

    fn snap_with(tables: Vec<TableSnapshot>) -> SchemaSnapshot {
        SchemaSnapshot {
            tables,
            m2m_tables: vec![],
            indexes: vec![],
            checks: vec![],
            excludes: vec![],
        }
    }

    fn t(name: &str) -> TableSnapshot {
        TableSnapshot {
            name: name.into(),
            model: name.into(),
            fields: vec![FieldSnapshot {
                name: "id".into(),
                column: "id".into(),
                ty: "i64".into(),
                nullable: false,
                primary_key: true,
                max_length: None,
                min: None,
                max: None,
                default: None,
                auto: true,
                unique: false,
                case_insensitive: false,
                generated_as: None,
                db_comment: None,
                fk: None,
            }],
            composite_fks: vec![],
        }
    }

    #[test]
    fn make_migrations_scoped_with_no_changes_returns_none() {
        // Seed dir with a prior tenant migration whose snapshot already
        // matches `current` → diff is empty → no new file emitted.
        let dir = tempdir();
        let snap = snap_with(vec![t("rustango_users")]);
        let prior = Migration {
            name: "0001_initial".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            prev: None,
            atomic: true,
            scope: MigrationScope::Tenant,
            replaces: Vec::new(),
            merges: Vec::new(),
            snapshot: snap.clone(),
            forward: vec![],
        };
        std::fs::write(
            dir.join("0001_initial.json"),
            serde_json::to_string(&prior).unwrap(),
        )
        .unwrap();
        let r = make_migrations_scoped(
            &dir,
            &snap,
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap();
        assert!(r.is_none(), "no changes should yield no file");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn make_migrations_scoped_emits_with_correct_migration_scope() {
        // First call in an empty dir writes one file tagged
        // `MigrationScope::Tenant`.
        //
        // The table name must not start with `rustango_`: that
        // prefix is filtered out of an app diff baseline, so a
        // framework-shaped name would test nothing.
        let dir = tempdir();
        let snap = snap_with(vec![t("posts")]);
        let mig = make_migrations_scoped(
            &dir,
            &snap,
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap()
        .expect("expected a migration file");
        assert_eq!(mig.scope, MigrationScope::Tenant);
        assert!(mig.name.starts_with("0001_"), "got: {}", mig.name);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn make_migrations_scoped_filters_prev_to_scope_for_old_bootstrap_layout() {
        // An old bootstrap snapshot holds both registry and tenant
        // framework tables. `filtered_to_scope` must drop the
        // registry ones before the diff, so a tenant-scope diff sees
        // only the new user table and emits nothing for
        // `rustango_operators`.
        //
        // A table missing from the inventory counts as Tenant, so
        // only tables declared `scope = Registry` are filtered out.
        let dir = tempdir();
        let prev = Migration {
            name: "0001_initial".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            prev: None,
            atomic: true,
            scope: MigrationScope::Tenant,
            replaces: Vec::new(),
            merges: Vec::new(),
            snapshot: snap_with(vec![t("rustango_users")]),
            forward: vec![],
        };
        let path = dir.join("0001_initial.json");
        std::fs::write(&path, serde_json::to_string(&prev).unwrap()).unwrap();
        // current adds a new tenant table.
        let current = snap_with(vec![t("posts"), t("rustango_users")]);
        let mig = make_migrations_scoped(
            &dir,
            &current,
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap()
        .expect("expected a migration");
        assert_eq!(mig.scope, MigrationScope::Tenant);
        // The CreateTable for `posts` is the only forward op.
        assert_eq!(mig.forward.len(), 1, "got: {:?}", mig.forward);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn make_migrations_scoped_indexes_walk_full_dir_not_just_scope() {
        // With a registry `0001` and a tenant `0002` in the same
        // directory, the next tenant migration must be `0003`.
        // Numbering walks both scopes so filenames cannot collide.
        let dir = tempdir();
        let r = Migration {
            name: "0001_registry_initial".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            prev: None,
            atomic: true,
            scope: MigrationScope::Registry,
            replaces: Vec::new(),
            merges: Vec::new(),
            snapshot: snap_with(vec![t("rustango_orgs")]),
            forward: vec![],
        };
        let t1 = Migration {
            name: "0002_initial".into(),
            created_at: "2026-01-02T00:00:00Z".into(),
            prev: None,
            atomic: true,
            scope: MigrationScope::Tenant,
            replaces: Vec::new(),
            merges: Vec::new(),
            snapshot: snap_with(vec![t("rustango_users")]),
            forward: vec![],
        };
        std::fs::write(
            dir.join("0001_registry_initial.json"),
            serde_json::to_string(&r).unwrap(),
        )
        .unwrap();
        std::fs::write(
            dir.join("0002_initial.json"),
            serde_json::to_string(&t1).unwrap(),
        )
        .unwrap();
        let current = snap_with(vec![t("posts"), t("rustango_users")]);
        let mig = make_migrations_scoped(
            &dir,
            &current,
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap()
        .expect("expected a migration");
        assert!(
            mig.name.starts_with("0003_"),
            "next migration must be 0003 to avoid collision with 0002, got: {}",
            mig.name
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    fn tempdir() -> std::path::PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static N: AtomicU64 = AtomicU64::new(0);
        let n = N.fetch_add(1, Ordering::SeqCst);
        let pid = std::process::id();
        let mut p = std::env::temp_dir();
        p.push(format!("rustango_make_scope_test_{pid}_{n}"));
        let _ = std::fs::remove_dir_all(&p);
        std::fs::create_dir_all(&p).unwrap();
        p
    }

    // ============================================ framework-table fold
    //
    // The first `migrate` applies the system migration chain, which
    // creates every `rustango_*` table. So by the user's first
    // `makemigrations` those tables already exist while the app's
    // migration directory is still empty.
    //
    // An app diff baseline must therefore treat them as present.
    // Otherwise `makemigrations` emits `CreateTable` for each one and
    // the next `migrate` fails on `already exists`. These tests pin
    // that for the plain and `--app` paths, which both go through
    // `make_migrations_from`.

    fn idx(name: &str, table: &str) -> crate::migrate::snapshot::IndexSnapshot {
        crate::migrate::snapshot::IndexSnapshot {
            name: name.into(),
            table: table.into(),
            columns: vec!["id".into()],
            unique: false,
            method: "btree".into(),
            where_clause: None,
            include: vec![],
        }
    }

    /// A first `makemigrations` in an empty dir must create the
    /// user's tables and leave the framework's alone.
    #[test]
    fn plain_makemigrations_does_not_re_emit_framework_tables() {
        let dir = tempdir();
        // Two user models beside the framework tables the system
        // chain has already created.
        let current = snap_with(vec![
            t("blog"),
            t("item"),
            t("rustango_admin_users"),
            t("rustango_audit_log"),
            t("rustango_content_types"),
        ]);

        let mig = make_migrations_from(&dir, &current, None)
            .expect("diff succeeds")
            .expect("user tables are new, so a migration is written");

        let created: Vec<&str> = mig
            .forward
            .iter()
            .filter_map(|op| match op {
                Operation::Schema(SchemaChange::CreateTable(n)) => Some(n.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            created,
            vec!["blog", "item"],
            "a user-app migration must create only user tables; any \
             rustango_* table here is what crashes the next `migrate`"
        );
    }

    /// Indexes must be folded in too: re-creating an index on a
    /// framework table fails the same way re-creating the table does.
    #[test]
    fn plain_makemigrations_does_not_re_emit_framework_indexes() {
        let dir = tempdir();
        let mut current = snap_with(vec![t("blog"), t("rustango_audit_log")]);
        current.indexes = vec![
            idx("blog_id_idx", "blog"),
            idx("rustango_audit_log_occurred_at_idx", "rustango_audit_log"),
        ];

        let mig = make_migrations_from(&dir, &current, None)
            .expect("diff succeeds")
            .expect("migration written");

        let indexed: Vec<&str> = mig
            .forward
            .iter()
            .filter_map(|op| match op {
                Operation::Schema(SchemaChange::CreateIndex { table, .. }) => Some(table.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            indexed,
            vec!["blog"],
            "framework indexes belong to the system chain"
        );
    }

    /// With only framework tables present there is nothing for an
    /// app migration to write.
    #[test]
    fn framework_only_registry_yields_no_migration() {
        let dir = tempdir();
        let current = snap_with(vec![t("rustango_admin_users"), t("rustango_media")]);
        assert!(
            make_migrations_from(&dir, &current, None)
                .expect("diff succeeds")
                .is_none(),
            "nothing but framework tables means no user-app migration"
        );
    }

    /// The fold matches the reserved prefix only. A user table whose
    /// name merely contains `rustango` still belongs to the user.
    #[test]
    fn fold_only_matches_the_reserved_prefix() {
        let dir = tempdir();
        let current = snap_with(vec![t("my_rustango_notes"), t("rustango_media")]);

        let mig = make_migrations_from(&dir, &current, None)
            .expect("diff succeeds")
            .expect("the user table is new");

        let created: Vec<&str> = mig
            .forward
            .iter()
            .filter_map(|op| match op {
                Operation::Schema(SchemaChange::CreateTable(n)) => Some(n.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(created, vec!["my_rustango_notes"]);
    }

    // ====================================== makemigrations --merge
    //
    // Reconciles a branched chain with an empty-forward
    // `NNNN_merge.json` whose `prev` is the last leaf. Its snapshot
    // joins the leaves' snapshots.

    fn write_mig(dir: &std::path::Path, mig: &Migration) {
        std::fs::write(
            dir.join(format!("{}.json", mig.name)),
            serde_json::to_string_pretty(mig).unwrap(),
        )
        .unwrap();
    }

    fn mig_at(name: &str, prev: Option<&str>, snapshot: SchemaSnapshot) -> Migration {
        Migration {
            name: name.into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            prev: prev.map(str::to_owned),
            atomic: true,
            scope: MigrationScope::Tenant,
            replaces: Vec::new(),
            merges: Vec::new(),
            snapshot,
            forward: vec![],
        }
    }

    /// Two `--empty` renames in a row: both reach the next diff (#2573).
    #[test]
    fn stacked_empty_renames_reach_the_baseline() {
        let dir = tempdir();
        let rename = |table: &str, old: &str, new: &str| {
            Operation::Schema(SchemaChange::RenameColumn {
                table: table.into(),
                old_column: old.into(),
                new_column: new.into(),
            })
        };
        let with = |cols: &[&str]| snap_with(vec![posts_with(cols)]);
        let old = with(&["a", "c"]);
        write_mig(&dir, &mig_at("0001_initial", None, old.clone()));
        let mut m2 = mig_at("0002_r1", Some("0001_initial"), old.clone());
        m2.forward = vec![rename("posts", "a", "b")];
        write_mig(&dir, &m2);
        let mut m3 = mig_at("0003_r2", Some("0002_r1"), old);
        m3.forward = vec![rename("posts", "c", "d")];
        write_mig(&dir, &m3);
        let next = make_migrations_from(&dir, &with(&["b", "d"]), None).unwrap();
        assert!(next.is_none(), "{:?}", next.map(|m| m.forward));
        // `makemigrations` itself takes the scoped path.
        let next = make_migrations_scoped(
            &dir,
            &with(&["b", "d"]),
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap();
        assert!(next.is_none(), "{:?}", next.map(|m| m.forward));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn merge_returns_none_when_chain_is_linear() {
        let dir = tempdir();
        let snap = snap_with(vec![t("posts")]);
        write_mig(&dir, &mig_at("0001_initial", None, snap.clone()));
        write_mig(
            &dir,
            &mig_at("0002_add", Some("0001_initial"), snap.clone()),
        );
        let r = make_merge_migration(&dir).unwrap();
        assert!(
            r.is_none(),
            "single-leaf chain should NOT emit a merge file, got {r:?}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn merge_errors_when_dir_is_empty() {
        let dir = tempdir();
        let err = make_merge_migration(&dir).unwrap_err();
        assert!(matches!(err, MigrateError::Validation(_)));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn merge_writes_merge_file_when_two_leaves_share_parent() {
        let dir = tempdir();
        let snap = snap_with(vec![t("posts")]);
        // 0001 ← 0002a (leaf A) and 0001 ← 0002b (leaf B).
        write_mig(&dir, &mig_at("0001_initial", None, snap.clone()));
        write_mig(
            &dir,
            &mig_at("0002a_branch", Some("0001_initial"), snap.clone()),
        );
        write_mig(
            &dir,
            &mig_at("0002b_branch", Some("0001_initial"), snap.clone()),
        );

        let mig = make_merge_migration(&dir)
            .unwrap()
            .expect("two leaves should produce a merge file");

        // Next index = max(0001, 0002a, 0002b) = 2 → next is 0003.
        assert!(
            mig.name.starts_with("0003_"),
            "merge file index should follow lex-last leaf, got: {}",
            mig.name
        );
        assert_eq!(mig.name, "0003_merge");
        // The last leaf by name wins `prev`: 0002b sorts after 0002a.
        assert_eq!(mig.prev.as_deref(), Some("0002b_branch"));
        // The merge file only anchors the chain, so it runs nothing.
        assert!(mig.forward.is_empty(), "merge file must have empty forward");
        // Name order still applies 0002a, then 0002b, then the merge
        // file, so both branches' changes land. 0002a stays a leaf
        // afterwards because nothing names it, but that is a graph
        // quirk, not a chain conflict, so the test stops here.
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn merge_rejects_leaves_with_different_parents() {
        let dir = tempdir();
        let snap = snap_with(vec![t("posts")]);
        // Two leaves with different parents is a real divergence,
        // not a branch collision, so the merge must refuse.
        write_mig(&dir, &mig_at("0001_a", None, snap.clone()));
        write_mig(&dir, &mig_at("0002_b", Some("0001_a"), snap.clone()));
        write_mig(&dir, &mig_at("0001_z", None, snap.clone()));
        let err = make_merge_migration(&dir).unwrap_err();
        match err {
            MigrateError::Validation(msg) => {
                assert!(
                    msg.contains("common parent"),
                    "error should mention common-parent requirement, got: {msg}"
                );
            }
            other => panic!("expected Validation error, got {other:?}"),
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `posts` with `cols` beside its `id`.
    fn posts_with(cols: &[&str]) -> TableSnapshot {
        let mut table = t("posts");
        for c in cols {
            let mut f = table.fields[0].clone();
            (f.name, f.column, f.primary_key, f.auto) = ((*c).into(), (*c).into(), false, false);
            table.fields.push(f);
        }
        table.fields.sort_by(|a, b| a.column.cmp(&b.column));
        table
    }

    /// 0001 ← 0002a (adds `a`, drops `old`) and 0001 ← 0002b (adds `b`
    /// and the `tags` table).
    fn branched_dir() -> std::path::PathBuf {
        let dir = tempdir();
        let base = snap_with(vec![posts_with(&["old"])]);
        write_mig(&dir, &mig_at("0001_initial", None, base));
        let a = snap_with(vec![posts_with(&["a"])]);
        write_mig(&dir, &mig_at("0002a", Some("0001_initial"), a));
        let b = snap_with(vec![posts_with(&["b", "old"]), t("tags")]);
        write_mig(&dir, &mig_at("0002b", Some("0001_initial"), b));
        dir
    }

    /// A merged-in branch is part of the chain, not a side chain whose
    /// tables and indexes fold back into the baseline.
    #[test]
    fn scoped_makemigrations_follows_merges() {
        let dir = tempdir();
        let mut base = snap_with(vec![posts_with(&[])]);
        base.indexes = vec![idx("posts_x_idx", "posts")];
        write_mig(&dir, &mig_at("0001_initial", None, base));
        let mut a = snap_with(vec![posts_with(&["a"])]);
        a.indexes = vec![idx("posts_x_idx", "posts")];
        write_mig(&dir, &mig_at("0002a", Some("0001_initial"), a));
        let b = snap_with(vec![posts_with(&[])]);
        write_mig(&dir, &mig_at("0002b", Some("0001_initial"), b));
        let mig = make_merge_migration(&dir).unwrap().unwrap();
        assert!(mig.snapshot.indexes.is_empty(), "{:?}", mig.snapshot);
        let next = make_migrations_scoped(
            &dir,
            &mig.snapshot,
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap();
        assert!(next.is_none(), "{:?}", next.map(|m| m.forward));
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A merge file from before `merges` existed still joins its branch.
    #[test]
    fn legacy_merge_file_still_joins_the_branch() {
        let dir = branched_dir();
        let joined = snap_with(vec![posts_with(&["a", "b"]), t("tags")]);
        write_mig(&dir, &mig_at("0003_merge", Some("0002b"), joined.clone()));
        assert!(make_migrations_from(&dir, &joined, None).unwrap().is_none());
        let scoped = make_migrations_scoped(
            &dir,
            &joined,
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap();
        assert!(scoped.is_none(), "{:?}", scoped.map(|m| m.forward));
        assert!(make_merge_migration(&dir).unwrap().is_none());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Diffing one branch would re-add the other's column (#2574).
    #[test]
    fn makemigrations_refuses_a_branched_chain() {
        let dir = branched_dir();
        let current = snap_with(vec![posts_with(&["a", "b"]), t("tags")]);
        let err = make_migrations_from(&dir, &current, None).unwrap_err();
        assert!(
            matches!(&err, MigrateError::Validation(m) if m.contains("--merge")),
            "{err:?}"
        );
        let err = make_migrations_scoped(
            &dir,
            &current,
            ModelScope::Tenant,
            MigrationScope::Tenant,
            None,
        )
        .unwrap_err();
        assert!(matches!(err, MigrateError::Validation(_)), "{err:?}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The merge snapshot joins both branches and keeps an unmigrated
    /// model edit out, so the next diff still emits it (#2574).
    #[test]
    fn merge_joins_the_branches_not_the_models() {
        let dir = branched_dir();
        let mig = make_merge_migration(&dir).unwrap().unwrap();
        assert_eq!(mig.merges, vec!["0002a".to_owned()]);
        let joined = snap_with(vec![posts_with(&["a", "b"]), t("tags")]);
        assert_eq!(mig.snapshot, joined);
        let mut current = joined;
        current.tables[0] = posts_with(&["a", "b", "c"]);
        let next = make_migrations_from(&dir, &current, None)
            .unwrap()
            .expect("the unmigrated column");
        assert_eq!(next.prev.as_deref(), Some(mig.name.as_str()));
        assert_eq!(
            next.forward,
            vec![Operation::Schema(SchemaChange::AddColumn {
                table: "posts".into(),
                column: "c".into(),
            })]
        );
        assert!(make_merge_migration(&dir).unwrap().is_none());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Both branches changing one thing differently is refused, not won by
    /// the other branch or the drop.
    #[test]
    fn merge_refuses_conflicting_branches() {
        let mut nullable = posts_with(&["c"]);
        nullable
            .fields
            .iter_mut()
            .find(|f| f.column == "c")
            .unwrap()
            .nullable = true;
        let mut longer = posts_with(&["c"]);
        longer
            .fields
            .iter_mut()
            .find(|f| f.column == "c")
            .unwrap()
            .max_length = Some(9);
        // Both add `tags.x`, with different types.
        let tags = |ty: &str| {
            let mut t = t("tags");
            let mut x = t.fields[0].clone();
            (x.name, x.column, x.primary_key, x.auto, x.ty) =
                ("x".into(), "x".into(), false, false, ty.into());
            t.fields.push(x);
            t
        };
        let model = |m: &str| TableSnapshot {
            model: m.into(),
            ..posts_with(&["c"])
        };
        for (a, b, what) in [
            (vec![nullable.clone()], vec![], "table `posts`"),
            (vec![], vec![nullable.clone()], "table `posts`"),
            (vec![nullable], vec![longer], "column `c`"),
            (
                vec![posts_with(&["c"]), tags("i64")],
                vec![posts_with(&["c"]), tags("string")],
                "table `tags` column `x`",
            ),
            (
                vec![model("PostA")],
                vec![model("PostB")],
                "table `posts` model",
            ),
        ] {
            let dir = tempdir();
            write_mig(
                &dir,
                &mig_at("0001_initial", None, snap_with(vec![posts_with(&["c"])])),
            );
            write_mig(&dir, &mig_at("0002a", Some("0001_initial"), snap_with(a)));
            write_mig(&dir, &mig_at("0002b", Some("0001_initial"), snap_with(b)));
            let err = make_merge_migration(&dir).expect_err(what);
            assert!(
                matches!(&err, MigrateError::Validation(m) if m.contains(what)),
                "{err:?}"
            );
            assert!(!dir.join("0003_merge.json").exists(), "{what}");
            let _ = std::fs::remove_dir_all(&dir);
        }
    }

    /// A refused tenant scope writes nothing: not the registry file planned
    /// before it, not the framework's system steps.
    #[test]
    fn tenancy_run_writes_no_file_when_a_scope_is_refused() {
        let root = tempdir();
        let dir = root.join("migrations");
        std::fs::create_dir_all(&dir).unwrap();
        let posts = |col: &str| {
            let mut p = t("posts");
            let mut f = p.fields[0].clone();
            f.name = col.into();
            f.column = col.into();
            f.ty = "string".into();
            f.primary_key = false;
            f.auto = false;
            f.max_length = Some(100);
            p.fields.push(f);
            p
        };
        let prior = Migration {
            name: "0001_initial".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            prev: None,
            atomic: true,
            scope: MigrationScope::Tenant,
            replaces: Vec::new(),
            merges: Vec::new(),
            snapshot: snap_with(vec![posts("subtitle")]),
            forward: vec![],
        };
        file::write(&dir.join("0001_initial.json"), &prior).unwrap();
        let scopes = [
            (ModelScope::Registry, snap_with(vec![t("orgs")])),
            (ModelScope::Tenant, snap_with(vec![posts("tagline")])),
        ];
        let err = make_tenancy_from(&dir, &scopes, None, DropAndAdd::Refuse)
            .expect_err("the tenant rename is refused");
        assert!(err.to_string().contains("renamed field"), "{err}");
        let names = |d: &Path| -> Vec<String> {
            file::list_dir(d)
                .unwrap()
                .into_iter()
                .map(|m| m.name)
                .collect()
        };
        assert_eq!(names(&dir), ["0001_initial"]);
        assert!(!root.join("system").exists(), "no system step written");

        let run = make_tenancy_from(&dir, &scopes, None, DropAndAdd::Allow).expect("allowed");
        let app: Vec<_> = run.app.iter().flat_map(|(_, m)| m.clone()).collect();
        assert_eq!(app.len(), 2);
        assert!(app[0].name.starts_with("0002_"), "{}", app[0].name);
        assert!(app[1].name.starts_with("0003_"), "{}", app[1].name);
        assert_eq!(names(&dir).len(), 3);
        let _ = std::fs::remove_dir_all(&root);
    }
}