puerto 0.33.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-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
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
use super::*;

// ── T-07: compile matrix ──────────────────────────────────────────────────
//
// The structural tests above assert on substrings of the generated *text*. Nothing there proves
// the text is valid Rust — which is how `Option<VO>`/`Vec<VO>` (T-01), `--no-demo` (T-02) and
// use-case-less entities (T-03) shipped broken. These scenarios generate a real project, scaffold
// into it, and run `cargo test --workspace` inside it: the only assertion that cannot be fooled.
//
// They are `#[ignore]`d (slow) and run via `make test/full`.

/// One end-to-end generation scenario.
pub(super) struct Scenario<'a> {
    /// Temp-dir suffix and snapshot name; must be unique per scenario.
    pub(super) name: &'a str,
    /// A `--db` project (`puerto nuevo --db`): Pg repositories, migrations.
    pub(super) db: bool,
    /// `puerto nuevo --db --eventos <transport>`: units of work, `events.rs`, the outbox.
    pub(super) events: Option<&'a str>,
    /// `puerto nuevo --auth <mode>`: the `User` entity, the provisioning authenticator, `GET /me`.
    pub(super) auth: Option<&'a str>,
    /// Strip the Saludo demo before scaffolding (`puerto nuevo --sin-demo`).
    pub(super) no_demo: bool,
    /// Strip the web frontend (`puerto nuevo --sin-web`).
    pub(super) no_web: bool,
    /// Shared VOs declared in puerto.toml before any scaffold (`(name, inner_type, --ejemplo)`). An
    /// `inner_type` with a `:` is a composite one's fields (Fase 31): `"calle:String cp:opt:String"`.
    pub(super) shared_vos: &'a [(&'a str, &'a str, Option<&'a str>)],
    /// Entities to scaffold: `(PascalName, CLI field args)`.
    pub(super) entities: &'a [(&'a str, &'a [&'a str])],
    /// Auth projects: `(PascalName, --public use cases, --role use_case=role)` of a scaffold.
    pub(super) access: &'a [Access<'a>],
    /// Auth projects: `(PascalName, --solo-rol use cases)` of a scaffold (28.2).
    pub(super) role_only: &'a [(&'a str, &'a [&'a str])],
    /// `(PascalName, --unico groups, --orden keys, --privado fields)` of a scaffold (Phase 20.7–20.9).
    pub(super) shapes: &'a [Shape<'a>],
    /// Custom use cases added after scaffolding: `(PascalEntity, snake_action)`.
    pub(super) use_cases: &'a [(&'a str, &'a str)],
    /// Transitions added after the custom use cases (`puerto generar transicion`): `(PascalEntity,
    /// verb, --evento, --rol, --interno, --solo-rol)`.
    pub(super) transitions: &'a [Transition<'a>],
    /// Internal use cases (`puerto generar caso-de-uso --interno`, 27.13): `(PascalEntity, action)`.
    pub(super) internal_use_cases: &'a [(&'a str, &'a str)],
    /// Custom events declared after scaffolding (`puerto generar evento`): `(PascalEntity, name)`.
    pub(super) entity_events: &'a [(&'a str, &'a str)],
    /// Worker consumers added last (`puerto generar consumidor`): `(name, event types, --usa)`.
    pub(super) consumers: &'a [(&'a str, &'a [&'a str], &'a [&'a str])],
    /// Mails added after the consumers (`puerto generar correo`): `(name, CLI field args, --tras,
    /// --to)`.
    pub(super) mails: &'a [Mail<'a>],
    /// `puerto nuevo --portada --ruta-app <path>`: the portada at `/`, the app under the path.
    pub(super) portada: Option<&'a str>,
    /// Blocks installed last, with `--forzar` (`puerto generar web-bloque`, ADR-0028).
    pub(super) blocks: &'a [&'a str],
}

pub(super) type Access<'a> = (&'a str, &'a [&'a str], &'a [&'a str]);

/// `(entity, --unico, --orden, --privado, --por-defecto, --generado, --propietario)`.
pub(super) type Shape<'a> = (
    &'a str,
    &'a [&'a str],
    &'a [&'a str],
    &'a [&'a str],
    &'a [&'a str],
    &'a [&'a str],
    Option<&'a str>,
);

pub(super) type Transition<'a> = (&'a str, &'a str, Option<&'a str>, &'a [&'a str], bool, bool);

pub(super) type Mail<'a> = (&'a str, &'a [&'a str], &'a [&'a str], Option<&'a str>);

// The scenarios, shared with the snapshot tests (`generated_output.rs`): one proves the output
// compiles, the other that it did not change.

