elinvar 0.1.1

Find the holes in a design before you build it: a relational model finder, its command line, and an MCP server
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
//! Direct single-state database dump auditor (`elinvar audit`, N32, R7).
//!
//! Parses a SQL schema (plus optional `--with` sidecar views and Alloy promises)
//! and a SQL dump of `INSERT` statements, then evaluates every table rule and
//! every single-state promise directly in Rust without invoking the SAT solver.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;

use elinvar_engine::logic::{
    Error, FormulaKind, Instance, Place, TemporalOp, Trace, Universe, evaluate_trace_at,
};
use serde_json::{Value, json};

use crate::cli::verbs::{Output, error_output};

/// Options for `elinvar audit`.
#[derive(Clone, Debug, Default)]
pub struct AuditOptions {
    /// Optional `--tables` slice.
    pub tables: Vec<String>,
    /// With `--tables`, include tables pointing into the slice.
    pub with_referencing: bool,
    /// Optional sidecar `.als` promises appended to the imported model.
    pub extra_als: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum DumpVal {
    Null,
    Bool(bool),
    Int(i64),
    Str(String),
}

impl DumpVal {
    fn display(&self) -> String {
        match self {
            DumpVal::Null => "NULL".to_string(),
            DumpVal::Bool(b) => b.to_string(),
            DumpVal::Int(n) => n.to_string(),
            DumpVal::Str(s) => format!("'{s}'"),
        }
    }
}

#[derive(Clone, Debug)]
struct RawInsertStmt {
    line: usize,
    sql: String,
}

#[derive(Clone, Debug)]
struct RuleViolation {
    rule: String,
    table: Option<String>,
    detail: String,
    line: Option<usize>,
}

fn audit_parse_error(msg: String) -> Output {
    let text = format!("elinvar audit: {msg}\n");
    Output {
        status: 3,
        text: text.clone(),
        json: json!({
            "elinvar": 1,
            "command": "audit",
            "errors": [{
                "code": "audit.parse",
                "message": msg,
                "fix": "pass a SQL dump containing standard INSERT INTO ... VALUES (...) statements",
            }],
            "story": text,
        }),
    }
}

/// Splits a SQL dump into semicolon-terminated statements while preserving
/// 1-based starting line numbers and skipping `--` and `/* ... */` comments.
fn split_dump_statements(src: &str) -> Vec<RawInsertStmt> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut cur_line: Option<usize> = None;
    let mut in_str = false;
    let mut in_block_comment = false;

    for (idx, raw_line) in src.lines().enumerate() {
        let line_no = idx + 1;
        let trimmed_start = raw_line.trim_start();
        if !in_str && !in_block_comment && trimmed_start.starts_with('\\') {
            // Skip psql meta-commands such as `\connect` / `\restrict`.
            continue;
        }
        let mut chars = raw_line.chars().peekable();
        while let Some(c) = chars.next() {
            if in_block_comment {
                if c == '*' && chars.peek() == Some(&'/') {
                    chars.next();
                    in_block_comment = false;
                }
                continue;
            }
            if in_str {
                cur.push(c);
                if c == '\'' {
                    if chars.peek() == Some(&'\'') {
                        cur.push(chars.next().expect("peeked"));
                    } else {
                        in_str = false;
                    }
                }
                continue;
            }
            if c == '-' && chars.peek() == Some(&'-') {
                break;
            }
            if c == '/' && chars.peek() == Some(&'*') {
                chars.next();
                in_block_comment = true;
                continue;
            }
            if c == '\'' {
                if cur_line.is_none() {
                    cur_line = Some(line_no);
                }
                in_str = true;
                cur.push(c);
            } else if c == ';' {
                let s = cur.trim().to_string();
                if !s.is_empty() {
                    out.push(RawInsertStmt {
                        line: cur_line.unwrap_or(line_no),
                        sql: s,
                    });
                }
                cur.clear();
                cur_line = None;
            } else {
                if !c.is_whitespace() && cur_line.is_none() {
                    cur_line = Some(line_no);
                }
                cur.push(c);
            }
        }
        if !cur.is_empty() {
            cur.push(' ');
        }
    }
    let tail = cur.trim().to_string();
    if !tail.is_empty() {
        out.push(RawInsertStmt {
            line: cur_line.unwrap_or(1),
            sql: tail,
        });
    }
    out
}

fn split_once_kw_top<'a>(s: &'a str, kw: &str) -> Option<(&'a str, &'a str)> {
    let bytes = s.as_bytes();
    let klen = kw.len();
    let mut i = 0;
    let mut in_str = false;
    let mut depth = 0usize;
    while i < bytes.len() {
        let b = bytes[i];
        if in_str {
            if b == b'\'' {
                if bytes.get(i + 1) == Some(&b'\'') {
                    i += 2;
                    continue;
                }
                in_str = false;
            }
            i += 1;
            continue;
        }
        if b == b'\'' {
            in_str = true;
            i += 1;
            continue;
        }
        if b == b'(' {
            depth += 1;
            i += 1;
            continue;
        }
        if b == b')' {
            depth = depth.saturating_sub(1);
            i += 1;
            continue;
        }
        if depth == 0 && i + klen <= bytes.len() {
            let before_ok =
                i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
            let after_ok = i + klen == bytes.len()
                || !(bytes[i + klen].is_ascii_alphanumeric() || bytes[i + klen] == b'_');
            if before_ok && after_ok && s[i..i + klen].eq_ignore_ascii_case(kw) {
                return Some((&s[..i], &s[i + klen..]));
            }
        }
        i += 1;
    }
    None
}

fn split_value_tuples(s: &str) -> Option<Vec<&str>> {
    let bytes = s.as_bytes();
    let mut i = 0;
    let mut out = Vec::new();
    while i < bytes.len() {
        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= bytes.len() {
            break;
        }
        if bytes[i] != b'(' {
            return None;
        }
        let start = i + 1;
        let mut depth = 1usize;
        let mut in_str = false;
        i += 1;
        while i < bytes.len() && depth > 0 {
            let b = bytes[i];
            if in_str {
                if b == b'\'' {
                    if bytes.get(i + 1) == Some(&b'\'') {
                        i += 2;
                        continue;
                    }
                    in_str = false;
                }
                i += 1;
                continue;
            }
            if b == b'\'' {
                in_str = true;
            } else if b == b'(' {
                depth += 1;
            } else if b == b')' {
                depth -= 1;
                if depth == 0 {
                    out.push(&s[start..i]);
                    i += 1;
                    break;
                }
            }
            i += 1;
        }
        if depth != 0 {
            return None;
        }
        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        if i < bytes.len() {
            if bytes[i] == b',' {
                i += 1;
            } else {
                return None;
            }
        }
    }
    Some(out)
}

fn split_csv(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut in_str = false;
    let mut depth = 0usize;
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if in_str {
            cur.push(c);
            if c == '\'' {
                if chars.peek() == Some(&'\'') {
                    cur.push(chars.next().expect("peeked"));
                } else {
                    in_str = false;
                }
            }
        } else if c == '\'' {
            in_str = true;
            cur.push(c);
        } else if c == '(' {
            depth += 1;
            cur.push(c);
        } else if c == ')' {
            depth = depth.saturating_sub(1);
            cur.push(c);
        } else if c == ',' && depth == 0 {
            out.push(cur.trim().to_string());
            cur.clear();
        } else {
            cur.push(c);
        }
    }
    if !cur.trim().is_empty() {
        out.push(cur.trim().to_string());
    }
    out
}

/// Strips trailing Postgres `::type` casts outside single-quoted strings.
fn strip_pg_cast(raw: &str) -> &str {
    let bytes = raw.as_bytes();
    let mut in_str = false;
    let mut depth = 0usize;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if in_str {
            if b == b'\'' {
                if bytes.get(i + 1) == Some(&b'\'') {
                    i += 2;
                    continue;
                }
                in_str = false;
            }
            i += 1;
            continue;
        }
        if b == b'\'' {
            in_str = true;
        } else if b == b'(' {
            depth += 1;
        } else if b == b')' {
            depth = depth.saturating_sub(1);
        } else if depth == 0 && b == b':' && bytes.get(i + 1) == Some(&b':') {
            return raw[..i].trim();
        }
        i += 1;
    }
    raw.trim()
}

fn parse_dump_val(raw: &str, line: usize) -> Result<DumpVal, String> {
    let mut t = strip_pg_cast(raw);
    while t.starts_with('(') && t.ends_with(')') && t.len() >= 2 {
        let inner = t[1..t.len() - 1].trim();
        t = strip_pg_cast(inner);
    }
    if t.eq_ignore_ascii_case("null") {
        Ok(DumpVal::Null)
    } else if t.eq_ignore_ascii_case("true") {
        Ok(DumpVal::Bool(true))
    } else if t.eq_ignore_ascii_case("false") {
        Ok(DumpVal::Bool(false))
    } else if t.starts_with('\'') && t.ends_with('\'') && t.len() >= 2 {
        let inner = &t[1..t.len() - 1];
        let mut chars = inner.chars().peekable();
        let mut out = String::new();
        while let Some(c) = chars.next() {
            if c == '\'' {
                if chars.peek() == Some(&'\'') {
                    chars.next();
                    out.push('\'');
                } else {
                    return Err(format!("line {line}: malformed string literal `{t}`"));
                }
            } else {
                out.push(c);
            }
        }
        Ok(DumpVal::Str(out))
    } else if (t.starts_with("x'") || t.starts_with("X'")) && t.ends_with('\'') && t.len() >= 3 {
        // B66: SQLite hex BLOB literal (`x'00112233'` / `X'...'`) emitted by `sqlite3 .dump`.
        let hex = &t[2..t.len() - 1];
        if hex.len().is_multiple_of(2) && hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            Ok(DumpVal::Str(format!("x'{}'", hex.to_ascii_lowercase())))
        } else {
            Err(format!(
                "line {line}: invalid hex BLOB literal `{t}` in SQL dump"
            ))
        }
    } else if let Ok(n) = t.parse::<i64>() {
        Ok(DumpVal::Int(n))
    } else {
        Err(format!("line {line}: unsupported value `{t}` in SQL dump"))
    }
}

fn clean_sql_ident(raw: &str) -> String {
    let t = raw.trim();
    let part = t.rsplit('.').next().unwrap_or(t).trim();
    part.trim_matches('"')
        .trim_matches('`')
        .trim_matches('\'')
        .to_ascii_lowercase()
}

fn default_to_dump_val(d: &elinvar_als::SqlDefault) -> DumpVal {
    match d {
        elinvar_als::SqlDefault::Int(n) => DumpVal::Int(*n),
        elinvar_als::SqlDefault::Str(s) => DumpVal::Str(s.clone()),
        elinvar_als::SqlDefault::Bool(b) => DumpVal::Bool(*b),
        elinvar_als::SqlDefault::Null | _ => DumpVal::Null,
    }
}

type TableRow = (usize, BTreeMap<String, DumpVal>);
/// A dump's rows, by lowercased table name.
type RowsByTable = BTreeMap<String, Vec<TableRow>>;

/// Statements a dump carries beside its rows, which hold no data: they are
/// passed over without a warning.
const DUMP_BOILERPLATE: &[&str] = &[
    "ALTER",
    "ANALYZE",
    "BEGIN",
    "COMMENT",
    "COMMIT",
    "CREATE",
    "DROP",
    "END",
    "GRANT",
    "LOCK",
    "PRAGMA",
    "RELEASE",
    "REVOKE",
    "ROLLBACK",
    "SAVEPOINT",
    "SELECT",
    "SET",
    "START",
    "UNLOCK",
    "USE",
    "VACUUM",
];

/// A warning from the `CLI_CODES` table, at a line of the dump.
fn dump_warning(code: &'static str, message: String, file: &str, line: usize) -> Error {
    let fix = crate::cli::verbs::CLI_CODES
        .iter()
        .find(|c| c.code == code)
        .map_or("", |c| c.fix);
    Error::with_fix(code, message, fix).at(Place::new(
        file,
        u32::try_from(line).unwrap_or(u32::MAX),
        1,
    ))
}

/// The rows of a dump by table, and a warning for each statement or row it
/// did not read (AGENTS.md law 20).
fn parse_dump_rows(
    data_file: &str,
    data_sql: &str,
    imp: &elinvar_als::SqlImport,
) -> Result<(RowsByTable, Vec<Error>), String> {
    let mut cols_by_table: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (tname, cols) in &imp.table_columns {
        cols_by_table.insert(
            tname.to_ascii_lowercase(),
            cols.iter()
                .map(|c| c.sql_name.to_ascii_lowercase())
                .collect(),
        );
    }

    let mut rows_by_table: BTreeMap<String, Vec<TableRow>> = BTreeMap::new();
    for t in cols_by_table.keys() {
        rows_by_table.insert(t.clone(), Vec::new());
    }

    let mut warnings = Vec::new();
    let mut inserts = 0usize;
    // Rows of tables the audited schema lacks: count and first line.
    let mut dropped: BTreeMap<String, (usize, usize)> = BTreeMap::new();
    for stmt in split_dump_statements(data_sql) {
        let up = stmt.sql.to_ascii_uppercase();
        if !up.starts_with("INSERT") {
            let word: String = up
                .trim_start()
                .chars()
                .take_while(char::is_ascii_alphabetic)
                .collect();
            if !DUMP_BOILERPLATE.contains(&word.as_str()) {
                let shown: String = stmt.sql.trim().chars().take(60).collect();
                let message = if word == "COPY" {
                    format!(
                        "a `COPY` statement was not read, and its rows were not audited; \
                         dump with `pg_dump --inserts`: `{shown}`"
                    )
                } else {
                    format!("a statement that is not an INSERT was not read: `{shown}`")
                };
                warnings.push(dump_warning(
                    "audit.ignored_statement",
                    message,
                    data_file,
                    stmt.line,
                ));
            }
            continue;
        }
        inserts += 1;
        let after_into = split_once_kw_top(&stmt.sql, "INTO")
            .map(|(_, r)| r.trim())
            .ok_or_else(|| format!("line {}: malformed INSERT statement", stmt.line))?;
        let Some((before_vals, vals_part)) = split_once_kw_top(after_into, "VALUES") else {
            return Err(format!(
                "line {}: INSERT is missing VALUES clause",
                stmt.line
            ));
        };
        let (tname, explicit_cols) = if let Some((tn, rest)) = before_vals.split_once('(') {
            let clist: Vec<String> = rest
                .trim()
                .trim_end_matches(')')
                .split(',')
                .map(clean_sql_ident)
                .filter(|c| !c.is_empty())
                .collect();
            (clean_sql_ident(tn), Some(clist))
        } else {
            (clean_sql_ident(before_vals), None)
        };
        let Some(schema_cols) = cols_by_table.get(&tname) else {
            // Table is outside `--tables` slice or not part of the schema:
            // its rows are not audited, and a warning says how many.
            let rows = split_value_tuples(vals_part).map_or(1, |t| t.len());
            let e = dropped.entry(tname).or_insert((0, stmt.line));
            e.0 += rows;
            continue;
        };
        let target_cols: &[String] = match explicit_cols.as_deref() {
            Some(c) => c,
            None => schema_cols.as_slice(),
        };
        // Strip optional Postgres `ON CONFLICT ...` suffix after the VALUES tuples.
        let vals_clean = split_once_kw_top(vals_part, "ON")
            .map_or(vals_part.trim(), |(before, _)| before.trim());
        let tuples = split_value_tuples(vals_clean)
            .ok_or_else(|| format!("line {}: malformed VALUES list in INSERT", stmt.line))?;
        for tup in tuples {
            let raw_vals = split_csv(tup);
            if raw_vals.len() != target_cols.len() {
                return Err(format!(
                    "line {}: INSERT into `{tname}` has {} column(s) but {} value(s)",
                    stmt.line,
                    target_cols.len(),
                    raw_vals.len()
                ));
            }
            let mut row = BTreeMap::new();
            for (c, rv) in target_cols.iter().zip(raw_vals.iter()) {
                row.insert(c.clone(), parse_dump_val(rv, stmt.line)?);
            }
            // Apply schema DEFAULT literals for omitted columns.
            for ((dt, dc), def) in &imp.col_defaults {
                if dt == &tname && !row.contains_key(dc) {
                    row.insert(dc.clone(), default_to_dump_val(def));
                }
            }
            rows_by_table
                .entry(tname.clone())
                .or_default()
                .push((stmt.line, row));
        }
    }
    for (table, (rows, line)) in dropped {
        warnings.push(dump_warning(
            "audit.dropped_rows",
            format!(
                "{rows} row(s) inserted into `{table}` were not audited: the table is not in \
                 the schema, or not in its `--tables` slice"
            ),
            data_file,
            line,
        ));
    }
    if inserts == 0 {
        // Nothing read and something passed over: not a dump at all.
        if let Some(first) = warnings.first() {
            return Err(format!(
                "`{data_file}` has no INSERT statement, so it is not a SQL dump (line {}: {})",
                first.place.as_ref().map_or(1, |p| p.line),
                first.message
            ));
        }
        warnings.push(dump_warning(
            "audit.no_rows",
            "the dump has no INSERT statement, so no row was audited".to_string(),
            data_file,
            1,
        ));
    }
    Ok((rows_by_table, warnings))
}