pub(super) const NO_DEMO: Scenario = Scenario {
    name: "no_demo",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: true,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[("Persona", &["name:String"])],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const NO_WEB: Scenario = Scenario {
    name: "no_web",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: true,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const PRIMITIVES: Scenario = Scenario {
    name: "primitives",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Producto",
        &[
            "title:String",
            "price:i64",
            "in_stock:bool",
            "rate:f64",
            "released_at:DateTime",
            "meta:map",
            // A `Uuid` field (the usual foreign key) was missing from this matrix, which is how
            // the generators shipped dropping it from every params struct and DTO.
            "categoria_id:Uuid",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const UUID_VO: Scenario = Scenario {
    name: "uuid_vo",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[("Reserva", &["reference:String", "tenant_id:TenantId:Uuid"])],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const OPT_VEC_PRIM: Scenario = Scenario {
    name: "opt_vec_prim",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Article",
        &[
            "title:String",
            "summary:opt:String",
            "views:opt:i64",
            "tags:vec:String",
            "scores:vec:i64",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const PLAIN_VO: Scenario = Scenario {
    name: "plain_vo",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Articulo",
        &["name:Name:String", "sku:Sku:String!", "weight:Weight:i64"],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const OPT_VEC_VO: Scenario = Scenario {
    name: "opt_vec_vo",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Persona",
        &[
            "name:String",
            "middle_name:MiddleName:opt:String",
            "tags:Tag:vec:String",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const ENUM_VO: Scenario = Scenario {
    name: "enum_vo",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Pedido",
        &[
            "reference:String",
            "status:Status:enum:Pending/Confirmed/Cancelled",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const SHARED_VO: Scenario = Scenario {
    name: "shared_vo",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    // 27.15: their examples reach the mothers, the route and use-case tests and the web's.
    shared_vos: &[
        ("Email", "String", Some("ana@ejemplo.es")),
        ("Money", "i64", Some("1250")),
        // 27.16: a shared class with a rule; its field takes it from here.
        ("Amount", "dinero", None),
        // Fase 31: a composite one, one column per field.
        (
            "Direccion",
            "calle:String ciudad:String cp:opt:String numero:i64",
            None,
        ),
    ],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Cliente",
        &[
            "name:String",
            "email:Email",
            "credit:Money",
            "total:Amount",
            "address:Direccion",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const MULTI_ENTITY: Scenario = Scenario {
    name: "multi_entity",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[
        ("Producto", &["title:String", "price:i64"]),
        ("Categoria", &["name:Name:String"]),
    ],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const VO_KITCHEN_SINK: Scenario = Scenario {
    name: "vo_kitchen_sink",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[("Email", "String", None)],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Cuenta",
        &[
            "title:String",
            "price:i64",
            "name:Name:String",
            "sku:Sku:String!",
            "note:opt:String",
            "middle_name:MiddleName:opt:String",
            "tags:Tag:vec:String",
            "status:Status:enum:Active/Archived",
            "email:Email",
            // 27.16: the value objects with a rule, and their tests.
            "contact:Contact:email",
            "fee:Fee:dinero",
        ],
    )],
    // 27.17: the server sets them — `status` on create, `sku` made up by the domain.
    shapes: &[(
        "Cuenta",
        &[],
        &[],
        &[],
        &["status=Archived"],
        &["sku"],
        None,
    )],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const ENUM_ONLY: Scenario = Scenario {
    name: "enum_only",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[("Billete", &["state:State:enum:Open/Closed"])],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// A custom use case, and a transition with neither events nor auth (27.12).
pub(super) const CUSTOM_USE_CASE: Scenario = Scenario {
    name: "custom_use_case",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[("Producto", "archive_producto")],
    transitions: &[("Producto", "archivar", None, &[], false, false)],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[("Producto", &["title:String", "price:i64"])],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// Phase 9.2: an entity whose every field reaches the frontend — each primitive an input holds,
/// and a value object over one — with a two-word name (`linea-pedido` files, `/lineas_pedido`).
pub(super) const WEB_CRUD: Scenario = Scenario {
    name: "web_crud",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "LineaPedido",
        &[
            "title:String",
            "quantity:i64",
            "rate:f64",
            "in_stock:bool",
            "ref_id:Uuid",
            "sku:Sku:String",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// Phase 9.3: every field type on the frontend — `Option` of each primitive, `Vec`, `HashMap`,
/// `DateTime`, an enum VO, `Option` / `Vec` VOs — on an entity named after a TypeScript keyword
/// (`Case` → `caseItem`).
pub(super) const WEB_EVERY_TYPE: Scenario = Scenario {
    name: "web_every_type",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[(
        "Case",
        &[
            "title:String",
            "summary:opt:String",
            "views:opt:i64",
            "ratio:opt:f64",
            "urgent:opt:bool",
            "due_at:opt:DateTime",
            "opened_at:DateTime",
            "tags:vec:String",
            "scores:vec:i64",
            "meta:map",
            "status:Status:enum:Open/Closed",
            "middle_name:MiddleName:opt:String",
            "labels:Label:vec:String",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// Phase 18 (ADR-0022): references — required, optional, two to one target, a chain
/// (`Envio` → `Pedido` → `Cliente`), a unique one (one-to-one) and two targets on one form
/// (`Envio` → `Pedido`, `Cliente`). Fase 29: self references, alone (`Cliente`) and beside
/// another target (`Pedido`), on an entity others reference.
const REFERENCE_ENTITIES: &[(&str, &[&str])] = &[
    // Fase 32: the target of a set.
    ("Etiqueta", &["nombre:String"]),
    (
        "Cliente",
        &[
            "name:Name:String",
            "email:String!",
            "padre_id:ref:opt:Cliente",
        ],
    ),
    (
        "Pedido",
        &[
            "cliente_id:ref:Cliente",
            "reviewer_id:ref:opt:Cliente",
            "total:i64",
            "origen_id:ref:opt:Pedido",
            // Fase 32: a set of another entity's rows, and of its own.
            "etiquetas:vec:ref:Etiqueta",
            "relacionados:vec:ref:Pedido",
        ],
    ),
    (
        "Envio",
        &[
            "pedido_id:ref:Pedido!",
            "destinatario_id:ref:opt:Cliente",
            "carrier:String",
        ],
    ),
];

pub(super) const REFERENCES: Scenario = Scenario {
    name: "references",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: REFERENCE_ENTITIES,
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const REFERENCES_DB: Scenario = Scenario {
    name: "references_db",
    db: true,
    ..REFERENCES
};

/// [`REFERENCES_DB`]'s shapes under other names: `#[sqlx::test]` names its database after the
/// test's path, so two scenarios with the same entities collide on one server when they run at once.
pub(super) const REFERENCES_EVENTS: Scenario = Scenario {
    name: "references_events",
    db: true,
    events: Some("db"),
    entities: &[
        (
            "Proveedor",
            &[
                "name:Name:String",
                "email:String!",
                "matriz_id:ref:opt:Proveedor",
            ],
        ),
        (
            "Compra",
            &[
                "proveedor_id:ref:Proveedor",
                "approver_id:ref:opt:Proveedor",
                "total:i64",
                "origen_id:ref:opt:Compra",
                // Fase 32: sets, written by the unit of work.
                "proveedores:vec:ref:Proveedor",
                "relacionadas:vec:ref:Compra",
            ],
        ),
        (
            "Entrega",
            &[
                "compra_id:ref:Compra!",
                "destinatario_id:ref:opt:Proveedor",
                "carrier:String",
            ],
        ),
    ],
    ..REFERENCES
};

pub(super) const POSTGRES_EVERY_TYPE: Scenario = Scenario {
    name: "postgres_every_type",
    db: true,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[
        ("Email", "String", Some("ana@ejemplo.es")),
        // Fase 31: a composite one, one column per field.
        (
            "Direccion",
            "calle:String ciudad:String cp:opt:String numero:i64",
            None,
        ),
    ],
    mails: &[],
    use_cases: &[("Producto", "archive_producto")],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[
        (
            "Producto",
            &[
                "title:String",
                "sku:String!",
                "price:i64!",
                "rating:f64",
                "active:bool",
                "ref_id:Uuid",
                "published_at:DateTime",
                "summary:opt:String",
                "views:opt:i64",
                "expires_at:opt:DateTime",
                "tags:vec:String",
                "scores:vec:i64",
                "meta:map",
            ],
        ),
        (
            "Cliente",
            &[
                "email:Email",
                "name:Name:String",
                "code:Code:String!",
                // 27.16: a unique email, seeded fresh in the form its rule asks for.
                "alert:Alert:email!",
                "age:Age:i64",
                "joined:Joined:DateTime",
                "middle:MiddleName:opt:String",
                "labels:Label:vec:String",
                "address:Direccion",
                "status:Status:enum:Active/Inactive",
            ],
        ),
        ("Billete", &["state:State:enum:Open/Closed"]),
    ],
    // 27.17: a generated unique `String`, and defaults of a `bool` and an `f64`.
    shapes: &[(
        "Producto",
        &[],
        &[],
        &[],
        &["active=true", "rating=2"],
        &["sku"],
        None,
    )],
    role_only: &[],
    portada: None,
    blocks: &[],
};

pub(super) const EVENTS_DB: Scenario = Scenario {
    name: "events_db",
    db: true,
    events: Some("db"),
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[
        // Fase 31: a composite one, one column per field.
        (
            "Direccion",
            "calle:String ciudad:String cp:opt:String numero:i64",
            None,
        ),
    ],
    mails: &[],
    use_cases: &[("Producto", "publish_producto")],
    transitions: &[],
    entity_events: &[("Producto", "producto_published")],
    internal_use_cases: &[],
    // 27.14: it holds two use cases, built from `cableado` (with the caller in auth projects).
    consumers: &[(
        "notify_new_producto",
        &["producto_creado", "producto_published"],
        &["obtener_producto", "listar_productos"],
    )],
    entities: &[(
        "Producto",
        &[
            "name:Name:String",
            "sku:Sku:String!",
            "price:i64",
            "status:Status:enum:Draft/Published",
            "tags:vec:String",
            "released_at:opt:DateTime",
            "meta:map",
            "origin:Direccion",
        ],
    )],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// [`EVENTS_DB`] in an auth project (Phase 16.4): the unit-of-work writes take the caller too,
/// and the worker builds without one. With a transition that emits its own event and needs a role
/// (27.12), and an internal one (27.13).
pub(super) const AUTH_OIDC_EVENTS: Scenario = Scenario {
    name: "auth_oidc_events",
    auth: Some("oidc"),
    // 27.13: `agotar`, internal — the worker's.
    transitions: &[
        (
            "Producto",
            "cancelar",
            Some("producto_cancelado"),
            &["admin"],
            false,
            false,
        ),
        ("Producto", "agotar", None, &[], true, false),
    ],
    access: &[(
        "Producto",
        &["listar_productos"],
        &["borrar_producto=admin"],
    )],
    ..EVENTS_DB
};

/// `events_db` on the `kafka` transport (Phase 13.5): the worker's registry wires `puerto-kafka`,
/// the outbox migration has no `entregas_eventos`, `docker-compose.yml` runs Redpanda.
pub(super) const EVENTS_KAFKA: Scenario = Scenario {
    name: "events_kafka",
    events: Some("kafka"),
    ..EVENTS_DB
};

/// `events_db` with mails the worker sends (Phase 14.4): one on two events of `Producto`, its fields
/// taken from the snapshot (VO, enum, `Option<DateTime>`; `Vec` and map left out), and one with
/// fields named after `--`. Plus a mail nothing sends, which the registry leaves out.
pub(super) const EVENTS_MAIL: Scenario = Scenario {
    name: "events_mail",
    mails: &[
        (
            "producto_live",
            &[],
            &["producto_creado", "producto_published"],
            Some("sku"),
        ),
        (
            "price_alert",
            &["name:String", "price:i64"],
            &["producto_published"],
            Some("name"),
        ),
        ("digest", &[], &[], None),
    ],
    ..EVENTS_DB
};

/// [`EVENTS_MAIL`] on the `kafka` transport: each mail is a consumer group of its own.
pub(super) const EVENTS_MAIL_KAFKA: Scenario = Scenario {
    name: "events_mail_kafka",
    events: Some("kafka"),
    ..EVENTS_MAIL
};

/// `puerto nuevo --db --eventos db` and nothing else: the worker has to build before the first
/// scaffold (it named `infrastructure::db`, which only a scaffold declared). No `query!`, so no
/// database is needed.
pub(super) const EVENTS_FRESH: Scenario = Scenario {
    name: "events_fresh",
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[],
    ..EVENTS_DB
};

/// Two mails in a project without a database (Phase 14.3): every field type a mail can carry, the
/// `mail` blocks of both `lib.rs` opened by the first and extended by the second, `puerto-correo`
/// and its fakes, and each mail's render tests.
pub(super) const MAIL: Scenario = Scenario {
    name: "mail",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: true,
    shared_vos: &[],
    mails: &[
        (
            "welcome",
            &["name:String", "plan:opt:String", "seats:i64"],
            &[],
            None,
        ),
        (
            "receipt",
            &[
                "pedido_id:Uuid",
                "paid_at:DateTime",
                "total:f64",
                "gift:bool",
                "note:opt:String",
                "points:opt:i64",
                "express:opt:bool",
                "discount:opt:f64",
                "shipped_at:opt:DateTime",
            ],
            &[],
            None,
        ),
    ],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// `puerto nuevo --auth oidc` (Phase 16.4): the `User` entity in memory, the provisioning
/// authenticator and its tests, `GET /me` in the spec the frontend is typed from, Keycloak in a
/// `docker-compose.yml` of its own. The Saludo demo is `public`. Two scaffolds: protected routes
/// (`BearerAuth`, `actor`, 401/403/503) and the route tests that prove them.
pub(super) const AUTH_OIDC: Scenario = Scenario {
    name: "auth_oidc",
    db: false,
    events: None,
    auth: Some("oidc"),
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    // Protected by default: its params carry the caller.
    use_cases: &[("Producto", "publish_producto")],
    // 27.12: a transition that needs two roles, and one any caller with a session can make.
    transitions: &[
        (
            "Producto",
            "retirar",
            None,
            &["admin", "owner"],
            false,
            false,
        ),
        // 28.2: Pedido is owned, so its buyer pays it; only `admin` refunds it.
        ("Pedido", "pagar", None, &[], false, false),
        ("Pedido", "reembolsar", None, &["admin"], false, true),
    ],
    entity_events: &[],
    // 27.13: a use case only the backend calls — no caller, no field in ApiPedido.
    internal_use_cases: &[("Pedido", "close_pedido")],
    consumers: &[],
    entities: &[
        (
            "Producto",
            &[
                "name:Name:String",
                "sku:String!",
                "price:i64",
                "status:Status:enum:Draft/Live",
            ],
        ),
        ("Pedido", &["total:i64", "comprador_id:Uuid"]),
    ],
    // Producto: public reads, two roles on one route, a protected route with no role. Pedido: every
    // route protected, its list and its detail for `admin` only (27.8: the menu hides it, creating
    // goes to the panel).
    access: &[
        (
            "Producto",
            &["listar_productos", "obtener_producto"],
            &[
                "crear_producto=admin",
                "borrar_producto=admin",
                "borrar_producto=owner",
            ],
        ),
        (
            "Pedido",
            &[],
            &[
                "listar_pedidos=admin",
                "obtener_pedido=admin",
                "borrar_pedido=admin",
            ],
        ),
    ],
    // 28.2: its buyer does not delete it, only `admin` does.
    role_only: &[("Pedido", &["borrar_pedido"])],
    // 27.18: a Pedido is its buyer's — or admin's, the role of its detail.
    shapes: &[("Pedido", &[], &[], &[], &[], &[], Some("comprador_id"))],
    portada: None,
    blocks: &[],
};

/// Phase 20.6: what canasta has — references on a web slice of an auth project. The detail screen
/// loads each reference's label through its target's repository, so its tests (the role ones
/// included) hand it the targets.
pub(super) const REFERENCES_AUTH: Scenario = Scenario {
    name: "references_auth",
    db: false,
    events: None,
    auth: Some("oidc"),
    no_demo: true,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    // Fase 30: a team's manager is a user, a player's scout may be one.
    entities: &[
        (
            "Equipo",
            &[
                "nombre:String",
                "responsable_id:ref:Usuario",
                // Fase 32: a set of users.
                "miembros:vec:ref:Usuario",
            ],
        ),
        (
            "Jugador",
            &[
                "equipo_id:ref:Equipo",
                "dorsal:i64",
                "email:String",
                "ojeador_id:ref:opt:Usuario",
            ],
        ),
    ],
    // Equipo's detail for `admin` only (27.8): creating one goes to its list.
    access: &[
        (
            "Jugador",
            &["listar_jugadores", "obtener_jugador"],
            &["actualizar_jugador=admin", "borrar_jugador=admin"],
        ),
        ("Equipo", &[], &["obtener_equipo=admin"]),
    ],
    // canasta: one shirt number per team, listed by number; a player's email for signed-in callers.
    shapes: &[(
        "Jugador",
        &["equipo_id,dorsal"],
        &["-dorsal"],
        &["email"],
        &[],
        &[],
        None,
    )],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// [`REFERENCES_AUTH`] on Postgres: the unique over a reference and a number is a partial index,
/// its `#[sqlx::test]` hits it, and the seeds keep two rows apart.
pub(super) const REFERENCES_AUTH_DB: Scenario = Scenario {
    name: "references_auth_db",
    db: true,
    no_web: true,
    ..REFERENCES_AUTH
};

/// [`AUTH_OIDC`] with a database: `PgUserRepository` over runtime-checked queries (no query cache
/// needed) and the `usuarios` migration; its `#[sqlx::test]`s run under `make test/db`. Without the
/// demo: the strip once undid auth's module declarations.
pub(super) const AUTH_OIDC_DB: Scenario = Scenario {
    name: "auth_oidc_db",
    db: true,
    no_demo: true,
    no_web: true,
    // 36.2: the whole list of Pedidos, only to `admin` — in [`AUTH_OIDC`], each buyer lists theirs.
    // [`AUTH_LOCAL`] inherits it: the menu hides the list from who lacks the role.
    role_only: &[("Pedido", &["borrar_pedido", "listar_pedidos"])],
    ..AUTH_OIDC
};

/// `puerto nuevo --db --auth local` (Phase 16.6, 16.7): accounts and sessions in Postgres — the
/// local use cases, `/auth/*`, `SesionesPostgres` as the authenticator, the users and auth migrations —
/// the same access rules on two scaffolds as [`AUTH_OIDC`], and the frontend that signs in with a
/// password.
pub(super) const AUTH_LOCAL: Scenario = Scenario {
    name: "auth_local",
    auth: Some("local"),
    no_web: false,
    ..AUTH_OIDC_DB
};

/// `puerto nuevo --auth oidc --portada` with every block that is not a default one installed
/// (Fase 26, ADR-0028): each variant keeps its slot's contract, so the frontend still typechecks,
/// lints and passes the template's tests. Without a database: it runs in `make test/full`.
pub(super) const WEB_BLOCKS: Scenario = Scenario {
    name: "web_blocks",
    role_only: &[],
    portada: Some("/panel"),
    blocks: &[
        "acceso/centrado",
        "marco/superior",
        "panel/resumen",
        "perfil/banda",
        "tema/miel",
        "portada/producto",
        "cabecera/dividida",
        // 27.20: the public list of Producto, on the portada.
        "escaparate/tarjetas Producto",
    ],
    ..AUTH_OIDC
};

/// Local accounts under a portada: `/login` and `/registro` beside it in `main.tsx`, the sign-in
/// going back to the app. Needs Postgres (`make test/db`).
pub(super) const WEB_BLOCKS_LOCAL: Scenario = Scenario {
    name: "web_blocks_local",
    role_only: &[],
    portada: Some("/panel"),
    blocks: &["acceso/centrado", "portada/producto"],
    ..AUTH_LOCAL
};

/// The blocks without auth (the top frame without the user's menu), and the app under `/app`.
pub(super) const WEB_BLOCKS_PLAIN: Scenario = Scenario {
    name: "web_blocks_plain",
    role_only: &[],
    portada: Some("/app"),
    blocks: &[
        "marco/superior",
        "panel/resumen",
        "tema/pizarra",
        "portada/producto",
    ],
    ..WEB_CRUD
};

/// Generates the project, applies the scenario, and asserts the result compiles, **passes its own
/// `task lint`** and **its tests pass**. `cargo check` is not enough: T-01 only broke test targets,
/// and every generated project ships a `task lint` with `-D warnings` that a fresh `puerto nuevo`
/// used to fail.
fn assert_scenario_compiles(scenario: &Scenario) {
    let dir = scenario_workspace(scenario.name);
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();

    let output = generate_project(&format!("compile-{}", scenario.name), &dir).unwrap();
    apply_scenario(scenario, &output);
    assert_generated_project_is_clean(&output, &dir, scenario.name, &[]);
    cleanup(&dir);
}

/// Applies the scenario's shared VOs, entities and custom use cases to a generated project.
pub(super) fn apply_scenario(scenario: &Scenario, output: &Path) {
    if scenario.db {
        crate::generators::project::apply_db_to_new_project(output).unwrap();
    }
    if let Some(transport) = scenario.events {
        scaffold::apply_events_to_new_project(output, transport).unwrap();
    }
    // `puerto nuevo`'s order: auth last, after the strips.
    if scenario.no_demo {
        scaffold::apply_no_demo(output).unwrap();
    }
    if scenario.no_web {
        scaffold::apply_no_web(output).unwrap();
    } else {
        crate::generators::project::keep_web_blocks(output).unwrap();
    }
    if let Some(path) = scenario.portada {
        crate::generators::project::apply_portada(output, path).unwrap();
    }
    if let Some(mode) = scenario.auth {
        crate::generators::auth::apply_auth_to_new_project(output, mode).unwrap();
    }
    // `puerto nuevo`, and every later command that writes Rust, ends with `cargo fmt`: the next
    // step's patchers read formatted code, as they do for a user.
    let format = || crate::generators::format::format_project(output).unwrap();
    format();

    for (vo_name, inner, example) in scenario.shared_vos {
        if inner.contains(':') {
            let fields: Vec<String> = inner.split_whitespace().map(str::to_string).collect();
            scaffold::run_composite_value_object(vo_name, &fields, *example, output).unwrap();
        } else {
            scaffold::run_value_object(vo_name, inner, *example, output).unwrap();
        }
    }

    let shared_vos = puerto_toml::read(output).unwrap().value_object;

    for (entity, field_args) in scenario.entities {
        let parsed: Vec<puerto_toml::Field> = field_args
            .iter()
            .map(|arg| puerto_toml::parse_field_arg(arg).unwrap())
            .collect();
        let fields = puerto_toml::apply_shared_vo_inference(parsed, &shared_vos);
        crate::generators::types::validate_fields(&fields).unwrap();
        let access = scenario
            .access
            .iter()
            .find(|(name, _, _)| name == entity)
            .map(|(_, public, roles)| {
                let strings =
                    |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
                let role_only = scenario
                    .role_only
                    .iter()
                    .find(|(name, _)| name == entity)
                    .map(|(_, ucs)| strings(ucs))
                    .unwrap_or_default();
                scaffold::ScaffoldAccess::from_args(&strings(public), &strings(roles))
                    .unwrap()
                    .with_role_only(&role_only)
            })
            .unwrap_or_default();
        let shape = scenario
            .shapes
            .iter()
            .find(|(name, ..)| name == entity)
            .map(|(_, uniques, order, private, defaults, generated, owner)| {
                let strings =
                    |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
                scaffold::EntityShape::from_args(
                    &strings(uniques),
                    &strings(order),
                    &strings(private),
                )
                .with_server_set(&strings(defaults), &strings(generated))
                .with_owner(owner.map(str::to_string))
            })
            .unwrap_or_default();
        scaffold::run_scaffold_with_options(
            entity,
            output,
            &fields,
            OverwritePolicy::Ask,
            &access,
            &shape,
        )
        .unwrap();
        format();
    }

    for (entity, action) in scenario.use_cases {
        scaffold::run_use_case(entity, action, output).unwrap();
        format();
    }

    for (entity, action) in scenario.internal_use_cases {
        scaffold::run_use_case_with(entity, action, true, output).unwrap();
        format();
    }

    for (entity, verb, event, roles, internal, role_only) in scenario.transitions {
        let roles: Vec<String> = roles.iter().map(|r| r.to_string()).collect();
        scaffold::run_generate_transition(
            entity, verb, *event, &roles, *internal, *role_only, output,
        )
        .unwrap();
        format();
    }

    for (entity, event) in scenario.entity_events {
        scaffold::run_generate_event(entity, event, output).unwrap();
        format();
    }

    for (name, events, uses) in scenario.consumers {
        let strings = |args: &[&str]| args.iter().map(|a| a.to_string()).collect::<Vec<_>>();
        scaffold::run_generate_consumer_with(name, &strings(events), &strings(uses), output)
            .unwrap();
        format();
    }

    for (name, field_args, on, to) in scenario.mails {
        let field_args: Vec<String> = field_args.iter().map(|f| f.to_string()).collect();
        let on: Vec<String> = on.iter().map(|e| e.to_string()).collect();
        scaffold::run_generate_mail_on(name, &field_args, &on, *to, output).unwrap();
        format();
    }

    for block in scenario.blocks {
        // A block that shows an entity names it after a space: `escaparate/tarjetas Producto`.
        let (id, entity) = block
            .split_once(' ')
            .map_or((*block, None), |(id, entity)| (id, Some(entity)));
        crate::generators::blocks::run_install_for(id, entity, output, OverwritePolicy::Force)
            .unwrap();
    }
}

/// Runs `cargo clippy --all-targets -D warnings` and `cargo test` inside a generated project.
///
/// A target dir **per scenario**: every generated project names its crates
/// `business`/`infrastructure`/`presentation`, so a shared target dir has them overwrite each
/// other's artifacts and fail for reasons unrelated to the code under test.
pub(super) fn assert_generated_project_is_clean(
    output: &Path,
    dir: &Path,
    name: &str,
    envs: &[(&str, &str)],
) {
    patch_runtime_crates(output);
    for args in [
        &[
            "clippy",
            "--workspace",
            "--all-targets",
            "--",
            "-D",
            "warnings",
        ][..],
        &["test", "--workspace"][..],
        // The project's own `task format`: generated code is formatted as it is written.
        &["fmt", "--all", "--", "--check"][..],
    ] {
        let result = std::process::Command::new("cargo")
            .args(args)
            .env("CARGO_TARGET_DIR", dir.join("target"))
            .envs(envs.iter().copied())
            .current_dir(output)
            .output()
            .expect("failed to run cargo");

        if !result.status.success() {
            eprintln!("stdout:\n{}", String::from_utf8_lossy(&result.stdout));
            eprintln!("stderr:\n{}", String::from_utf8_lossy(&result.stderr));
            panic!(
                "scenario '{name}': generated project failed `cargo {}`",
                args.join(" ")
            );
        }
    }

    if output.join("web").is_dir() {
        assert_spec_export_is_stable(output, dir, name, envs);
        assert_web_is_clean(output, name);
    }
}

/// Builds the project against the runtime crates in this checkout, not the ones on crates.io: the
/// templates and an unreleased runtime change are tested together (ADR-0017). Done by the harness
/// only — `puerto nuevo` never writes it, so it is not in the snapshots either.
pub(super) fn patch_runtime_crates(output: &Path) {
    let crates = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..");
    let manifest = output.join("Cargo.toml");
    let mut src = fs::read_to_string(&manifest).unwrap();
    let mut patch = String::from("\n[patch.crates-io]\n");
    // `puerto-nucleo` lives in `crates/nucleo`, `puerto-web` in `crates/web`, … Only the crates the
    // project names: an unused patch is a cargo warning in every build.
    for name in crate::runtime::RUNTIME_CRATES {
        if !src.contains(&format!("{name} = ")) {
            continue;
        }
        let dir = name.trim_start_matches("puerto-");
        let path = crates.join(dir).canonicalize().unwrap();
        patch.push_str(&format!("{name} = {{ path = {path:?} }}\n"));
    }
    if !src.contains("[patch.crates-io]") {
        src.push_str(&patch);
        fs::write(&manifest, src).unwrap();
    }
}

/// The first `cargo test` of a web project wrote `docs/api/openapi.json` (it was missing). A
/// second run compares against it: the strict path users hit after every scaffold, and proof the
/// export is deterministic.
fn assert_spec_export_is_stable(output: &Path, dir: &Path, name: &str, envs: &[(&str, &str)]) {
    assert!(
        output.join("docs/api/openapi.json").exists(),
        "scenario '{name}': `cargo test` did not export docs/api/openapi.json"
    );
    let result = std::process::Command::new("cargo")
        .args(["test", "-p", "api", "openapi"])
        .env("CARGO_TARGET_DIR", dir.join("target"))
        .envs(envs.iter().copied())
        .current_dir(output)
        .output()
        .expect("failed to run cargo");
    if !result.status.success() {
        eprintln!("stdout:\n{}", String::from_utf8_lossy(&result.stdout));
        eprintln!("stderr:\n{}", String::from_utf8_lossy(&result.stderr));
        panic!("scenario '{name}': the exported spec differs from the one just written");
    }
}

/// Workspace for one scenario: the generated project plus its cargo target dir.
///
/// Lives under Puerto's own `target/`, not `/tmp`: a full build tree per scenario is gigabytes,
/// and on a tmpfs `/tmp` the matrix hits "Disk quota exceeded" instead of reporting on the code.
/// `cleanup()` on success keeps the total bounded by how many scenarios run concurrently; a
/// failing scenario keeps its tree for inspection.
pub(super) fn scenario_workspace(scenario: &str) -> PathBuf {
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../../target/compile-matrix")
        .join(scenario);
    let _ = fs::create_dir_all(&root);
    root
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_no_demo_then_scaffold() {
    assert_scenario_compiles(&NO_DEMO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_all_primitive_field_types() {
    assert_scenario_compiles(&PRIMITIVES);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_uuid_value_object() {
    assert_scenario_compiles(&UUID_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_option_and_vec_primitives() {
    assert_scenario_compiles(&OPT_VEC_PRIM);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_plain_and_unique_value_objects() {
    assert_scenario_compiles(&PLAIN_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_option_and_vec_value_objects() {
    assert_scenario_compiles(&OPT_VEC_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_enum_value_object() {
    assert_scenario_compiles(&ENUM_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_shared_value_objects() {
    assert_scenario_compiles(&SHARED_VO);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_references_between_entities() {
    assert_scenario_compiles(&REFERENCES);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_multiple_entities() {
    assert_scenario_compiles(&MULTI_ENTITY);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_every_value_object_kind_at_once() {
    assert_scenario_compiles(&VO_KITCHEN_SINK);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_domain_first_layered_flow_and_fields() {
    // T-06: `generate domain -- fields` persists the fields, so the three later layered commands
    // read them back from puerto.toml. Before, every one of them was field-blind and this flow
    // could only ever produce the default `name: String`.
    let dir = scenario_workspace("layered_fields");
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();

    let output = generate_project("compile-layered-fields", &dir).unwrap();

    let fields: Vec<puerto_toml::Field> = [
        "amount:i64",
        "reference:Reference:String",
        "note:opt:String",
    ]
    .iter()
    .map(|arg| puerto_toml::parse_field_arg(arg).unwrap())
    .collect();

    // Formatted after each step, like the CLI. Until the last layer exists a declared module has
    // no file and `cargo fmt` fails — the CLI only warns, so the steps here ignore it too.
    let format = || {
        let _ = crate::generators::format::format_project(&output);
    };
    format();
    scaffold::run_generate_domain("Factura", &output, &fields).unwrap();
    format();
    scaffold::run_generate_application("Factura", &output, OverwritePolicy::Ask).unwrap();
    format();
    scaffold::run_generate_repository("Factura", &output, OverwritePolicy::Ask).unwrap();
    format();
    scaffold::run_generate_presentation("Factura", &output, OverwritePolicy::Ask).unwrap();
    format();
    // The flow's last step in a web project: `generated/*` already routes Factura.
    scaffold::run_generate_web("Factura", &output, OverwritePolicy::Ask).unwrap();

    assert_generated_project_is_clean(&output, &dir, "layered_fields", &[]);

    cleanup(&dir);
}

// ── T-13: review fixes — matrix gaps ──────────────────────────────────────

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_enum_vo_as_only_string_field() {
    // The create test asserted `.value()` on the first String-typed field — an enum VO has
    // `as_str()`, so an entity whose only String was an enum never compiled its tests.
    assert_scenario_compiles(&ENUM_ONLY);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_mails_and_renders_their_templates() {
    assert_scenario_compiles(&MAIL);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_with_custom_use_case_after_scaffold() {
    // `generate use-case` on a scaffolded entity wired the use case into `ProductoApi` in
    // bootstrap.rs while routes.rs had no such field (E0560).
    assert_scenario_compiles(&CUSTOM_USE_CASE);
}

// ── Phase 9: the web frontend ─────────────────────────────────────────────

/// Runs the frontend's own checks inside a generated project: install, wire types from the
/// exported spec, typecheck, Biome, dependency-cruiser, `bun test` and a production build. Needs
/// `bun` on `PATH`, and `docs/api/openapi.json` (`assert_generated_project_is_clean` exports it,
/// then calls this for every web scenario: a few seconds each, against minutes of `cargo`).
///
/// `bun run lint` runs **before** any formatting: the generated TypeScript must come out
/// Biome-clean. (`task web:sync` formats too — the net for names long enough to wrap a line.)
fn assert_web_is_clean(output: &Path, name: &str) {
    let web = output.join("web");
    // 27.3: the messages are the user's; the tests read them from mensajes.ts, so a changed one
    // must not break them.
    if let Ok(contexts) = fs::read_dir(web.join("src/contextos")) {
        for context in contexts.flatten() {
            let path = context.path().join("mensajes.ts");
            if let Ok(messages) = fs::read_to_string(&path) {
                let changed = messages
                    .replace("Estos valores ya están en uso", "Ya hay uno igual")
                    .replace(": campo obligatorio\"", ": rellénalo\"");
                fs::write(&path, changed).unwrap();
            }
        }
    }
    for args in [
        &["install"][..],
        &["run", "openapi:types"][..],
        &["run", "typecheck"][..],
        &["run", "lint"][..],
        &["run", "lint:arch"][..],
        &["test"][..],
        &["run", "build"][..],
    ] {
        let result = std::process::Command::new("bun")
            .args(args)
            .current_dir(&web)
            .output()
            .expect("bun not found — the web scenarios need it on PATH (https://bun.sh)");

        if !result.status.success() {
            eprintln!("stdout:\n{}", String::from_utf8_lossy(&result.stdout));
            eprintln!("stderr:\n{}", String::from_utf8_lossy(&result.stderr));
            panic!(
                "scenario '{name}': generated frontend failed `bun {}`",
                args.join(" ")
            );
        }
    }
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn web_shell_passes_its_own_checks() {
    let dir = scenario_workspace("web_shell");
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();

    let output = generate_project("compile-web-shell", &dir).unwrap();
    // What `puerto nuevo` does last.
    crate::generators::format::format_project(&output).unwrap();
    assert_generated_project_is_clean(&output, &dir, "web_shell", &[]);
    assert!(output.join("web/src/api/esquema.d.ts").exists());

    cleanup(&dir);
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn web_crud_slice_passes_its_own_checks() {
    assert_scenario_compiles(&WEB_CRUD);
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn web_every_type_slice_passes_its_own_checks() {
    assert_scenario_compiles(&WEB_EVERY_TYPE);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_without_the_web_frontend() {
    assert_scenario_compiles(&NO_WEB);
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn every_block_passes_the_checks_of_its_slot() {
    assert_scenario_compiles(&WEB_BLOCKS);
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn every_block_passes_the_checks_of_its_slot_without_auth() {
    assert_scenario_compiles(&WEB_BLOCKS_PLAIN);
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn compiles_an_oidc_auth_project() {
    assert_scenario_compiles(&AUTH_OIDC);
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn compiles_references_on_the_web_slice_of_an_auth_project() {
    assert_scenario_compiles(&REFERENCES_AUTH);
}

#[test]
#[ignore = "slow: compiles and tests a generated project"]
fn compiles_a_fresh_events_project_before_any_scaffold() {
    assert_scenario_compiles(&EVENTS_FRESH);
}

/// `PUERTO_TEST_DATABASE_URL` — a Postgres server URL **without** a database name, e.g.
/// `postgres://postgres:pg@localhost:55432`. `make test/db` starts one in Docker and sets it.
pub(super) fn test_database_server() -> Option<String> {
    std::env::var("PUERTO_TEST_DATABASE_URL")
        .ok()
        .map(|u| u.trim_end_matches('/').to_string())
        .filter(|u| !u.is_empty())
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_project_with_every_type_compiles_lints_and_passes_integration_tests() {
    // Nothing in the matrix generated a `--db` project, which is how `HashMap` columns, the Pg
    // repository test imports, timestamp round-trips and `unique` seeds all shipped broken.
    assert_postgres_scenario_is_clean(&POSTGRES_EVERY_TYPE, "puerto_matrix");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_unique_group_project_compiles_lints_and_passes_integration_tests() {
    // Phase 20.7: a unique over several fields, in the migration and against Postgres.
    assert_postgres_scenario_is_clean(&REFERENCES_AUTH_DB, "puerto_matrix_unique_group");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_references_project_compiles_lints_and_passes_integration_tests() {
    // Phase 18: foreign keys, a missing target → `MissingReference`, rows seeded through their
    // targets' own seeds.
    assert_postgres_scenario_is_clean(&REFERENCES_DB, "puerto_matrix_references");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_references_events_project_compiles_lints_and_passes_integration_tests() {
    assert_postgres_scenario_is_clean(&REFERENCES_EVENTS, "puerto_matrix_references_events");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_oidc_auth_project_compiles_lints_and_passes_integration_tests() {
    assert_postgres_scenario_is_clean(&AUTH_OIDC_DB, "puerto_matrix_auth_oidc");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_local_auth_project_compiles_lints_and_passes_integration_tests() {
    assert_postgres_scenario_is_clean(&AUTH_LOCAL, "puerto_matrix_auth_local");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_local_auth_under_a_portada_compiles_lints_and_passes_integration_tests() {
    assert_postgres_scenario_is_clean(&WEB_BLOCKS_LOCAL, "puerto_matrix_web_blocks_local");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_oidc_auth_events_project_compiles_lints_and_passes_integration_tests() {
    assert_postgres_scenario_is_clean(&AUTH_OIDC_EVENTS, "puerto_matrix_auth_oidc_events");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_events_project_compiles_lints_and_passes_integration_tests() {
    // Phase 13.3: units of work, the outbox migration and `events.rs` — the Pg unit of work's
    // tests write an entity and its `producto_created` row, and a taken `unique` writes neither.
    assert_postgres_scenario_is_clean(&EVENTS_DB, "puerto_matrix_events");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/kafka`"]
fn kafka_events_project_compiles_lints_and_passes_integration_tests() {
    // Phase 13.5: the worker against `puerto-kafka`, and the outbox migration without
    // `entregas_eventos` under the Pg unit of work's tests. No broker is needed to build and
    // test it; `make test/kafka` provides the Postgres it compiles against.
    assert_postgres_scenario_is_clean(&EVENTS_KAFKA, "puerto_matrix_events_kafka");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_events_project_with_mails_compiles_lints_and_passes_its_tests() {
    // Phase 14.4: the mail consumers, their registry wiring and the `correos_enviados` migration.
    assert_postgres_scenario_is_clean(&EVENTS_MAIL, "puerto_matrix_events_mail");
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/kafka`"]
fn kafka_events_project_with_mails_compiles_lints_and_passes_its_tests() {
    assert_postgres_scenario_is_clean(&EVENTS_MAIL_KAFKA, "puerto_matrix_events_mail_kafka");
}

/// A `--db` scenario against a real database: `query!` checks its SQL at compile time, so the
/// schema has to exist before the project builds.
fn assert_postgres_scenario_is_clean(scenario: &Scenario, database: &str) {
    assert_edited_postgres_scenario_is_clean(scenario, database, |_| {});
}

/// [`assert_postgres_scenario_is_clean`], with `edit` applied to the project before it builds —
/// what a user writes by hand after the generators.
pub(super) fn assert_edited_postgres_scenario_is_clean(
    scenario: &Scenario,
    database: &str,
    edit: impl FnOnce(&Path),
) {
    let Some(server) = test_database_server() else {
        eprintln!("PUERTO_TEST_DATABASE_URL not set — skipping (run `make test/db`)");
        return;
    };
    let dir = scenario_workspace(scenario.name);
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();

    let output = generate_project(
        &format!("compile-{}", scenario.name.replace('_', "-")),
        &dir,
    )
    .unwrap();
    apply_scenario(scenario, &output);
    edit(&output);

    let database_url = format!("{server}/{database}");
    for args in [
        &["database", "drop", "-y"][..],
        &["database", "create"][..],
        &["migrate", "run", "--source", "migraciones"][..],
    ] {
        let status = std::process::Command::new("sqlx")
            .args(args)
            .env("DATABASE_URL", &database_url)
            .current_dir(&output)
            .status()
            .expect("sqlx CLI not found — cargo install sqlx-cli");
        assert!(status.success(), "`sqlx {}` failed", args.join(" "));
    }

    assert_generated_project_is_clean(
        &output,
        &dir,
        scenario.name,
        &[("DATABASE_URL", &database_url), ("SQLX_OFFLINE", "false")],
    );
    assert_startup_reports_a_database_that_is_down(&output, &dir, &database_url);

    cleanup(&dir);
}

/// Phase 15.2: the server (and the worker) started against a database that is down end with a
/// message and a hint — exit code 1, no panic, no password.
fn assert_startup_reports_a_database_that_is_down(output: &Path, dir: &Path, database_url: &str) {
    let binaries: Vec<(&str, &str)> = [
        ("api", "presentacion/api"),
        ("worker", "presentacion/worker"),
    ]
    .into_iter()
    .filter(|(_, dir)| output.join(dir).is_dir())
    .collect();
    for (binary, member) in &binaries {
        let built = std::process::Command::new("cargo")
            .args(["build", "-p", binary])
            .env("CARGO_TARGET_DIR", dir.join("target"))
            .env("DATABASE_URL", database_url)
            .env("SQLX_OFFLINE", "false")
            .current_dir(output)
            .status()
            .expect("failed to run cargo");
        assert!(built.success(), "cargo build -p {binary}");

        // The executable is the `[[bin]]` name when the member declares one (api's is the
        // project's name), else the package's.
        let manifest = fs::read_to_string(output.join(member).join("Cargo.toml")).unwrap();
        let executable = manifest
            .split_once("[[bin]]")
            .and_then(|(_, bin)| bin.lines().find_map(|l| l.strip_prefix("name = ")))
            .map_or(*binary, |name| name.trim_matches('"'));

        // Nothing listens on port 1.
        let run = std::process::Command::new(dir.join("target/debug").join(executable))
            .env("DATABASE_URL", "postgres://devuser:s3cret@127.0.0.1:1/shop")
            .env("PUERTO_BANNER", "false")
            .current_dir(output)
            .output()
            .expect("failed to start the binary");
        let stderr = String::from_utf8_lossy(&run.stderr);
        assert_eq!(run.status.code(), Some(1), "{binary}: {stderr}");
        assert!(stderr.contains("127.0.0.1:1/shop"), "{binary}: {stderr}");
        assert!(
            stderr.contains("¿está arrancada la base de datos? `task docker-compose:up`"),
            "{binary}: {stderr}"
        );
        assert!(!stderr.contains("panicked"), "{binary}: {stderr}");
        assert!(!stderr.contains("s3cret"), "{binary}: {stderr}");
    }
}

// ── Fase 33.3: `generar campo` over code written by hand ──────────────────

/// `Articulo`, with a custom use case: `generar campo` adds two fields after the hand edits.
pub(super) const ADDED_FIELDS: Scenario = Scenario {
    name: "added_fields",
    db: false,
    events: None,
    auth: None,
    access: &[],
    no_demo: false,
    no_web: false,
    shared_vos: &[],
    mails: &[],
    use_cases: &[("Articulo", "rebajar_articulo")],
    transitions: &[],
    entity_events: &[],
    internal_use_cases: &[],
    consumers: &[],
    entities: &[("Articulo", &["titulo:String", "precio:i64"])],
    shapes: &[],
    role_only: &[],
    portada: None,
    blocks: &[],
};

/// `Lote` in Postgres, and `Almacen` for the optional reference `generar campo` adds.
pub(super) const ADDED_FIELDS_DB: Scenario = Scenario {
    name: "postgres_added_fields",
    db: true,
    no_web: true,
    use_cases: &[],
    entities: &[
        ("Almacen", &["nombre:String"]),
        ("Lote", &["codigo:String", "cantidad:i64"]),
    ],
    ..ADDED_FIELDS
};

/// What a user does after the generators: a business rule in the model, a line at the end of the
/// repository — then `puerto generar campo`, and the `cargo fmt` that ends every command.
fn add_fields_over_hand_edits(output: &Path, entity: &str, args: &[&str]) {
    let snake = crate::generators::naming::pascal_to_snake(entity);
    let modelo = output.join(format!("contextos/{snake}/dominio/src/modelo.rs"));
    let src = fs::read_to_string(&modelo).unwrap();
    let at = src.find("#[cfg(test)]").unwrap();
    let rule = format!(
        "impl {entity} {{\n    pub fn sin_cambios(&self) -> bool {{\n        self.creado_en == self.actualizado_en\n    }}\n}}\n\n"
    );
    fs::write(&modelo, format!("{}{rule}{}", &src[..at], &src[at..])).unwrap();
    let repositorio = output.join(format!(
        "contextos/{snake}/infraestructura/src/repositorio.rs"
    ));
    let src = fs::read_to_string(&repositorio).unwrap();
    fs::write(&repositorio, format!("{src}// escrito a mano\n")).unwrap();

    let fields: Vec<puerto_toml::Field> = args
        .iter()
        .map(|arg| puerto_toml::parse_field_arg(arg).unwrap())
        .collect();
    crate::generators::add_field::run_add_fields(entity, output, &fields).unwrap();
    crate::generators::format::format_project(output).unwrap();
    assert!(
        fs::read_to_string(&modelo)
            .unwrap()
            .contains("pub fn sin_cambios")
    );
}

/// 36.4 (ADR-0029): a dependency more for `crear_<entidad>` — the field in its `Impl`, one line in
/// the `caso_de_uso` of its tests and one in `casos.rs` — and nothing else to change.
fn give_crear_a_second_dependency(output: &Path, entity: &str) {
    let snake = crate::generators::naming::pascal_to_snake(entity);
    let edit = |rel: String, from: &str, to: &str| {
        let path = output.join(&rel);
        let src = fs::read_to_string(&path).unwrap();
        assert_eq!(src.matches(from).count(), 1, "{rel}: {from}\n{src}");
        fs::write(&path, src.replace(from, to)).unwrap();
    };
    let use_case = format!("contextos/{snake}/aplicacion/src/crear_{snake}.rs");
    edit(
        use_case.clone(),
        &format!("    pub repositorio: Arc<dyn Repositorio{entity}>,\n}}"),
        &format!(
            "    pub repositorio: Arc<dyn Repositorio{entity}>,\n    pub catalogo: Arc<dyn Repositorio{entity}>,\n}}"
        ),
    );
    edit(
        use_case,
        "            repositorio: Arc::new(repositorio),\n",
        &format!(
            "            repositorio: Arc::new(repositorio),\n            catalogo: Arc::new(MockRepositorio{entity}::new()),\n"
        ),
    );
    edit(
        format!("presentacion/cableado/src/{snake}/casos.rs"),
        &format!(
            "Crear{entity}Impl {{\n        repositorio: Arc::clone(&dependencias.repositorio),\n"
        ),
        &format!(
            "Crear{entity}Impl {{\n        repositorio: Arc::clone(&dependencias.repositorio),\n        catalogo: Arc::clone(&dependencias.repositorio),\n"
        ),
    );
}

#[test]
#[ignore = "slow: compiles a generated project, then installs, lints and tests its frontend"]
fn compiles_after_generar_campo_over_hand_written_code() {
    let dir = scenario_workspace(ADDED_FIELDS.name);
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();
    let output = generate_project("compile-added-fields", &dir).unwrap();
    apply_scenario(&ADDED_FIELDS, &output);

    give_crear_a_second_dependency(&output, "Articulo");
    add_fields_over_hand_edits(&output, "Articulo", &["stock:i64", "nota:opt:String"]);
    let crear =
        fs::read_to_string(output.join("contextos/articulo/aplicacion/src/crear_articulo.rs"))
            .unwrap();
    assert!(
        crear.contains("pub catalogo:")
            && crear.contains("catalogo: Arc::new(MockRepositorioArticulo::new())"),
        "{crear}"
    );

    assert_generated_project_is_clean(&output, &dir, ADDED_FIELDS.name, &[]);
    cleanup(&dir);
}

#[test]
#[ignore = "slow: needs Postgres — run via `make test/db`"]
fn postgres_generar_campo_project_compiles_lints_and_passes_integration_tests() {
    // The `ALTER TABLE` migration runs after the `CREATE TABLE` one, and the repository's checked
    // queries agree with the table it leaves.
    assert_edited_postgres_scenario_is_clean(
        &ADDED_FIELDS_DB,
        "puerto_matrix_added_fields",
        |output| {
            add_fields_over_hand_edits(
                output,
                "Lote",
                &[
                    "peso:f64",
                    "nota:opt:String",
                    "almacen_id:ref:opt:Almacen",
                    "estado:Estado:enum:Abierto/Cerrado",
                ],
            );
        },
    );
}

// ── Fase 36.3: the rule of a transition, written by hand ──────────────────

/// `Producto` with a state and the transition `archivar`, in memory and without web.
pub(super) const TRANSITION_RULE: Scenario = Scenario {
    name: "transition_rule",
    no_web: true,
    use_cases: &[],
    transitions: &[("Producto", "archivar", None, &[], false, false)],
    entities: &[(
        "Producto",
        &["title:String", "estado:Estado:enum:Borrador/Publicado"],
    )],
    ..ADDED_FIELDS
};

#[test]
#[ignore = "slow: compiles a generated project"]
fn passes_its_tests_after_writing_a_rule_that_rejects_the_default_state() {
    let dir = scenario_workspace(TRANSITION_RULE.name);
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();
    let output = generate_project("compile-transition-rule", &dir).unwrap();
    apply_scenario(&TRANSITION_RULE, &output);

    // What the hint says: the rule, the entity the tests start from, and no `#[ignore]`.
    let domain = output.join("contextos/producto/dominio/src/archivar.rs");
    let src = fs::read_to_string(&domain).unwrap();
    let rule = "        if self.estado != crate::valores::Estado::Publicado {\n            return \
                Err(ErrorProducto::Validacion(\"no_se_puede_archivar\".into()));\n        }\n";
    let src = src
        .replace(
            "        Ok(())\n    }\n\n    pub fn archivar",
            &format!("{rule}        Ok(())\n    }}\n\n    pub fn archivar"),
        )
        .replace(
            "    pub fn para_archivar() -> Producto {\n        Self::aleatorio()",
            "    pub fn para_archivar() -> Producto {\n        Self::new()\n            \
             .con_estado(crate::valores::Estado::Publicado)\n            .construir()",
        );
    assert!(
        src.contains(rule) && src.contains("Estado::Publicado)\n"),
        "{src}"
    );
    let use_case = output.join("contextos/producto/aplicacion/src/archivar_producto.rs");
    for path in [&domain, &use_case] {
        let text = if path == &domain {
            src.clone()
        } else {
            fs::read_to_string(path).unwrap()
        };
        assert!(
            text.contains("#[ignore = \"escribe la regla\"]\n"),
            "{}",
            path.display()
        );
        fs::write(
            path,
            text.replace("    #[ignore = \"escribe la regla\"]\n", ""),
        )
        .unwrap();
    }

    assert_generated_project_is_clean(&output, &dir, TRANSITION_RULE.name, &[]);
    cleanup(&dir);
}