/// Runs O(N) direct structural checks (`NOT NULL`, `PK`, `UNIQUE`, partial
/// unique indexes, `FOREIGN KEY`, and closed enums) over the parsed rows.
fn check_structural_rules(
    imp: &elinvar_als::SqlImport,
    rows_by_table: &BTreeMap<String, Vec<TableRow>>,
) -> Vec<RuleViolation> {
    let mut out = Vec::new();

    // 1. NOT NULL, PK uniqueness, single-column UNIQUE, and closed enums.
    for (tname, cols) in &imp.table_columns {
        let t_low = tname.to_ascii_lowercase();
        let Some(rows) = rows_by_table.get(&t_low) else {
            continue;
        };
        let pk_cols: Vec<String> = cols
            .iter()
            .filter(|c| c.primary_key)
            .map(|c| c.sql_name.to_ascii_lowercase())
            .collect();
        let mut seen_pk: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
        let mut seen_unique: BTreeMap<String, BTreeSet<DumpVal>> = BTreeMap::new();

        for (line, row) in rows {
            for col in cols {
                let c_low = col.sql_name.to_ascii_lowercase();
                let val = row.get(&c_low).unwrap_or(&DumpVal::Null);
                if col.not_null && matches!(val, DumpVal::Null) {
                    out.push(RuleViolation {
                        rule: format!("NOT NULL {t_low}.{c_low}"),
                        table: Some(tname.clone()),
                        detail: format!("row at line {line} has NULL in NOT NULL column `{c_low}`"),
                        line: Some(*line),
                    });
                }
                if col.unique && !matches!(val, DumpVal::Null) {
                    let set = seen_unique.entry(c_low.clone()).or_default();
                    if !set.insert(val.clone()) {
                        out.push(RuleViolation {
                            rule: format!("UNIQUE {t_low}.{c_low}"),
                            table: Some(tname.clone()),
                            detail: format!(
                                "duplicate value {} in UNIQUE column `{t_low}.{c_low}` at line {line}",
                                val.display()
                            ),
                            line: Some(*line),
                        });
                    }
                }
                if !matches!(val, DumpVal::Null)
                    && let Some(allowed) = imp.enum_values.get(&(t_low.clone(), c_low.clone()))
                {
                    let s = match val {
                        DumpVal::Str(v) => v.clone(),
                        DumpVal::Int(n) => n.to_string(),
                        DumpVal::Bool(b) => b.to_string(),
                        DumpVal::Null => unreachable!(),
                    };
                    if !allowed.iter().any(|a| a == &s) {
                        out.push(RuleViolation {
                            rule: format!("CHECK enum {t_low}.{c_low}"),
                            table: Some(tname.clone()),
                            detail: format!(
                                "value '{}' at line {line} is outside allowed enum values [{}]",
                                s,
                                allowed.join(", ")
                            ),
                            line: Some(*line),
                        });
                    }
                }
            }
            if !pk_cols.is_empty() {
                let key: Vec<DumpVal> = pk_cols
                    .iter()
                    .map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
                    .collect();
                if !seen_pk.insert(key) {
                    out.push(RuleViolation {
                        rule: format!("PRIMARY KEY {t_low}({})", pk_cols.join(", ")),
                        table: Some(tname.clone()),
                        detail: format!("duplicate primary key at line {line}"),
                        line: Some(*line),
                    });
                }
            }
        }
    }

    // 2. Partial unique indexes (`WHERE null_col IS NULL`), multi-column `UNIQUE`,
    //    and unfiltered `CREATE UNIQUE INDEX` constraints (W30).
    for (tname, ulist) in &imp.table_uniques {
        let t_low = tname.to_ascii_lowercase();
        let Some(rows) = rows_by_table.get(&t_low) else {
            continue;
        };
        for ucols in ulist {
            let key_cols: Vec<String> = ucols.iter().map(|c| c.to_ascii_lowercase()).collect();
            let mut seen: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
            for (line, row) in rows {
                let key: Vec<DumpVal> = key_cols
                    .iter()
                    .map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
                    .collect();
                if key.iter().any(|v| matches!(v, DumpVal::Null)) {
                    continue;
                }
                if !seen.insert(key) {
                    out.push(RuleViolation {
                        rule: format!("UNIQUE {t_low}({})", ucols.join(", ")),
                        table: Some(tname.clone()),
                        detail: format!(
                            "duplicate key ({}) in UNIQUE constraint on `{t_low}` at line {line}",
                            ucols.join(", ")
                        ),
                        line: Some(*line),
                    });
                }
            }
        }
    }
    for (tname, idx_name, ucols) in &imp.unique_indexes {
        let t_low = tname.to_ascii_lowercase();
        let Some(rows) = rows_by_table.get(&t_low) else {
            continue;
        };
        let key_cols: Vec<String> = ucols.iter().map(|c| c.to_ascii_lowercase()).collect();
        let mut seen: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
        for (line, row) in rows {
            let key: Vec<DumpVal> = key_cols
                .iter()
                .map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
                .collect();
            if key.iter().any(|v| matches!(v, DumpVal::Null)) {
                continue;
            }
            if !seen.insert(key) {
                out.push(RuleViolation {
                    rule: format!("UNIQUE INDEX {idx_name}"),
                    table: Some(tname.clone()),
                    detail: format!(
                        "duplicate key ({}) in UNIQUE INDEX `{idx_name}` at line {line}",
                        ucols.join(", ")
                    ),
                    line: Some(*line),
                });
            }
        }
    }
    for idx in &imp.partial_unique_indexes {
        let t_low = idx.table.to_ascii_lowercase();
        let Some(rows) = rows_by_table.get(&t_low) else {
            continue;
        };
        let null_col = idx.null_col.to_ascii_lowercase();
        let key_cols: Vec<String> = idx.cols.iter().map(|c| c.to_ascii_lowercase()).collect();
        let mut seen: BTreeSet<Vec<DumpVal>> = BTreeSet::new();
        for (line, row) in rows {
            if !matches!(row.get(&null_col), None | Some(DumpVal::Null)) {
                continue;
            }
            let key: Vec<DumpVal> = key_cols
                .iter()
                .map(|c| row.get(c).cloned().unwrap_or(DumpVal::Null))
                .collect();
            if key.iter().any(|v| matches!(v, DumpVal::Null)) {
                continue;
            }
            if !seen.insert(key) {
                out.push(RuleViolation {
                    rule: format!("UNIQUE INDEX {}", idx.name),
                    table: Some(idx.table.clone()),
                    detail: format!(
                        "duplicate open key ({}) with `{null_col}` IS NULL at line {line}",
                        idx.cols.join(", ")
                    ),
                    line: Some(*line),
                });
            }
        }
    }

    // 3. Foreign keys (`imp.fk_targets`).
    let mut target_index: BTreeMap<(String, String), BTreeSet<DumpVal>> = BTreeMap::new();
    for fk in imp.fk_targets.values() {
        let key = (fk.target_table.clone(), fk.target_col.clone());
        target_index.entry(key).or_insert_with(|| {
            let mut vals = BTreeSet::new();
            if let Some(trows) = rows_by_table.get(&fk.target_table) {
                for (_, r) in trows {
                    if let Some(v) = r.get(&fk.target_col)
                        && !matches!(v, DumpVal::Null)
                    {
                        vals.insert(v.clone());
                    }
                }
            }
            vals
        });
    }
    for ((src_t, src_c), fk) in &imp.fk_targets {
        let Some(rows) = rows_by_table.get(src_t) else {
            continue;
        };
        let valid_targets = target_index
            .get(&(fk.target_table.clone(), fk.target_col.clone()))
            .expect("populated above");
        for (line, row) in rows {
            if let Some(val) = row.get(src_c)
                && !matches!(val, DumpVal::Null)
                && !valid_targets.contains(val)
            {
                out.push(RuleViolation {
                    rule: format!(
                        "FOREIGN KEY {src_t}.{src_c} -> {}.{}",
                        fk.target_table, fk.target_col
                    ),
                    table: Some(src_t.clone()),
                    detail: format!(
                        "value {} at line {line} does not exist in `{}.{}`",
                        val.display(),
                        fk.target_table,
                        fk.target_col
                    ),
                    line: Some(*line),
                });
            }
        }
    }

    out
}

/// Evaluates all single-state model facts (CHECKs, composite UNIQUEs) and all
/// single-state user promises directly over the dump via `elinvar_engine::logic`
/// without invoking the SAT solver (R7).
#[allow(clippy::type_complexity)]
fn evaluate_dump_on_model(
    model: &elinvar_als::AlsModel,
    imp: &elinvar_als::SqlImport,
    rows_by_table: &BTreeMap<String, Vec<TableRow>>,
) -> Result<
    (
        Vec<RuleViolation>,
        Vec<(String, bool)>,
        Vec<(String, String)>,
    ),
    Vec<elinvar_engine::logic::Error>,
> {
    // W30: pre-select the single-state facts and promises that still need Alloy
    // evaluation (skipping O(N^2)/O(N^3) structural facts already verified in
    // O(N) by `check_structural_rules`, plus trivially true domain/retired facts
    // and CHECK facts on empty tables).
    let mut structural_facts_done: BTreeSet<String> = BTreeSet::new();
    structural_facts_done.insert("fact SqlOrdFn_monotone".to_string());
    for t in &imp.tables {
        let tid = imp
            .sql_to_alloy_table
            .get(t)
            .map(String::as_str)
            .unwrap_or(t.as_str());
        structural_facts_done.insert(format!("fact {tid}_domain"));
        structural_facts_done.insert(format!("fact {tid}_retired_disjoint"));
        let row_count = rows_by_table
            .get(&t.to_ascii_lowercase())
            .map_or(0, Vec::len);
        if row_count == 0 {
            structural_facts_done.insert(format!("fact {tid}_checks"));
        }
        if let Some(cols) = imp.table_columns.get(t) {
            for c in cols {
                if c.unique {
                    structural_facts_done.insert(format!("fact {tid}_unique_{}", c.alloy_name));
                }
            }
        }
        if let Some(ulist) = imp.table_uniques.get(t) {
            for idx in 0..ulist.len() {
                structural_facts_done.insert(format!("fact {tid}_unique_{}", idx + 1));
            }
        }
    }
    for (tname, idx_name, _) in &imp.unique_indexes {
        let tid = imp
            .sql_to_alloy_table
            .get(tname)
            .map(String::as_str)
            .unwrap_or(tname.as_str());
        structural_facts_done.insert(format!("fact {tid}_uniq_{idx_name}"));
    }
    for idx in &imp.partial_unique_indexes {
        let tid = imp
            .sql_to_alloy_table
            .get(&idx.table)
            .map(String::as_str)
            .unwrap_or(idx.table.as_str());
        structural_facts_done.insert(format!("fact {tid}_uniq_{}", idx.name));
        structural_facts_done.insert(format!("fact {}", idx.name));
    }

    let mut active_facts: Vec<(String, elinvar_engine::logic::Formula)> = Vec::new();
    for (fname, formula) in model.model.all_facts_named() {
        if fname == "fact trace"
            || fname == "fact StartEmpty"
            || fname.ends_with("_no_row_reuse")
            || fname.starts_with("sig ")
            || fname.starts_with("field ")
            || structural_facts_done.contains(&fname)
            || crate::cli::dates::is_synthetic_date_fn_rule(&fname)
        {
            continue;
        }
        let inner = match formula.kind() {
            FormulaKind::Temporal(TemporalOp::Always, sub) => sub.clone(),
            _ => formula,
        };
        if inner.is_temporal() {
            continue;
        }
        active_facts.push((fname, inner));
    }

    let mut active_promises: Vec<(String, elinvar_engine::logic::Formula)> = Vec::new();
    let mut skipped_promises = Vec::new();
    for spec in &model.commands {
        if !spec.check {
            continue;
        }
        let cmd = model.command(spec);
        let f = cmd.formula();
        let inner = match f.kind() {
            FormulaKind::Temporal(TemporalOp::Always, sub) => sub.clone(),
            _ => f.clone(),
        };
        if inner.is_temporal() {
            skipped_promises.push((
                spec.name.clone(),
                "requires multiple states (uses temporal step operators)".to_string(),
            ));
            continue;
        }
        active_promises.push((spec.name.clone(), inner));
    }

    if active_facts.is_empty() && active_promises.is_empty() {
        return Ok((Vec::new(), Vec::new(), skipped_promises));
    }

    let need_date_fn = active_facts
        .iter()
        .chain(active_promises.iter())
        .any(|(_, f)| f.to_string().contains("SqlDateFn"));
    let need_ord_fn = active_facts
        .iter()
        .chain(active_promises.iter())
        .any(|(_, f)| f.to_string().contains("SqlOrdFn"));

    // Use a tiny scope-2 bounds build (<1ms regardless of dump size!) purely
    // to inspect each relation's schema metadata (at scope 2, `one sig` and
    // `enum` members have `upper.len() == 1`, while normal sigs have `>= 2`).
    let schema_bounds = model
        .model
        .run(&elinvar_engine::logic::Formula::truth())
        .scope(2)
        .bounds()?;
    let su = schema_bounds.universe();
    let relations = model.model.relations();

    // Map atom -> parent sig name from scope-2 schema bounds.
    let mut atom_sig_name: BTreeMap<String, String> = BTreeMap::new();
    let mut singleton_rel_names: BTreeSet<String> = BTreeSet::new();
    let mut ordered_aliases: BTreeMap<String, String> = BTreeMap::new(); // sig_name -> alias
    let mut sig_children: BTreeMap<String, Vec<String>> = BTreeMap::new(); // parent_sig -> [child_singleton_sig]

    let is_parent_container = |rname: &str| {
        rname == "SqlBool"
            || rname.ends_with("_enum")
            || rname.ends_with("_val")
            || rname.ends_with("_row")
            || rname.ends_with("_ord")
            || rname.starts_with("time_ord_")
            || rname.starts_with("date_ord_")
    };

    // Pass 1: record every atom belonging to a parent container sig (`SqlBool`, `*_enum`, `*_val`, `*_row`, `*_ord`).
    let mut container_atoms: Vec<(String, BTreeSet<String>)> = Vec::new();
    for rel in &relations {
        if rel.is_changing() || rel.arity() != 1 {
            continue;
        }
        let rname = rel.name();
        if rname == "Int" || rname == "first" || rname.ends_with("/first") {
            continue;
        }
        if is_parent_container(rname)
            && let Some(up) = schema_bounds.upper(rel)
        {
            let mut set = BTreeSet::new();
            for idx in up.indices() {
                if let Some(aname) = su.atom(idx as usize) {
                    atom_sig_name.insert(aname.to_string(), rname.to_string());
                    set.insert(aname.to_string());
                }
            }
            container_atoms.push((rname.to_string(), set));
        }
    }

    // B60: W26 text-check subset signatures (`sig foo_chk_0 in foo_ord`) are
    // populated explicitly below from concrete string predicates; never treat
    // them as `one sig` children of their parent domain or ordered signature.
    let text_check_sig_names: BTreeSet<&str> = imp
        .text_checks
        .iter()
        .map(|tc| tc.sig_name.as_str())
        .collect();

    // Pass 2: every non-container fixed 1-ary relation whose upper bound is a
    // single atom OR sits inside a parent container (enum members & `one sig extends`)
    // is a singleton atom; record its parent container in `sig_children`.
    for rel in &relations {
        if rel.is_changing() || rel.arity() != 1 {
            continue;
        }
        let rname = rel.name();
        if rname == "Int"
            || rname == "first"
            || rname.ends_with("/first")
            || is_parent_container(rname)
            || text_check_sig_names.contains(rname)
        {
            continue;
        }
        let Some(up) = schema_bounds.upper(rel) else {
            continue;
        };
        let up_atoms: Vec<String> = up
            .indices()
            .filter_map(|idx| su.atom(idx as usize).map(str::to_string))
            .collect();
        let parent_match = container_atoms
            .iter()
            .find(|(_, cset)| !up_atoms.is_empty() && up_atoms.iter().all(|a| cset.contains(a)))
            .map(|(pname, _)| pname.clone());
        let is_one = up_atoms.len() == 1
            || schema_bounds.lower(rel).is_some_and(|lo| lo.len() == 1)
            || parent_match.is_some();
        if is_one {
            singleton_rel_names.insert(rname.to_string());
            if let Some(pname) = parent_match {
                sig_children
                    .entry(pname)
                    .or_default()
                    .push(rname.to_string());
            } else {
                for a in &up_atoms {
                    atom_sig_name
                        .entry(a.clone())
                        .or_insert_with(|| rname.to_string());
                }
            }
        } else {
            for a in &up_atoms {
                atom_sig_name
                    .entry(a.clone())
                    .or_insert_with(|| rname.to_string());
            }
        }
    }
    // Identify ordered signatures (`<alias>/first` -> target sig).
    // Note: Alloy `enum`s also have `<enum>/first` and `<enum>/next` (B27),
    // so keep dynamic `*_ord` orderings separate from fixed-member `enum` orderings.
    let mut enum_order_aliases: BTreeMap<String, String> = BTreeMap::new(); // enum_sig -> alias
    for rel in &relations {
        if !rel.is_changing()
            && rel.arity() == 1
            && let Some(alias) = rel.name().strip_suffix("/first")
            && let Some(up) = schema_bounds.upper(rel)
            && let Some(idx) = up.indices().next()
            && let Some(aname) = su.atom(idx as usize)
            && let Some(parent_sig) = atom_sig_name.get(aname)
        {
            if sig_children.contains_key(parent_sig) {
                enum_order_aliases.insert(parent_sig.clone(), alias.to_string());
            } else {
                ordered_aliases.insert(parent_sig.clone(), alias.to_string());
            }
        }
    }

    // Determine each 2-ary field's (owner_alloy_table, sql_col, range_sig).
    let mut sql_to_alloy_table: BTreeMap<String, String> = BTreeMap::new();
    for (a, s) in &imp.alloy_to_sql_table {
        sql_to_alloy_table.insert(s.clone(), a.clone());
    }
    let mut field_range_sig: BTreeMap<String, String> = BTreeMap::new();
    let sn = su.size() as u64;
    for rel in &relations {
        if rel.arity() < 2 || rel.name().ends_with("/next") || rel.name() == "next" {
            continue;
        }
        if let Some(up) = schema_bounds.upper(rel)
            && let Some(flat) = up.indices().next()
            && let Some(ran_atom) = su.atom((flat % sn) as usize)
        {
            let range_sig = if su.int_of((flat % sn) as usize).is_some() {
                "Int".to_string()
            } else {
                atom_sig_name
                    .get(ran_atom)
                    .cloned()
                    .unwrap_or_else(|| "Unknown".to_string())
            };
            field_range_sig.insert(rel.name().to_string(), range_sig);
        }
    }

    // Collect atoms needed for our tight direct Universe (no solver bounds!).
    let mut all_atoms: Vec<String> = Vec::new();
    let mut atom_seen: BTreeSet<String> = BTreeSet::new();
    let mut add_atom = |a: String| {
        if atom_seen.insert(a.clone()) {
            all_atoms.push(a);
        }
    };

    // 1. Row atoms per table: `{alloy_table}_row{i}`.
    let mut table_row_atoms: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut pk_row_lookup: BTreeMap<(String, String, DumpVal), String> = BTreeMap::new();
    for (t_sql, rows) in rows_by_table {
        let t_alloy = sql_to_alloy_table
            .get(t_sql)
            .cloned()
            .unwrap_or_else(|| t_sql.clone());
        let mut ratoms = Vec::with_capacity(rows.len());
        for (i, (_, r)) in rows.iter().enumerate() {
            let ratom = format!("{t_alloy}_row{i}");
            add_atom(ratom.clone());
            for (c, v) in r {
                if !matches!(v, DumpVal::Null) {
                    pk_row_lookup
                        .entry((t_sql.clone(), c.clone(), v.clone()))
                        .or_insert_with(|| ratom.clone());
                }
            }
            ratoms.push(ratom);
        }
        table_row_atoms.insert(t_sql.clone(), ratoms);
    }

    // 2. Singleton atoms (enums, SqlTrue, SqlFalse, named domain literals, SqlDateFn).
    let mut singleton_atoms: BTreeMap<String, String> = BTreeMap::new();
    for srel in &singleton_rel_names {
        let atom = format!("{srel}0");
        add_atom(atom.clone());
        singleton_atoms.insert(srel.clone(), atom);
    }

    // 3. Distinct ordered values & domain values & integers from the dump.
    let mut ordered_vals: BTreeMap<String, BTreeSet<DumpVal>> = BTreeMap::new();
    let mut domain_vals: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    let mut int_vals: BTreeSet<i64> = BTreeSet::from([0]);

    for rel in &relations {
        if !rel.is_changing() || rel.arity() != 2 {
            continue;
        }
        let rname = rel.name();
        let Some(range_sig) = field_range_sig.get(rname) else {
            continue;
        };
        let rname_low = rname.to_ascii_lowercase();
        let (owner_hint, col_alloy) = match rname_low.rsplit_once('.') {
            Some((o, c)) => (Some(o), c),
            None => (None, rname_low.as_str()),
        };
        for (t_sql, rows) in rows_by_table {
            let t_alloy = sql_to_alloy_table
                .get(t_sql)
                .map(String::as_str)
                .unwrap_or(t_sql.as_str());
            if let Some(oh) = owner_hint
                && oh != t_alloy
                && oh != t_sql.as_str()
            {
                continue;
            }
            let col_sql = imp
                .alloy_to_sql_col
                .get(&(t_alloy.to_string(), col_alloy.to_string()))
                .map(String::as_str)
                .unwrap_or(col_alloy);
            for (_, row) in rows {
                let Some(val) = row.get(col_sql) else {
                    continue;
                };
                if matches!(val, DumpVal::Null) {
                    continue;
                }
                if range_sig == "Int" {
                    if let DumpVal::Int(n) = val {
                        int_vals.insert(*n);
                    }
                } else if ordered_aliases.contains_key(range_sig) {
                    ordered_vals
                        .entry(range_sig.clone())
                        .or_default()
                        .insert(val.clone());
                } else if range_sig != "SqlBool"
                    && !imp.int_regions.iter().any(|r| r.sig_name == *range_sig)
                    && !range_sig.ends_with("_row")
                    && !imp
                        .alloy_to_sql_table
                        .contains_key(&range_sig.to_ascii_lowercase())
                {
                    let sval = match val {
                        DumpVal::Str(s) => s.clone(),
                        DumpVal::Int(n) => n.to_string(),
                        DumpVal::Bool(b) => b.to_string(),
                        DumpVal::Null => unreachable!(),
                    };
                    domain_vals
                        .entry(range_sig.clone())
                        .or_default()
                        .insert(sval);
                }
            }
        }
    }

    // B48: when `SqlDateFn` is present, expand the date ordered sig with real
    // calendar conversions (`strftime(..., 'unixepoch')`) and real shifted dates.
    let date_sig_opt =
        crate::cli::dates::detect_date_sig_from_relations(&relations, &field_range_sig);
    let date_fmt = imp.date_format.as_deref().unwrap_or("%Y-%m");
    if let Some(date_sig) = &date_sig_opt {
        let mut src_unix_vals: Vec<i64> = Vec::new();
        let mut ord_shift_vals: BTreeMap<String, Vec<i64>> = BTreeMap::new();
        for rel in &relations {
            let short = rel.name().rsplit('.').next().unwrap_or(rel.name());
            if let Some(src_sig) = short.strip_prefix("to_date_") {
                if src_sig == "Int" {
                    src_unix_vals.extend(int_vals.iter().copied());
                } else if let Some(vs) = ordered_vals.get(src_sig) {
                    for v in vs {
                        if let DumpVal::Int(n) = v {
                            src_unix_vals.push(*n);
                        }
                    }
                }
            } else if let Some(ord_sig) = short.strip_prefix("add_")
                && rel.arity() == 4
                && ord_sig != "Int"
                && let Some(vs) = ordered_vals.get(ord_sig)
            {
                let nums: Vec<i64> = vs
                    .iter()
                    .filter_map(|v| match v {
                        DumpVal::Int(n) => Some(*n),
                        _ => None,
                    })
                    .collect();
                ord_shift_vals.insert(ord_sig.to_string(), nums);
            }
        }
        let mut base_dates: BTreeSet<String> = ordered_vals
            .get(date_sig)
            .map(|vs| {
                vs.iter()
                    .filter_map(|v| match v {
                        DumpVal::Str(s) => Some(s.clone()),
                        _ => None,
                    })
                    .collect()
            })
            .unwrap_or_default();
        crate::cli::dates::expand_date_domain(
            date_fmt,
            &imp.date_shifts,
            &src_unix_vals,
            &int_vals,
            &ord_shift_vals,
            &mut base_dates,
        );
        let entry = ordered_vals.entry(date_sig.clone()).or_default();
        for d in base_dates {
            entry.insert(DumpVal::Str(d));
        }
    }

    // B61: expand ordered integer domains with `v + delta` for every `SqlOrdFn` shift.
    for sh in &imp.ord_shifts {
        let base_ints: Vec<i64> = ordered_vals
            .get(&sh.ordered_sig)
            .map(|vals| {
                vals.iter()
                    .filter_map(|v| match v {
                        DumpVal::Int(n) => Some(*n),
                        _ => None,
                    })
                    .collect()
            })
            .unwrap_or_default();
        let entry = ordered_vals.entry(sh.ordered_sig.clone()).or_default();
        for n in base_ints {
            entry.insert(DumpVal::Int(n.saturating_add(sh.delta)));
        }
    }

    // Ensure every ordered signature has at least 1 atom so `<alias>/first` is
    // non-empty even when the table using it has 0 rows in the dump.
    for osig in ordered_aliases.keys() {
        ordered_vals
            .entry(osig.clone())
            .or_default()
            .insert(DumpVal::Int(0));
    }

    // Allocate ordered atoms in natural sorted order (`DumpVal` derives Ord so Ints sort numerically and Strs sort lexicographically!).
    let mut ordered_atom_map: BTreeMap<(String, DumpVal), String> = BTreeMap::new();
    let mut ordered_chain: BTreeMap<String, Vec<String>> = BTreeMap::new();
    let mut ordered_int_pairs: BTreeMap<String, Vec<(String, i64)>> = BTreeMap::new();
    let mut ordered_str_values: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (osig, vals) in &ordered_vals {
        let mut chain = Vec::with_capacity(vals.len());
        let mut ipairs = Vec::new();
        let mut svals = Vec::new();
        for (i, v) in vals.iter().enumerate() {
            let atom = format!("{osig}_v{i}");
            add_atom(atom.clone());
            ordered_atom_map.insert((osig.clone(), v.clone()), atom.clone());
            match v {
                DumpVal::Int(n) => ipairs.push((atom.clone(), *n)),
                DumpVal::Str(s) => svals.push(s.clone()),
                _ => {}
            }
            chain.push(atom);
        }
        if !ipairs.is_empty() {
            ordered_int_pairs.insert(osig.clone(), ipairs);
        }
        if !svals.is_empty() {
            ordered_str_values.insert(osig.clone(), svals);
        }
        ordered_chain.insert(osig.clone(), chain);
    }

    // Allocate domain atoms, preferring existing singleton literal sub-sigs when names match.
    let mut domain_atom_map: BTreeMap<(String, String), String> = BTreeMap::new();
    let mut domain_extra_atoms: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (dsig, vals) in &domain_vals {
        let children = sig_children.get(dsig).cloned().unwrap_or_default();
        let mut extra = Vec::new();
        for (i, v) in vals.iter().enumerate() {
            let v_low = v.to_ascii_lowercase();
            let matched_child = children.iter().find(|ch| {
                let ch_low = ch.to_ascii_lowercase();
                ch_low == v_low || ch_low.ends_with(&format!("_{v_low}"))
            });
            if let Some(ch) = matched_child
                && let Some(satom) = singleton_atoms.get(ch)
            {
                domain_atom_map.insert((dsig.clone(), v.clone()), satom.clone());
            } else {
                let atom = format!("{dsig}_d{i}");
                add_atom(atom.clone());
                domain_atom_map.insert((dsig.clone(), v.clone()), atom.clone());
                extra.push(atom);
            }
        }
        domain_extra_atoms.insert(dsig.clone(), extra);
    }

    // Allocate sparse 32-bit Int atoms if the model uses Int.
    let has_int_rel = relations.iter().any(|r| r.name() == "Int");
    let mut int_atom_pairs: Vec<(String, i64)> = Vec::new();
    if has_int_rel {
        for &n in &int_vals {
            if (i32::MIN as i64..=i32::MAX as i64).contains(&n) {
                let name = n.to_string();
                add_atom(name.clone());
                int_atom_pairs.push((name, n));
            }
        }
    }

    if all_atoms.is_empty() {
        all_atoms.push("_empty".to_string());
    }

    let base_u = Universe::new(all_atoms.iter().map(String::as_str)).map_err(|e| vec![e])?;
    let u = if has_int_rel && !int_atom_pairs.is_empty() {
        let refs: Vec<(&str, i64)> = int_atom_pairs
            .iter()
            .map(|(s, n)| (s.as_str(), *n))
            .collect();
        base_u.with_ints(32, &refs).map_err(|e| vec![e])?
    } else {
        base_u
    };

    // Populate fixed relations (`T_row`, singletons, enums, domains, orderings, Int).
    let mut fixed = Instance::new(&u);
    let mut table_row_sig_to_sql: BTreeMap<String, String> = BTreeMap::new();
    for (t_alloy, t_sql) in &imp.alloy_to_sql_table {
        table_row_sig_to_sql.insert(format!("{t_alloy}_row"), t_sql.clone());
    }

    let text_check_sig_names: BTreeSet<&str> = imp
        .text_checks
        .iter()
        .map(|tc| tc.sig_name.as_str())
        .collect();
    for rel in &relations {
        if rel.is_changing() {
            continue;
        }
        let rname = rel.name();
        if rel.arity() == 1 && text_check_sig_names.contains(rname) {
            continue;
        }
        if rel.arity() == 1 {
            let atoms: Vec<String> = if rname == "Int" {
                int_atom_pairs.iter().map(|(s, _)| s.clone()).collect()
            } else if let Some(t_sql) = table_row_sig_to_sql.get(&rname.to_ascii_lowercase()) {
                table_row_atoms.get(t_sql).cloned().unwrap_or_default()
            } else if let Some(satom) = singleton_atoms.get(rname) {
                vec![satom.clone()]
            } else if let Some(chain) = ordered_chain.get(rname) {
                chain.clone()
            } else if let Some(alias) = rname.strip_suffix("/first") {
                if let Some((osig, _)) = ordered_aliases.iter().find(|(_, a)| a.as_str() == alias) {
                    ordered_chain
                        .get(osig)
                        .and_then(|c| c.first())
                        .cloned()
                        .into_iter()
                        .collect()
                } else if let Some((esig, _)) =
                    enum_order_aliases.iter().find(|(_, a)| a.as_str() == alias)
                {
                    sig_children
                        .get(esig)
                        .and_then(|chs| chs.first())
                        .and_then(|ch| singleton_atoms.get(ch))
                        .cloned()
                        .into_iter()
                        .collect()
                } else {
                    Vec::new()
                }
            } else {
                // Parent enum or domain sig: union of its singleton children + extra domain atoms.
                let mut combined = Vec::new();
                if let Some(chs) = sig_children.get(rname) {
                    for ch in chs {
                        if let Some(a) = singleton_atoms.get(ch) {
                            combined.push(a.clone());
                        }
                    }
                }
                if let Some(ex) = domain_extra_atoms.get(rname) {
                    combined.extend(ex.iter().cloned());
                }
                combined
            };
            let slices: Vec<[&str; 1]> = atoms.iter().map(|a| [a.as_str()]).collect();
            let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
            let ts = u.tuple_set(1, &refs).map_err(|e| vec![e])?;
            fixed.set(rel, ts).map_err(|e| vec![e])?;
        } else if rel.arity() == 2 {
            let pairs: Vec<(String, String)> = if let Some(alias) = rname.strip_suffix("/next") {
                if let Some((osig, _)) = ordered_aliases.iter().find(|(_, a)| a.as_str() == alias) {
                    ordered_chain
                        .get(osig)
                        .map(|chain| {
                            chain
                                .windows(2)
                                .map(|w| (w[0].clone(), w[1].clone()))
                                .collect()
                        })
                        .unwrap_or_default()
                } else if let Some((esig, _)) =
                    enum_order_aliases.iter().find(|(_, a)| a.as_str() == alias)
                {
                    sig_children
                        .get(esig)
                        .map(|chs| {
                            chs.windows(2)
                                .filter_map(|w| {
                                    Some((
                                        singleton_atoms.get(&w[0])?.clone(),
                                        singleton_atoms.get(&w[1])?.clone(),
                                    ))
                                })
                                .collect()
                        })
                        .unwrap_or_default()
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            };
            let slices: Vec<[&str; 2]> = pairs
                .iter()
                .map(|(a, b)| [a.as_str(), b.as_str()])
                .collect();
            let refs: Vec<&[&str]> = slices.iter().map(|p| p.as_slice()).collect();
            let ts = u.tuple_set(2, &refs).map_err(|e| vec![e])?;
            fixed.set(rel, ts).map_err(|e| vec![e])?;
        } else {
            let short = rname.rsplit('.').next().unwrap_or(rname);
            let is_date_fn_rel = need_date_fn
                && date_sig_opt.is_some()
                && singleton_atoms.contains_key("SqlDateFn")
                && (rel.arity() == 3 || rel.arity() == 4)
                && (short.starts_with("to_date_") || short.starts_with("add_"));
            let is_ord_fn_rel = need_ord_fn
                && singleton_atoms.contains_key("SqlOrdFn")
                && rel.arity() == 3
                && imp.ord_shifts.iter().any(|s| s.field == short);
            if !is_date_fn_rel && !is_ord_fn_rel {
                let ts = u.tuple_set(rel.arity(), &[]).map_err(|e| vec![e])?;
                fixed.set(rel, ts).map_err(|e| vec![e])?;
            }
        }
    }

    // B48: populate `SqlDateFn` relations with exact real Gregorian calendar maps
    // only when an active single-state fact or promise actually references it (W30).
    if need_date_fn
        && let Some(date_sig) = &date_sig_opt
        && let Some(fn_atom) = singleton_atoms.get("SqlDateFn")
    {
        let date_strings = ordered_str_values
            .get(date_sig)
            .map(Vec::as_slice)
            .unwrap_or(&[]);
        let date_atoms = ordered_chain
            .get(date_sig)
            .map(Vec::as_slice)
            .unwrap_or(&[]);
        crate::cli::dates::populate_sql_date_fn(
            &mut fixed,
            &u,
            &relations,
            fn_atom,
            date_fmt,
            &imp.date_shifts,
            date_strings,
            date_atoms,
            &ordered_int_pairs,
            &int_atom_pairs,
        )
        .map_err(|e| vec![e])?;
    }

    // B61: populate `SqlOrdFn` constant-offset shifts with exact 64-bit arithmetic
    // only when an active single-state fact or promise actually references it (W30).
    if need_ord_fn
        && !imp.ord_shifts.is_empty()
        && let Some(fn_atom) = singleton_atoms.get("SqlOrdFn")
    {
        crate::cli::dates::populate_sql_ord_fn(
            &mut fixed,
            &u,
            &relations,
            fn_atom,
            &imp.ord_shifts,
            &ordered_int_pairs,
        )
        .map_err(|e| vec![e])?;
    }

    // W26: populate text-check subset signatures (`GLOB`, `length`, `lower`,
    // `upper`, `trim`) with the exact concrete string atoms that satisfy them.
    for tc in &imp.text_checks {
        let Some(rel) = relations.iter().find(|r| r.name() == tc.sig_name) else {
            continue;
        };
        let mut matched: Vec<String> = Vec::new();
        for ((dsig, raw), atom) in &domain_atom_map {
            if dsig == &tc.domain_sig && elinvar_als::eval_sql_text_check(raw, &tc.kind) {
                matched.push(atom.clone());
            }
        }
        if let (Some(strs), Some(atoms)) = (
            ordered_str_values.get(&tc.domain_sig),
            ordered_chain.get(&tc.domain_sig),
        ) {
            for (raw, atom) in strs.iter().zip(atoms.iter()) {
                if elinvar_als::eval_sql_text_check(raw, &tc.kind) {
                    matched.push(atom.clone());
                }
            }
        }
        for lsig in &tc.literal_sigs {
            if let Some(atom) = singleton_atoms.get(lsig) {
                matched.push(atom.clone());
            }
        }
        matched.sort();
        matched.dedup();
        let slices: Vec<[&str; 1]> = matched.iter().map(|a| [a.as_str()]).collect();
        let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
        let ts = u.tuple_set(1, &refs).map_err(|e| vec![e])?;
        fixed.set(rel, ts).map_err(|e| vec![e])?;
    }

    // Populate state 0 (changing table sets `T`, empty `T_retired`, and all 2-ary fields).
    let mut state0 = Instance::new(&u);
    for rel in &relations {
        if !rel.is_changing() {
            continue;
        }
        let rname = rel.name();
        let rname_low = rname.to_ascii_lowercase();
        if rel.arity() == 1 {
            let atoms: Vec<String> = if imp.alloy_retired_to_sql_table.contains_key(&rname_low) {
                Vec::new()
            } else {
                let t_sql = imp
                    .alloy_to_sql_table
                    .get(&rname_low)
                    .map(String::as_str)
                    .unwrap_or(rname_low.as_str());
                table_row_atoms.get(t_sql).cloned().unwrap_or_default()
            };
            let slices: Vec<[&str; 1]> = atoms.iter().map(|a| [a.as_str()]).collect();
            let refs: Vec<&[&str]> = slices.iter().map(|s| s.as_slice()).collect();
            let ts = u.tuple_set(1, &refs).map_err(|e| vec![e])?;
            state0.set(rel, ts).map_err(|e| vec![e])?;
        } else if rel.arity() == 2 {
            let range_sig = field_range_sig.get(rname).map(String::as_str).unwrap_or("");
            let (owner_hint, col_alloy) = match rname_low.rsplit_once('.') {
                Some((o, c)) => (Some(o), c),
                None => (None, rname_low.as_str()),
            };
            let mut pairs: Vec<(String, String)> = Vec::new();
            for (t_sql, rows) in rows_by_table {
                let t_alloy = sql_to_alloy_table
                    .get(t_sql)
                    .map(String::as_str)
                    .unwrap_or(t_sql.as_str());
                if let Some(oh) = owner_hint
                    && oh != t_alloy
                    && oh != t_sql.as_str()
                {
                    continue;
                }
                let col_sql = imp
                    .alloy_to_sql_col
                    .get(&(t_alloy.to_string(), col_alloy.to_string()))
                    .map(String::as_str)
                    .unwrap_or(col_alloy);
                let Some(ratoms) = table_row_atoms.get(t_sql) else {
                    continue;
                };
                let fk_opt = imp.fk_targets.get(&(t_sql.clone(), col_sql.to_string()));
                for (ratom, (_, row)) in ratoms.iter().zip(rows.iter()) {
                    let Some(val) = row.get(col_sql) else {
                        continue;
                    };
                    if matches!(val, DumpVal::Null) {
                        continue;
                    }
                    let val_atom: Option<String> = if let Some(fk) = fk_opt {
                        pk_row_lookup
                            .get(&(fk.target_table.clone(), fk.target_col.clone(), val.clone()))
                            .cloned()
                    } else if let Some(region) =
                        imp.int_regions.iter().find(|r| r.sig_name == range_sig)
                    {
                        match val {
                            DumpVal::Int(n) => region
                                .intervals
                                .iter()
                                .find(|(lo, hi, _)| {
                                    lo.is_none_or(|l| *n >= l) && hi.is_none_or(|h| *n <= h)
                                })
                                .and_then(|(_, _, atom_sig)| singleton_atoms.get(atom_sig))
                                .cloned(),
                            _ => None,
                        }
                    } else if range_sig == "Int" {
                        match val {
                            DumpVal::Int(n) => u
                                .atom_of_int(*n)
                                .and_then(|i| u.atom(i).map(str::to_string)),
                            _ => None,
                        }
                    } else if range_sig == "SqlBool" {
                        let is_true = match val {
                            DumpVal::Bool(b) => *b,
                            DumpVal::Int(n) => *n != 0,
                            DumpVal::Str(s) => s == "1" || s.eq_ignore_ascii_case("true"),
                            DumpVal::Null => false,
                        };
                        let key = if is_true { "SqlTrue" } else { "SqlFalse" };
                        singleton_atoms.get(key).cloned()
                    } else if ordered_aliases.contains_key(range_sig) {
                        ordered_atom_map
                            .get(&(range_sig.to_string(), val.clone()))
                            .cloned()
                    } else {
                        let sval = match val {
                            DumpVal::Str(s) => s.clone(),
                            DumpVal::Int(n) => n.to_string(),
                            DumpVal::Bool(b) => b.to_string(),
                            DumpVal::Null => unreachable!(),
                        };
                        domain_atom_map.get(&(range_sig.to_string(), sval)).cloned()
                    };
                    if let Some(va) = val_atom {
                        pairs.push((ratom.clone(), va));
                    }
                }
            }
            let slices: Vec<[&str; 2]> = pairs
                .iter()
                .map(|(a, b)| [a.as_str(), b.as_str()])
                .collect();
            let refs: Vec<&[&str]> = slices.iter().map(|p| p.as_slice()).collect();
            let ts = u.tuple_set(2, &refs).map_err(|e| vec![e])?;
            state0.set(rel, ts).map_err(|e| vec![e])?;
        }
    }

    let trace = Trace::new(fixed, vec![state0], 0).map_err(|e| vec![e])?;

    // Evaluate remaining single-state schema facts (CHECK constraints, composite UNIQUE, etc.).
    let mut fact_violations = Vec::new();
    for (fname, inner) in &active_facts {
        match evaluate_trace_at(&trace, inner, 0, &[]) {
            Ok(true) => {}
            Ok(false) => {
                fact_violations.push(RuleViolation {
                    rule: fname.clone(),
                    table: None,
                    detail: "schema rule does not hold on the dumped rows".to_string(),
                    line: None,
                });
            }
            Err(es) => return Err(es),
        }
    }

    // Evaluate every single-state `check` promise from `--with promises.als`.
    let mut promises = Vec::new();
    for (pname, inner) in &active_promises {
        let holds = evaluate_trace_at(&trace, inner, 0, &[])?;
        promises.push((pname.clone(), holds));
    }

    Ok((fact_violations, promises, skipped_promises))
}

/// Audits `data_sql` (a SQL dump of `INSERT` rows) against `schema_sql` and
/// optional sidecar Alloy promises without invoking the SAT solver (N32, R7).
pub fn audit(
    schema_file: &str,
    schema_sql: &str,
    data_file: &str,
    data_sql: &str,
    opts: &AuditOptions,
) -> Output {
    let imp = match elinvar_als::import_sql_with(
        schema_file,
        schema_sql,
        &elinvar_als::SqlImportOptions::new()
            .temporal(true)
            .from_empty(false)
            .tables(opts.tables.clone())
            .with_referencing(opts.with_referencing),
    ) {
        Ok(i) => i,
        Err(errors) => return error_output("audit", errors),
    };

    let (rows_by_table, warnings) = match parse_dump_rows(data_file, data_sql, &imp) {
        Ok(r) => r,
        Err(msg) => return audit_parse_error(msg),
    };

    let rows_audited: usize = rows_by_table.values().map(Vec::len).sum();
    let table_counts: BTreeMap<String, usize> = rows_by_table
        .iter()
        .map(|(t, rs)| (t.clone(), rs.len()))
        .collect();

    let mut rule_violations = check_structural_rules(&imp, &rows_by_table);

    let combined = match opts.extra_als.as_deref() {
        Some(extra) if !extra.trim().is_empty() => format!("{}\n{extra}\n", imp.model),
        _ => imp.model.clone(),
    };
    let model = match elinvar_als::read_with(
        schema_file,
        &combined,
        elinvar_als::ReadOptions::default().default_bitwidth(imp.bitwidth),
    ) {
        Ok(m) => m,
        Err(errors) => return error_output("audit", errors),
    };

    let (fact_violations, promises, skipped_promises) =
        match evaluate_dump_on_model(&model, &imp, &rows_by_table) {
            Ok(res) => res,
            // The model's own coded errors, not a fault of the dump.
            Err(errors) => return error_output("audit", errors),
        };
    // Deduplicate: if a structural check already flagged a broken FK/enum/PK/UNIQUE,
    // still keep Alloy CHECK violations (e.g. `fact items_checks`) that aren't already listed.
    for fv in fact_violations {
        if !rule_violations.iter().any(|rv| rv.rule == fv.rule) {
            rule_violations.push(fv);
        }
    }

    let broken_promises = promises.iter().filter(|(_, holds)| !holds).count();
    let has_violations = !rule_violations.is_empty() || broken_promises > 0;
    let verdict = if has_violations {
        "violations"
    } else {
        "clean"
    };
    let status = if has_violations { 1 } else { 0 };

    let mut text = String::new();
    let _ = writeln!(
        text,
        "audit ({data_file} against {schema_file}): {verdict} ({rows_audited} row(s), {} rule violation(s), {broken_promises} broken promise(s))",
        rule_violations.len()
    );
    for rv in &rule_violations {
        let _ = writeln!(text, "  BROKEN rule {}: {}", rv.rule, rv.detail);
    }
    for (pname, holds) in &promises {
        let word = if *holds { "holds" } else { "BROKEN" };
        let _ = writeln!(text, "  promise {pname}: {word}");
    }
    for (pname, reason) in &skipped_promises {
        let _ = writeln!(text, "  skipped promise {pname}: {reason}");
    }
    for w in &warnings {
        let line = w.place.as_ref().map_or(1, |p| p.line);
        let _ = writeln!(text, "warning[{}]: line {line}: {}", w.code, w.message);
    }
    if !imp.skipped.is_empty() {
        let noun = if imp.skipped.len() == 1 {
            "rule"
        } else {
            "rules"
        };
        let _ = writeln!(
            text,
            "warning: {} {noun} of the schema were not read and could not be checked",
            imp.skipped.len()
        );
    }

    let violations_json: Vec<Value> = rule_violations
        .iter()
        .map(|rv| {
            let mut obj = json!({
                "rule": rv.rule,
                "detail": rv.detail,
            });
            if let Some(t) = &rv.table {
                obj["table"] = Value::String(t.clone());
            }
            if let Some(l) = rv.line {
                obj["line"] = json!(l);
            }
            obj
        })
        .collect();
    let promises_json: Vec<Value> = promises
        .iter()
        .map(|(name, holds)| json!({ "name": name, "holds": holds }))
        .collect();
    let skipped_json: Vec<Value> = skipped_promises
        .iter()
        .map(|(name, reason)| json!({ "name": name, "reason": reason }))
        .collect();

    Output {
        status,
        text: text.clone(),
        json: json!({
            "elinvar": 1,
            "command": "audit",
            "verdict": verdict,
            "rows_audited": rows_audited,
            "tables": table_counts,
            "rule_violations": violations_json,
            "promises": promises_json,
            "skipped_promises": skipped_json,
            "unread_rules": imp.skipped.len(),
            "warnings": warnings,
            "story": text,
        }),
    }
}