elinvar 0.1.0

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
//! `elinvar`: the command line (DESIGN.md section 9.3, R34). Every command
//! is a verb, modes are flags, subjects are arguments (AGENTS.md law 32).
//! This is the one crate that reads files and stdin (AGENTS.md law 8).

use elinvar::cli::{audit, ci, discover, fuzz, mcp, verbs};

use std::io::{Read as _, Write as _};
use std::process::ExitCode;
use verbs::{Output, Overrides};

const VERSION: &str = env!("CARGO_PKG_VERSION");

const HELP: &str = "elinvar: find the holes in a design before you build it

usage: elinvar <verb> [arguments] [flags]

verbs:
  check FILE [NAME]        run every check command of an Alloy file, or the one named
  run FILE [NAME]          run every run command, or the one named (`--all` enumerates all)
  tests FILE               generate step reachability and per-guard refusal tests from a model
  accepts FILE TRACE       check whether a model allows a trace JSON or SQL DML script
  fuzz FILE --against CMD  run seeded random SQL scripts on both a real database and the model
  discover FILE            discover and prove common invariants of a `.sql` schema by induction
  audit FILE --data DUMP   check table rules and single-state promises directly on a SQL dump (no solver)
  ci [MANIFEST]            run a repository manifest under one timeout (Markdown, JUnit, SARIF, JSON)
  diff OLD NEW             compare two Alloy models (or two `.sql` schemas) and show differences
  import FILE              import SQL DDL (CREATE TABLE, UNIQUE INDEX, TRIGGER) into Alloy 6
  render RESULT            render a result JSON's instance or trace as DOT, Mermaid, or SQL
  eval FILE RESULT EXPR    evaluate an expression or formula on a result's instance or
                           trace, without solving again
  explain [CODE|schema:<verb>|skill]
                           explain an error code, print a verb's JSON Schema (or `schema`
                           to list them), print the embedded agent guide, or list every code
  serve --mcp              run the Model Context Protocol (MCP) server over stdio

Pass `-` for any single input file argument to read from stdin.
`elinvar <verb> --help` explains each verb in full; `elinvar --version` prints the version.

exit status: 0 every promise holds, or the instance was found; 1 a counterexample was
found, or no instance exists; 2 a verdict is unknown or vacuous; 3 the model or the
arguments have errors.";

const CHECK_HELP: &str =
    "elinvar check FILE [NAME] [--with FILE] [--from-any] [--tables A,B [--with-referencing]] [--json] [--explain] [--brief] [--summary] [--climb] [--induction [K]] [--no-slicing] [--scope N] [--steps N] [--budget N] [--timeout DUR]

Runs every `check` command of FILE (an Alloy 6 model, or a `.sql` schema paired
with `--with promises.als`), or only the one named NAME (its label, or the
assertion it checks).

For a `.sql` schema, traces start from empty tables by default (`--from-empty`);
pass `--from-any` to start from any state the schema's rules allow.

Each result says one of:
  holds           no counterexample up to the scope searched; a larger case might
                  still break the promise
  proved          proved for any number of steps within the scope by k-induction
  counterexample  a case that breaks it, shrunk to the fewest atoms and tuples
  vacuous         the rules allow no case at all, so nothing can break the promise:
                  the rules are wrong, not the promise right
  unknown         the budget ran out first; the note says what is known

flags:
  --with FILE          append sidecar `.als` promises or `.sql` views/queries (repeatable)
  --from-any           for a `.sql` schema, start from any allowed state (default: empty tables)
  --from-empty         for a `.sql` schema, start from empty tables (default on `check`)
  --tables A,B         for a `.sql` schema, import only these tables and their FK targets
  --with-referencing   with `--tables`, also include tables pointing into the slice
  --json               print the result as JSON (schema: `elinvar explain schema:result`);
                       one result is an object, several are an array
  --explain            on holds, proved, or vacuous checks, extract the minimal unsat core
                       of rules that established the verdict
  --brief              omit empty relations and ordering helpers from text output
  --summary            print one compact Markdown table across all checks (and JSON summary)
  --climb              climb scopes automatically under the conflict budget until a hole is
                       found or the budget runs out
  --induction [K]      prove `always P` for any number of steps by k-induction (default K=1);
                       falls back to bounded traces if the inductive step does not close
  --no-slicing         solve every check whole, without first slicing away what the
                       assertion cannot see: slower, and the reference answer
  --scope N            the scope of every top-level signature the command does not name
  --steps N            at most N states in a trace
  --budget N           at most N solver conflicts per solve (default 10000000)
  --timeout DUR        wall-clock time limit per solve (e.g. `500ms`, `30s`, `2m`)

exit status: 0 all hold/proved (or every `expect` is met); 1 a counterexample (or an `expect` is not met); 2 unknown or vacuous; 3 errors.";

const RUN_HELP: &str =
    "elinvar run FILE [NAME] [--with FILE] [--from-any] [--tables A,B [--with-referencing]] [--shrink] [--all [--limit N] [--sql]] [--json] [--explain] [--brief] [--scope N] [--steps N] [--budget N] [--timeout DUR]

Runs every `run` command of FILE (an Alloy 6 model or `.sql` schema), or only
the one named NAME (its label, or the predicate it runs), and shows an instance
of the facts and the predicate, or says there is none up to the scope.

For a `.sql` schema, traces start from empty tables by default (`--from-empty`);
pass `--from-any` to start from any state the schema's rules allow.

With `--with FILE`, appends sidecar `.als` predicates/commands or `.sql` views.
With `--shrink`, shrinks the found instance to the fewest atoms and tuples.
With `--explain`, when there is no instance, names the minimal set of rules
that, with the run's predicate, allows none.
With `--all`, enumerates every non-isomorphic instance up to the scope (capped at
`--limit N`, default 1000). With `--sql`, renders each instance as SQL inserts.

exit status: 0 found; 1 none; 2 unknown; 3 errors.";

const TESTS_HELP: &str =
    "elinvar tests FILE [--with FILE] [--json] [--sql] [--tables A,B [--with-referencing]] [--values SPEC] [--allow-dead S1,S2] [--scope N] [--steps N] [--budget N] [--timeout DUR]

Generates step reachability and per-guard refusal tests from a model with steps
(or a `.sql` schema, imported with `--temporal --from-empty`):
  - For each step: the shortest trace in which it fires (or flags it as a dead step).
  - For each guard condition of each step: the shortest trace where that condition
    alone refuses the step (or flags it as unreachable / redundant).

In text mode, each test is printed as soon as it finishes; `--budget N` bounds
each test individually and names any unfinished tests at the end.

flags:
  --with FILE          append sidecar `.als` promises/pragmas or `.sql` views (repeatable)
  --sql                render each test case as an executable SQL replay script
  --tables A,B         for a `.sql` schema, test only these tables and their FK targets
  --with-referencing   with `--tables`, also include tables pointing into the slice
  --values SPEC        sample values for SQL columns (`table.col=v1,v2` or `@file`, repeatable)
  --allow-dead S1,S2   steps expected to be dead (exit 0); also read from `-- expect-dead:` comments
  --scope N            scope per top-level signature (default 3)
  --steps N            at most N states per trace (default 5 for `.sql`, 4 for `.als`)
  --budget N           at most N solver conflicts per test
  --timeout DUR        wall-clock time limit per test (e.g. `500ms`, `30s`, `2m`)
  --json               print all results as one JSON document

exit status: 0 all steps reachable (or expected dead) and all guards decide; 1 unexpected dead step or unreachable guard; 2 not reached within steps or unknown; 3 errors.";

const ACCEPTS_HELP: &str =
    "elinvar accepts FILE TRACE [--with FILE] [--tables A,B [--with-referencing]] [--json]

Checks whether TRACE (a result/trace JSON file, or a SQL script of INSERT/UPDATE/DELETE
statements) is allowed by FILE (an Alloy 6 model or a `.sql` schema) and whether every
`check` promise in FILE (and any `--with` sidecar) holds along it.

exit status: 0 trace is allowed and every check holds; 1 refused or a check breaks; 3 errors.";

const FUZZ_HELP: &str =
    "elinvar fuzz FILE [--against CMD] [--seed N] [--scripts N] [--length N] [--require-coverage] [--with FILE] [--tables A,B [--with-referencing]] [--timeout DUR] [--json]

Generates seeded random SQL DML scripts (`INSERT`, `UPDATE`, `DELETE`) from a
`.sql` schema in foreign-key dependency order, runs every statement against both
the real database (`--against`, default `sqlite3`) and Elinvar's imported model,
and shrinks the first statement they judge differently.

flags:
  --against CMD        external database CLI (default `sqlite3`; e.g. `sqlite3` or `psql mydb`)
  --seed N             deterministic random seed (default 1)
  --scripts N          number of random scripts to test (default 100)
  --length N           statements per script (default 8)
  --require-coverage   exit 2 if any table received 0 rows or any read rule never fired
  --with FILE          append sidecar `.als` or `.sql` views/queries (repeatable)
  --tables A,B         import only these tables and their FK targets
  --with-referencing   with `--tables`, also include tables pointing into the slice
  --timeout DUR        wall-clock time limit for the fuzz run (e.g. `30s`, `2m`)
  --json               print the result as JSON (schema: `elinvar explain schema:fuzz`)

exit status: 0 all scripts agreed; 1 shrunk disagreement found; 2 timeout or incomplete coverage; 3 errors.";

const DISCOVER_HELP: &str =
    "elinvar discover FILE [--with FILE] [--tables A,B [--with-referencing]] [--show-rejected] [--scope N] [--budget N] [--timeout DUR] [--json]

Tries common database invariants on each table of FILE (a `.sql` schema):
  - rows never deleted (append-only)
  - rows never deleted while referenced by a child table
  - columns never changing after insert, never changing once set, never cleared,
    always present, non-decreasing, or unique across live rows
  - at most one open/active row per key (nullable marker column unset)

Keeps only the invariants proved for any number of steps within scope by
k-induction, and prints each in plain English together with the triggers and
rules it rests on.

flags:
  --with FILE          append sidecar `.als` rules or `.sql` views/queries (repeatable)
  --tables A,B         discover invariants only on these tables (importing their FK targets)
  --with-referencing   with `--tables`, also include tables pointing into the slice
  --show-rejected      also print candidates that failed, each with its counterexample
  --scope N            scope per top-level signature (default 3)
  --budget N           at most N solver conflicts per candidate (default 200000)
  --timeout DUR        wall-clock time limit for the discovery run (e.g. `30s`, `2m`)
  --json               print the result as JSON (schema: `elinvar explain schema:discover`)

exit status: 0 all candidates finished; 2 some candidates did not finish within budget/timeout; 3 errors.";

const DIFF_HELP: &str =
    "elinvar diff OLD NEW [--with FILE] [--from-any | --from-empty] [--of FUN] [--tables A,B [--with-referencing]] [--ignore-unread] [--no-slicing] [--json] [--scope N] [--steps N] [--budget N] [--timeout DUR]
elinvar diff BASE --migration MIG.sql [...]

Compares two Alloy 6 models sharing the same signatures and fields, or two
`.sql` schemas (or directories of ordered `.sql` migration files; with
`--migration MIG.sql`, compares BASE against BASE plus MIG.sql). Unread rules
identical on both sides are listed once under `unchanged_skipped`, while changed
unread rules stop with `sql.skipped` unless `--ignore-unread` is passed. Finds a
minimal shrunk instance or trace allowed by OLD and forbidden by NEW (tightened),
and one allowed by NEW and forbidden by OLD (loosened).

With `--of FUN`, compares the tuples returned by function or query FUN across
cases allowed by both models, showing tuples lost or gained by NEW.

Verdicts:
  equivalent  both models (or functions) agree up to the scope
  tightened   NEW forbids at least one case (or drops a tuple) OLD allows
  loosened    NEW allows at least one case (or gains a tuple) OLD forbids
  diverged    each side allows a case (or tuple) the other lacks
  unknown     the budget ran out first
  vacuous     with `--of`, the two models together allow no case, so there is
              nothing to compare the functions on: fix the rules

flags:
  --migration FILE     apply SQL migration FILE on top of BASE and diff BASE vs BASE+FILE
  --with FILE          append sidecar `.als` or `.sql` views/queries to both sides (repeatable)
  --from-any           for `.sql` schemas, compare transitions from any allowed state (default on `diff`, 2 steps)
  --from-empty         for `.sql` schemas, start traces from empty tables (4 steps by default)
  --of FUN             compare one function, view, parameterized predicate, or expression
  --tables A,B         for `.sql` schemas, compare only these tables plus their FK
                       and trigger targets
  --with-referencing   with `--tables`, also include tables pointing into the slice
  --ignore-unread      for `.sql` schemas, compare what is read and list differing unread
                       rules under `not_compared` (exits 2 so unread changes are never silent)
  --no-slicing         solve each side whole, without slicing or reductions: slower,
                       and the reference answer
  --json               print the diff report as JSON
  --scope N            the scope of every top-level signature (default 3)
  --steps N            at most N states in a trace
  --budget N           at most N solver conflicts per solve
  --timeout DUR        wall-clock time limit per solve (e.g. `500ms`, `30s`, `2m`)

exit status: 0 equivalent; 1 tightened, loosened, or diverged; 2 unknown, vacuous, or not_compared; 3 errors.";

const IMPORT_HELP: &str =
    "elinvar import FILE|DIR [--with FILE] [--json] [--strict] [--temporal [--from-empty | --from-any]] [--tables A,B [--with-referencing]] [--only-ruled]

Reads SQL DDL (CREATE TABLE, CREATE TYPE ... AS ENUM, ALTER TABLE, DROP TABLE/INDEX/TRIGGER,
CREATE UNIQUE INDEX, PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY / REFERENCES, CHECK
constraints, and with `--temporal`, CREATE TRIGGER statements) from FILE (or a directory
of ordered `*.sql` migration files) and emits an Alloy 6 model in Elinvar's subset.
With `--with FILE`, appends sidecar `.sql` views/queries and `.als` promises/predicates.
With `--temporal`, traces start from any allowed state by default (`--from-any`); pass
`--from-empty` to require all tables to start empty.

Any statement or constraint not carried into the model is noted as a `-- not
read` comment, listed under `skipped` in `--json`, and summarized on stderr.

flags:
  --json              print `{ elinvar, tables, skipped, ignored, outside_referencing_tables, dropped_triggers, sample_values, views, model }` as JSON (`views` only when there are some; `elinvar explain schema:import`)
  --strict            fail with exit 3 if any SQL rule was skipped (non-rule statements
                      such as `CREATE INDEX` and `PRAGMA` are listed under `ignored`)
  --temporal          emit stateful `var` tables, insert/update/delete steps, and triggers
  --from-empty        with `--temporal`, require all tables to start empty so every state
                      is reached by guarded steps
  --tables A,B        import only these tables and those they reference via foreign keys
  --with-referencing  with `--tables`, also include tables that point into the slice via FKs
  --only-ruled        omit columns not mentioned in any key, index, constraint, or trigger

exit status: 0 imported; 3 errors (or skipped rules with `--strict`).";

const RENDER_HELP: &str =
    "elinvar render FILE [--format dot|mermaid|sql] [--dot] [--mermaid] [--sql] [--state K] [--values SPEC] [--json]

Renders either:
  - a result JSON file from `elinvar check --json` or `elinvar run --json`, as
    Graphviz DOT (default), Mermaid, or executable SQL replay statements (`--sql`), or
  - an Alloy model (`.als`) or SQL schema (`.sql`), as a DOT or Mermaid overview of
    its signatures, `var` relations, `extends` hierarchy, fields, and step predicates.

flags:
  --format FMT    output format: `dot` (default), `mermaid`, or `sql`
  --dot           shorthand for `--format dot`
  --mermaid       shorthand for `--format mermaid`
  --sql           shorthand for `--format sql` (result JSON only)
  --state K       for a trace result, render only state K (from 0)
  --values SPEC   sample column values for `--sql` (`table.col=v1,v2` or `@file`, repeatable)
  --json          print `{ elinvar, format, diagram, ... }` as JSON

exit status: 0 rendered; 3 errors.";

const EVAL_HELP: &str = "elinvar eval FILE RESULT EXPR [--state K] [--with FILE] [--tables A,B [--with-referencing]] [--json]

Evaluates EXPR, an expression or a formula in the model of FILE (an Alloy `.als`
model, a `.sql` schema, or a SQL migrations directory), on the instance or trace
of RESULT, a file with the JSON of one result of `elinvar check --json` or
`elinvar run --json` for that model. Relations are matched by name. With a trace,
--state K picks the state, from 0 (default 0).

An expression prints its tuples, `{A, B}` or `{A -> B}`; a formula prints `true`
or `false`.

flags:
  --state K            for a trace result, evaluate at state K (from 0, default 0)
  --with FILE          append sidecar `.als` promises or `.sql` views/queries (repeatable)
  --tables A,B         narrow a `.sql` schema to these tables and their FK targets
  --with-referencing   with `--tables`, also include tables pointing into the slice
  --json               print the evaluated result as JSON (schema: `elinvar explain schema:eval`)

exit status: 0 evaluated; 3 errors.";

const AUDIT_HELP: &str =
    "elinvar audit SCHEMA --data DUMP.sql [--with FILE] [--tables A,B [--with-referencing]] [--json]

Audits the rows of a real database dump (INSERT statements from `sqlite3 .dump`
or `pg_dump --inserts`) as one state against SCHEMA (a `.sql` file or migrations
directory) and any sidecar `--with promises.als` / `.sql` views.

Evaluates every table rule (NOT NULL, PRIMARY KEY, UNIQUE, partial UNIQUE,
FOREIGN KEY, CHECK, enum) and every single-state promise directly without
invoking the SAT solver (R7). Multi-step temporal promises are listed under
`skipped_promises`.

What the dump holds and the audit does not read is a warning: rows of a table
not in SCHEMA or its `--tables` slice (`audit.dropped_rows`), a statement that
is not an INSERT, such as `COPY` or `UPDATE` (`audit.ignored_statement`), and a
dump with no INSERT at all (`audit.no_rows`). A file with no INSERT and other
text is not a dump, and is an error (`audit.parse`).

flags:
  --data FILE          SQL dump file containing INSERT statements (required; `-` for stdin)
  --with FILE          append sidecar `.als` promises or `.sql` views/queries (repeatable)
  --tables A,B         audit only these tables and their FK targets
  --with-referencing   with `--tables`, also include tables pointing into the slice
  --json               print the audit report as JSON (schema: `elinvar explain schema:audit`)

exit status: 0 all rules and promises hold; 1 at least one rule or promise was broken; 3 errors.";

const CI_HELP: &str =
    "elinvar ci [MANIFEST] [--timeout DUR] [--junit | --sarif | --json]

Runs every entry (`[[check]]`, `[[run]]`, `[[accepts]]`, `[[diff]]`,
`[[discover]]`, `[[tests]]`) in MANIFEST (default `elinvar.toml`) under one
shared wall-clock time limit, checking each entry against its `expect` verdict.

Outputs a Markdown summary table by default, or JUnit XML (`--junit`),
SARIF 2.1.0 (`--sarif`), or JSON (`--json`, schema: `elinvar explain schema:ci`).

flags:
  --timeout DUR   shared wall-clock time limit overriding manifest `timeout` (e.g. `60s`, `5m`)
  --junit         write a JUnit XML report
  --sarif         write a SARIF 2.1.0 report
  --json          print the full CI report as JSON

exit status: 0 all entries met expectations; 1 at least one entry failed; 2 at least one timed out / unknown; 3 manifest or argument error.";

const EXPLAIN_HELP: &str = "elinvar explain [CODE | schema[:NAME] | skill] [--json]

With a code, such as `arity.mismatch`, says when it is raised and how to fix it.
With `schema:<name>` (`schema:result`, `schema:diff`, `schema:import`, `schema:render`,
`schema:eval`, `schema:tests`, `schema:accepts`, `schema:fuzz`, `schema:discover`,
`schema:ci`, `schema:audit`), prints that verb's JSON Schema; with `schema`, lists all schemas. With
`skill`, prints the embedded agent guide (SKILL.md). With nothing, lists every code.";

const SERVE_HELP: &str = "elinvar serve --mcp

Serves the Model Context Protocol over stdin and stdout, one JSON-RPC message per
line. Exposes tools (check, run, tests, accepts, discover, audit, diff, import_sql,
render, eval, explain), server instructions on initialize, and resources
(`skill://elinvar/SKILL.md` and `elinvar://schema/<verb>-v1.json`). The server
keeps no state between calls.";

struct Args {
    positional: Vec<String>,
    json: bool,
    help: bool,
    mcp: bool,
    strict: bool,
    temporal: bool,
    from_empty: bool,
    from_any: bool,
    tables: Vec<String>,
    with_files: Vec<String>,
    with_referencing: bool,
    only_ruled: bool,
    values: Vec<String>,
    allow_dead: Vec<String>,
    all: bool,
    limit: Option<usize>,
    diff_of: Option<String>,
    migration: Option<String>,
    data_file: Option<String>,
    against: Option<String>,
    seed: Option<u64>,
    scripts: Option<usize>,
    length: Option<usize>,
    require_coverage: bool,
    show_rejected: bool,
    junit: bool,
    sarif: bool,
    over: Overrides,
    state: Option<usize>,
    format: elinvar::DiagramFormat,
    format_set: bool,
}

fn parse(args: &[String]) -> Result<Args, String> {
    let mut a = Args {
        positional: Vec::new(),
        json: false,
        help: false,
        mcp: false,
        strict: false,
        temporal: false,
        from_empty: false,
        from_any: false,
        tables: Vec::new(),
        with_files: Vec::new(),
        with_referencing: false,
        only_ruled: false,
        values: Vec::new(),
        allow_dead: Vec::new(),
        all: false,
        limit: None,
        diff_of: None,
        migration: None,
        data_file: None,
        against: None,
        seed: None,
        scripts: None,
        length: None,
        require_coverage: false,
        show_rejected: false,
        junit: false,
        sarif: false,
        over: Overrides::default(),
        state: None,
        format: elinvar::DiagramFormat::Dot,
        format_set: false,
    };
    let mut it = args.iter().peekable();
    while let Some(x) = it.next() {
        let mut number = |flag: &str| -> Result<usize, String> {
            it.next()
                .and_then(|v| v.parse().ok())
                .ok_or_else(|| format!("{flag} needs a number"))
        };
        match x.as_str() {
            "--json" => a.json = true,
            "--explain" => a.over.explain = true,
            "--brief" => a.over.brief = true,
            "--climb" => a.over.climb = true,
            "--no-slicing" => a.over.no_slicing = true,
            "--summary" => a.over.summary = true,
            "--shrink" => a.over.shrink = true,
            "--all" => a.all = true,
            "--limit" => a.limit = Some(number("--limit")?),
            "--of" => {
                let name = it
                    .next()
                    .ok_or("--of needs a function name or expression")?;
                a.diff_of = Some(name.clone());
            }
            "--migration" => {
                let path = it.next().ok_or("--migration needs a SQL file path")?;
                a.migration = Some(path.clone());
            }
            "--data" => {
                let path = it.next().ok_or("--data needs a SQL dump file path")?;
                a.data_file = Some(path.clone());
            }
            "--against" => {
                let cmd = it
                    .next()
                    .ok_or("--against needs a database command (for example `sqlite3`)")?;
                a.against = Some(cmd.clone());
            }
            "--seed" => a.seed = Some(number("--seed")? as u64),
            "--scripts" => a.scripts = Some(number("--scripts")?),
            "--length" => a.length = Some(number("--length")?),
            "--require-coverage" => a.require_coverage = true,
            "--show-rejected" => a.show_rejected = true,
            "--junit" => a.junit = true,
            "--sarif" => a.sarif = true,
            "--ignore-unread" => a.over.ignore_unread = true,
            "--help" | "-h" => a.help = true,
            "--mcp" => a.mcp = true,
            "--strict" => a.strict = true,
            "--temporal" => a.temporal = true,
            "--from-empty" => {
                a.from_empty = true;
                a.over.from_empty = true;
            }
            "--from-any" => {
                a.from_any = true;
                a.over.from_any = true;
            }
            "--with" => {
                let path = it.next().ok_or("--with needs a file path")?;
                a.with_files.push(path.clone());
            }
            "--with-referencing" => a.with_referencing = true,
            "--only-ruled" => a.only_ruled = true,
            "--values" => {
                let raw = it
                    .next()
                    .ok_or("--values needs `table.col=val1,val2` or `@file`")?;
                a.values.push(raw.clone());
            }
            "--allow-dead" => {
                let raw = it
                    .next()
                    .ok_or("--allow-dead needs a comma-separated list of step names")?;
                for part in raw.split(',') {
                    let s = part.trim();
                    if !s.is_empty() {
                        a.allow_dead.push(s.to_string());
                    }
                }
            }
            "--tables" => {
                let raw = it
                    .next()
                    .ok_or("--tables needs a comma-separated list of table names")?;
                for part in raw.split(',') {
                    let t = part.trim();
                    if !t.is_empty() {
                        a.tables.push(t.to_string());
                    }
                }
                if a.tables.is_empty() {
                    return Err("--tables needs at least one table name".to_string());
                }
            }
            "--dot" => {
                a.format = elinvar::DiagramFormat::Dot;
                a.format_set = true;
            }
            "--mermaid" => {
                a.format = elinvar::DiagramFormat::Mermaid;
                a.format_set = true;
            }
            "--sql" => {
                a.format = elinvar::DiagramFormat::Sql;
                a.format_set = true;
            }
            "--format" => {
                let name = it
                    .next()
                    .ok_or("--format needs `dot`, `mermaid`, or `sql`")?;
                a.format = verbs::diagram_format(name).ok_or_else(|| {
                    format!("unknown format `{name}` (use `dot`, `mermaid`, or `sql`)")
                })?;
                a.format_set = true;
            }
            "--scope" => a.over.scope = Some(number("--scope")?),
            "--steps" => a.over.steps = Some(number("--steps")?),
            "--budget" => a.over.budget = Some(number("--budget")? as u64),
            "--timeout" => {
                let raw = it
                    .next()
                    .ok_or("--timeout needs a duration (e.g. `500ms`, `30s`, `2m`)")?;
                a.over.timeout_ms = Some(verbs::parse_duration_ms(raw)?);
            }
            "--induction" => {
                let k = if let Some(next) = it.peek()
                    && let Ok(n) = next.parse::<usize>()
                    && n >= 1
                {
                    let _ = it.next();
                    n
                } else {
                    1
                };
                a.over.inductive = Some(k);
            }
            "--state" => a.state = Some(number("--state")?),
            f if f.starts_with('-') && f.len() > 1 => return Err(format!("unknown flag `{f}`")),
            _ => a.positional.push(x.clone()),
        }
    }
    Ok(a)
}

/// Rejects flags that do not apply to `verb` (AGENTS.md law 20: nothing fails
/// silently).
fn validate_flags(verb: &str, a: &Args) -> Result<(), String> {
    if a.over.explain && verb != "check" && verb != "run" {
        return Err(format!(
            "`--explain` is only valid for `check` and `run`, not `{verb}`"
        ));
    }
    if a.over.inductive.is_some() && verb != "check" {
        return Err(format!(
            "`--induction` is only valid for `check`, not `{verb}`"
        ));
    }
    if a.over.climb && verb != "check" {
        return Err(format!("`--climb` is only valid for `check`, not `{verb}`"));
    }
    if a.over.no_slicing && !matches!(verb, "check" | "diff") {
        return Err(format!(
            "`--no-slicing` is only valid for `check` and `diff`, not `{verb}`"
        ));
    }
    if a.over.summary && verb != "check" {
        return Err(format!(
            "`--summary` is only valid for `check`, not `{verb}`"
        ));
    }
    if a.over.shrink && verb != "run" {
        return Err(format!("`--shrink` is only valid for `run`, not `{verb}`"));
    }
    if a.diff_of.is_some() && verb != "diff" {
        return Err(format!("`--of` is only valid for `diff`, not `{verb}`"));
    }
    if a.migration.is_some() && verb != "diff" {
        return Err(format!(
            "`--migration` is only valid for `diff`, not `{verb}`"
        ));
    }
    if a.data_file.is_some() && verb != "audit" {
        return Err(format!("`--data` is only valid for `audit`, not `{verb}`"));
    }
    if a.over.ignore_unread && verb != "diff" {
        return Err(format!(
            "`--ignore-unread` is only valid for `diff`, not `{verb}`"
        ));
    }
    if (a.junit || a.sarif) && verb != "ci" {
        return Err(format!(
            "`--junit` and `--sarif` are only valid for `ci`, not `{verb}`"
        ));
    }
    if a.junit && a.sarif {
        return Err("cannot pass both `--junit` and `--sarif`".to_string());
    }
    if (a.junit || a.sarif) && a.json {
        return Err("cannot combine `--junit` or `--sarif` with `--json`".to_string());
    }
    if a.over.brief && !matches!(verb, "check" | "run") {
        return Err(format!(
            "`--brief` is only valid for `check` and `run`, not `{verb}`"
        ));
    }
    if (a.over.scope.is_some() || a.over.budget.is_some())
        && !matches!(verb, "check" | "run" | "diff" | "tests" | "discover")
    {
        return Err(format!(
            "`--scope` and `--budget` are not valid for `{verb}`"
        ));
    }
    if a.over.steps.is_some() && !matches!(verb, "check" | "run" | "diff" | "tests") {
        return Err(format!("`--steps` is not valid for `{verb}`"));
    }
    if a.over.timeout_ms.is_some()
        && !matches!(
            verb,
            "check" | "run" | "diff" | "tests" | "fuzz" | "discover" | "ci"
        )
    {
        return Err(format!("`--timeout` is not valid for `{verb}`"));
    }
    if (a.against.is_some()
        || a.seed.is_some()
        || a.scripts.is_some()
        || a.length.is_some()
        || a.require_coverage)
        && verb != "fuzz"
    {
        return Err(format!(
            "`--against`, `--seed`, `--scripts`, `--length`, and `--require-coverage` are only valid for `fuzz`, not `{verb}`"
        ));
    }
    if a.show_rejected && verb != "discover" {
        return Err(format!(
            "`--show-rejected` is only valid for `discover`, not `{verb}`"
        ));
    }
    if (a.all || a.limit.is_some()) && verb != "run" {
        return Err(format!(
            "`--all` and `--limit` are only valid for `run`, not `{verb}`"
        ));
    }
    if a.limit.is_some() && !a.all {
        return Err("`--limit` requires `--all`".to_string());
    }
    if a.all && a.over.explain {
        return Err(
            "`--explain` explains a run with no instance; `--all` lists instances, so they do not go together"
                .to_string(),
        );
    }
    if verb == "run" && a.format_set && a.format == elinvar::DiagramFormat::Sql && !a.all {
        return Err("`--sql` on `run` requires `--all`".to_string());
    }
    if a.format_set {
        let sql_on_other =
            a.format == elinvar::DiagramFormat::Sql && matches!(verb, "tests" | "run");
        if verb != "render" && !sql_on_other {
            return Err(format!(
                "`--format`, `--dot`, `--mermaid`, and `--sql` are not valid for `{verb}`"
            ));
        }
    }
    if a.state.is_some() && !matches!(verb, "eval" | "render") {
        return Err(format!(
            "`--state` is only valid for `eval` and `render`, not `{verb}`"
        ));
    }
    if a.mcp && verb != "serve" {
        return Err(format!("`--mcp` is only valid for `serve`, not `{verb}`"));
    }
    if (a.strict || a.temporal || a.only_ruled) && verb != "import" {
        return Err(format!(
            "`--strict`, `--temporal`, and `--only-ruled` are only valid for `import`, not `{verb}`"
        ));
    }
    if a.from_empty && a.from_any {
        return Err("`--from-empty` and `--from-any` cannot both be set".to_string());
    }
    if a.from_empty && !matches!(verb, "import" | "check" | "run" | "diff") {
        return Err(format!(
            "`--from-empty` is only valid for `import`, `check`, `run`, and `diff`, not `{verb}`"
        ));
    }
    if a.from_any && !matches!(verb, "import" | "check" | "run" | "diff") {
        return Err(format!(
            "`--from-any` is only valid for `import`, `check`, `run`, and `diff`, not `{verb}`"
        ));
    }
    if verb == "import" && (a.from_empty || a.from_any) && !a.temporal {
        return Err("`--from-empty` and `--from-any` on `import` require `--temporal`".to_string());
    }
    if a.with_referencing && a.tables.is_empty() {
        return Err("`--with-referencing` requires `--tables`".to_string());
    }
    if (!a.tables.is_empty() || a.with_referencing)
        && !matches!(
            verb,
            "import"
                | "tests"
                | "diff"
                | "check"
                | "run"
                | "accepts"
                | "fuzz"
                | "discover"
                | "audit"
                | "eval"
        )
    {
        return Err(format!(
            "`--tables` and `--with-referencing` are not valid for `{verb}`"
        ));
    }
    if !a.with_files.is_empty()
        && !matches!(
            verb,
            "check"
                | "run"
                | "tests"
                | "diff"
                | "accepts"
                | "import"
                | "fuzz"
                | "discover"
                | "audit"
                | "eval"
        )
    {
        return Err(format!("`--with` is not valid for `{verb}`"));
    }
    if !a.values.is_empty() && !matches!(verb, "tests" | "render") {
        return Err(format!(
            "`--values` is only valid for `tests` and `render`, not `{verb}`"
        ));
    }
    if !a.allow_dead.is_empty() && verb != "tests" {
        return Err(format!(
            "`--allow-dead` is only valid for `tests`, not `{verb}`"
        ));
    }
    Ok(())
}

fn parse_sample_values(
    specs: &[String],
) -> Result<std::collections::BTreeMap<String, Vec<String>>, Refusal> {
    let mut out: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();
    let mut parse_line = |raw: &str| -> Result<(), String> {
        let t = raw.trim();
        if t.is_empty() || t.starts_with('#') || t.starts_with("--") {
            return Ok(());
        }
        let (key, vals_raw) = t.split_once('=').ok_or_else(|| {
            format!("malformed `--values` entry `{t}` (expected `table.col=v1,v2`)")
        })?;
        let k = key.trim().to_ascii_lowercase();
        let vals: Vec<String> = vals_raw
            .split(',')
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .collect();
        if k.is_empty() || vals.is_empty() {
            return Err(format!(
                "malformed `--values` entry `{t}` (expected `table.col=v1,v2`)"
            ));
        }
        out.entry(k).or_default().extend(vals);
        Ok(())
    };
    for spec in specs {
        if let Some(path) = spec.strip_prefix('@') {
            let body = read(path)?;
            for line in body.lines() {
                parse_line(line)?;
            }
        } else {
            parse_line(spec)?;
        }
    }
    Ok(out)
}

fn is_sql_input(path: &str) -> bool {
    path.ends_with(".sql") || (path != "-" && std::path::Path::new(path).is_dir())
}

fn sql_display_path(path: &str) -> String {
    if path == "-" {
        "<stdin>".to_string()
    } else if std::path::Path::new(path).is_dir() {
        format!("{}.sql", path.trim_end_matches('/'))
    } else {
        path.to_string()
    }
}

fn read(path: &str) -> Result<String, Refusal> {
    if path == "-" {
        let mut buf = String::new();
        std::io::stdin()
            .read_to_string(&mut buf)
            .map_err(|e| Refusal::input(format!("cannot read stdin: {e}")))?;
        Ok(buf)
    } else if std::path::Path::new(path).is_dir() {
        // SQL.md section 1.1: the files joined, their places kept.
        elinvar::cli::migrations::read(std::path::Path::new(path)).map_err(Refusal::input)
    } else {
        std::fs::read_to_string(path)
            .map_err(|e| Refusal::input(format!("cannot read `{path}`: {e}")))
    }
}

/// `text`, read from `path`, parsed as JSON; an error names `path`.
fn parse_json(text: &str, path: &str) -> Result<serde_json::Value, Refusal> {
    serde_json::from_str(text)
        .map_err(|e| Refusal::input(format!("`{}` is not JSON: {e}", display_path(path))))
}

/// The help of a verb, or `None` for one that has none of its own.
fn verb_help(verb: &str) -> Option<&'static str> {
    Some(match verb {
        "check" => CHECK_HELP,
        "run" => RUN_HELP,
        "tests" => TESTS_HELP,
        "accepts" => ACCEPTS_HELP,
        "fuzz" => FUZZ_HELP,
        "discover" => DISCOVER_HELP,
        "audit" => AUDIT_HELP,
        "ci" => CI_HELP,
        "diff" => DIFF_HELP,
        "import" => IMPORT_HELP,
        "render" => RENDER_HELP,
        "eval" => EVAL_HELP,
        "explain" => EXPLAIN_HELP,
        "serve" => SERVE_HELP,
        _ => return None,
    })
}

fn display_path(path: &str) -> &str {
    if path == "-" { "<stdin>" } else { path }
}

/// Loads `--with FILE` sidecars, separating `.sql` query/view files from `.als`
/// promise/predicate files (N23).
fn load_sidecars(paths: &[String]) -> Result<(String, Option<String>), Refusal> {
    let mut extra_sql = String::new();
    let mut extra_als = String::new();
    for path in paths {
        let body = read(path)?;
        if path.ends_with(".sql") {
            extra_sql.push('\n');
            extra_sql.push_str(&body);
            extra_sql.push('\n');
        } else {
            extra_als.push('\n');
            extra_als.push_str(&body);
            extra_als.push('\n');
        }
    }
    let als = if extra_als.trim().is_empty() {
        None
    } else {
        Some(extra_als)
    };
    Ok((extra_sql, als))
}

fn read_pair(a: &str, b: &str) -> Result<(String, String), Refusal> {
    if a == "-" && b == "-" {
        return Err(Refusal::from("cannot read both inputs from stdin (`-`)"));
    }
    Ok((read(a)?, read(b)?))
}

fn print(out: &Output, json: bool) -> ExitCode {
    let mut stdout = std::io::stdout().lock();
    let _ = if json {
        let mut v = out.json.clone();
        elinvar::cli::migrations::remap_json(&mut v);
        writeln!(
            stdout,
            "{}",
            serde_json::to_string_pretty(&v).unwrap_or_default()
        )
    } else {
        write!(
            stdout,
            "{}",
            elinvar::cli::migrations::remap_text(&out.text)
        )
    };
    ExitCode::from(out.status)
}

/// CLI-only stderr heartbeat for long-running solves (N26; AGENTS.md law 23
/// keeps all stderr output in the command line, never in the library).
/// Silent for fast commands; prints a live status line every 3 seconds while
/// a solve is in progress.
struct ProgressReporter {
    state: std::sync::Arc<(std::sync::Mutex<(bool, String)>, std::sync::Condvar)>,
    thread: Option<std::thread::JoinHandle<()>>,
}

impl ProgressReporter {
    fn start(initial: String) -> Self {
        let state = std::sync::Arc::new((
            std::sync::Mutex::new((false, initial)),
            std::sync::Condvar::new(),
        ));
        let bg = std::sync::Arc::clone(&state);
        let started = std::time::Instant::now();
        let thread = std::thread::spawn(move || {
            let (lock, cvar) = &*bg;
            let mut guard = match lock.lock() {
                Ok(g) => g,
                Err(_) => return,
            };
            let interval = std::time::Duration::from_secs(3);
            while !guard.0 {
                let (g, timeout) = match cvar.wait_timeout(guard, interval) {
                    Ok(pair) => pair,
                    Err(_) => return,
                };
                guard = g;
                if guard.0 {
                    break;
                }
                if timeout.timed_out() {
                    let secs = started.elapsed().as_secs();
                    eprintln!("[elinvar] {} ({secs}s elapsed)...", guard.1);
                }
            }
        });
        ProgressReporter {
            state,
            thread: Some(thread),
        }
    }

    fn set(&self, status: &str) {
        if let Ok(mut guard) = self.state.0.lock() {
            guard.1.clear();
            guard.1.push_str(status);
        }
    }
}

impl Drop for ProgressReporter {
    fn drop(&mut self) {
        if let Ok(mut guard) = self.state.0.lock() {
            guard.0 = true;
            self.state.1.notify_all();
        }
        if let Some(handle) = self.thread.take() {
            let _ = handle.join();
        }
    }
}

/// Why a verb stopped before it ran: a flag or argument it cannot use
/// (`cli.usage`), or an input it cannot read (`cli.input`). Both are
/// listed by `elinvar explain` (AGENTS.md law 21).
struct Refusal {
    code: &'static str,
    message: String,
}

impl Refusal {
    fn input(message: String) -> Refusal {
        Refusal {
            code: "cli.input",
            message,
        }
    }
}

impl From<String> for Refusal {
    fn from(message: String) -> Refusal {
        Refusal {
            code: "cli.usage",
            message,
        }
    }
}

impl From<&String> for Refusal {
    fn from(message: &String) -> Refusal {
        Refusal::from(message.clone())
    }
}

impl From<&str> for Refusal {
    fn from(message: &str) -> Refusal {
        Refusal::from(message.to_string())
    }
}

impl From<&Refusal> for Refusal {
    fn from(r: &Refusal) -> Refusal {
        Refusal {
            code: r.code,
            message: r.message.clone(),
        }
    }
}

fn usage(refusal: impl Into<Refusal>, help: &str, json: bool) -> ExitCode {
    let Refusal { code, message } = refusal.into();
    if json {
        // `error` and `help` keep their first shape; `code` was added
        // beside them (schema:usage).
        let body = serde_json::json!({
            "elinvar": 1,
            "code": code,
            "error": message,
            "help": help,
        });
        let mut stdout = std::io::stdout().lock();
        let _ = writeln!(
            stdout,
            "{}",
            serde_json::to_string_pretty(&body).unwrap_or_default()
        );
    } else {
        eprintln!("elinvar: error[{code}]: {message}\n\n{help}");
    }
    ExitCode::from(3)
}

fn main() -> ExitCode {
    // Every command runs on a thread with a stack large enough for the
    // tallest tree the readers accept (`elinvar::cli::MODEL_STACK`).
    match elinvar::cli::model_thread().spawn(run) {
        Ok(handle) => handle.join().unwrap_or(ExitCode::from(101)),
        Err(_) => run(),
    }
}

fn run() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let Some(verb) = args.first() else {
        println!("{HELP}");
        return ExitCode::SUCCESS;
    };
    let wants_json = args.iter().any(|x| x == "--json");
    if matches!(verb.as_str(), "--version" | "-V" | "version") {
        if wants_json {
            let body = serde_json::json!({
                "elinvar": 1,
                "version": VERSION,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&body).unwrap_or_default()
            );
        } else {
            println!("elinvar {VERSION}");
        }
        return ExitCode::SUCCESS;
    }
    let mut a = match parse(&args[1..]) {
        Ok(a) => a,
        Err(m) => return usage(&m, HELP, wants_json),
    };
    let help = verb_help(verb).unwrap_or(HELP);
    if a.help && verb_help(verb).is_some() {
        println!("{help}");
        return ExitCode::SUCCESS;
    }
    if verb_help(verb).is_some()
        && let Err(m) = validate_flags(verb, &a)
    {
        return usage(&m, help, a.json);
    }
    let p: Vec<&str> = a.positional.iter().map(String::as_str).collect();
    match verb.as_str() {
        "--help" | "-h" | "help" => {
            println!("{HELP}");
            ExitCode::SUCCESS
        }
        "check" | "run" => {
            let (file, name) = match p[..] {
                [f] => (f, None),
                [f, n] => (f, Some(n)),
                _ => return usage("expected FILE and an optional NAME", help, a.json),
            };
            let raw_text = match read(file) {
                Ok(t) => t,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let verb: &'static str = if verb == "check" { "check" } else { "run" };
            let file_disp = sql_display_path(file);
            let is_sql = is_sql_input(file);
            let text = if is_sql {
                let full_sql = if extra_sql.is_empty() {
                    raw_text
                } else {
                    format!("{raw_text}\n{extra_sql}")
                };
                match verbs::compose_sql_model_with_bitwidth(
                    verb,
                    &file_disp,
                    &full_sql,
                    extra_als.as_deref(),
                    &a.tables,
                    a.with_referencing,
                    !a.from_any,
                ) {
                    Ok((m, bw)) => {
                        a.over.default_bitwidth = Some(bw);
                        m
                    }
                    Err(out) => return print(&out, a.json),
                }
            } else if let Some(extra) = extra_als {
                format!("{raw_text}\n{extra}\n")
            } else {
                raw_text
            };
            let allow_local = file != "-" && !is_sql;
            let progress = ProgressReporter::start(format!("{verb} {}", display_path(file)));
            let out = if verb == "run" && a.all {
                let as_sql = a.format_set && a.format == elinvar::DiagramFormat::Sql;
                verbs::run_all(
                    display_path(file),
                    &text,
                    name,
                    a.over,
                    as_sql,
                    a.limit.unwrap_or(1000),
                    allow_local,
                )
            } else {
                verbs::solve_with_progress(
                    verb,
                    display_path(file),
                    &text,
                    name,
                    a.over,
                    allow_local,
                    &|msg| progress.set(msg),
                )
            };
            drop(progress);
            print(&out, a.json)
        }
        "tests" => {
            let [file] = p[..] else {
                return usage("expected FILE", help, a.json);
            };
            let raw_text = match read(file) {
                Ok(t) => t,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let file_disp = sql_display_path(file);
            let is_sql = is_sql_input(file);
            let text = if is_sql && !extra_sql.is_empty() {
                format!("{raw_text}\n{extra_sql}")
            } else {
                raw_text
            };
            let sample_values = match parse_sample_values(&a.values) {
                Ok(v) => v,
                Err(m) => return usage(&m, help, a.json),
            };
            let as_sql = a.format_set && a.format == elinvar::DiagramFormat::Sql;
            let opts = verbs::TestsOptions {
                as_sql,
                tables: a.tables,
                with_referencing: a.with_referencing,
                sample_values,
                allow_dead: a.allow_dead,
                extra_als,
            };
            if a.json {
                let _progress = ProgressReporter::start(format!("tests {file_disp}"));
                let out = verbs::tests_with_options(
                    &file_disp,
                    &text,
                    a.over,
                    &opts,
                    file != "-" && !is_sql,
                    None,
                );
                print(&out, true)
            } else {
                let mut stream_cb = |chunk: &str| {
                    let mut stdout = std::io::stdout().lock();
                    let _ = write!(stdout, "{chunk}");
                    let _ = stdout.flush();
                };
                let out = verbs::tests_with_options(
                    &file_disp,
                    &text,
                    a.over,
                    &opts,
                    file != "-" && !is_sql,
                    Some(&mut stream_cb),
                );
                // If parsing/import failed before streaming any case, print errors now.
                if out.status == 3 {
                    return print(&out, false);
                }
                ExitCode::from(out.status)
            }
        }
        "accepts" => {
            let [file, trace_file] = p[..] else {
                return usage("expected FILE and TRACE", help, a.json);
            };
            let (raw_text, trace_text) = match read_pair(file, trace_file) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let file_disp = sql_display_path(file);
            let is_sql = is_sql_input(file);
            let text = if is_sql && !extra_sql.is_empty() {
                format!("{raw_text}\n{extra_sql}")
            } else {
                raw_text
            };
            let out = verbs::accepts_with_options(
                &file_disp,
                &text,
                &trace_text,
                file != "-" && !is_sql,
                extra_als.as_deref(),
                &a.tables,
                a.with_referencing,
            );
            print(&out, a.json)
        }
        "fuzz" => {
            let [file] = p[..] else {
                return usage("expected FILE (a `.sql` schema)", help, a.json);
            };
            let raw_sql = match read(file) {
                Ok(t) => t,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let full_sql = if extra_sql.is_empty() {
                raw_sql
            } else {
                format!("{raw_sql}\n{extra_sql}")
            };
            let opts = fuzz::FuzzOptions {
                against: a.against.unwrap_or_else(|| "sqlite3".to_string()),
                seed: a.seed.unwrap_or(1),
                scripts: a.scripts.unwrap_or(100),
                length: a.length.unwrap_or(8),
                tables: a.tables,
                with_referencing: a.with_referencing,
                extra_als,
                timeout_ms: a.over.timeout_ms,
                require_coverage: a.require_coverage,
            };
            let progress = ProgressReporter::start(format!("fuzz {}", display_path(file)));
            let out = fuzz::fuzz(
                display_path(file),
                &full_sql,
                &opts,
                Some(&|m| progress.set(m)),
            );
            drop(progress);
            print(&out, a.json)
        }
        "discover" => {
            let [file] = p[..] else {
                return usage("expected FILE (a `.sql` schema)", help, a.json);
            };
            let raw_sql = match read(file) {
                Ok(t) => t,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let full_sql = if extra_sql.is_empty() {
                raw_sql
            } else {
                format!("{raw_sql}\n{extra_sql}")
            };
            let opts = discover::DiscoverOptions {
                tables: a.tables,
                with_referencing: a.with_referencing,
                extra_als,
                scope: a.over.scope.unwrap_or(3),
                budget: a.over.budget,
                timeout_ms: a.over.timeout_ms,
                show_rejected: a.show_rejected,
            };
            let progress = ProgressReporter::start(format!("discover {}", display_path(file)));
            let out = discover::discover(
                display_path(file),
                &full_sql,
                &opts,
                Some(&|m| progress.set(m)),
            );
            drop(progress);
            print(&out, a.json)
        }
        "audit" => {
            let [schema_file] = p[..] else {
                return usage(
                    "expected SCHEMA (a `.sql` file or migrations directory)",
                    help,
                    a.json,
                );
            };
            let Some(data_file) = a.data_file.as_deref() else {
                return usage("`audit` requires `--data DUMP.sql`", help, a.json);
            };
            let (raw_schema, data_sql) = match read_pair(schema_file, data_file) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let full_schema = if extra_sql.is_empty() {
                raw_schema
            } else {
                format!("{raw_schema}\n{extra_sql}")
            };
            let opts = audit::AuditOptions {
                tables: a.tables,
                with_referencing: a.with_referencing,
                extra_als,
            };
            let out = audit::audit(
                &sql_display_path(schema_file),
                &full_schema,
                display_path(data_file),
                &data_sql,
                &opts,
            );
            print(&out, a.json)
        }
        "ci" => {
            let manifest_file = match p[..] {
                [] => "elinvar.toml",
                [f] => f,
                _ => return usage("expected at most one MANIFEST file", help, a.json),
            };
            let manifest_text = match read(manifest_file) {
                Ok(t) => t,
                Err(m) => return usage(&m, help, a.json),
            };
            let format = if a.junit {
                Some(ci::CiFormat::Junit)
            } else if a.sarif {
                Some(ci::CiFormat::Sarif)
            } else if a.json {
                Some(ci::CiFormat::Json)
            } else {
                Some(ci::CiFormat::Markdown)
            };
            let opts = ci::CiOptions {
                timeout_ms: a.over.timeout_ms,
                format,
            };
            let progress = ProgressReporter::start(format!("ci {}", display_path(manifest_file)));
            let out = ci::run_manifest(
                display_path(manifest_file),
                &manifest_text,
                &opts,
                Some(&|m| progress.set(m)),
            );
            drop(progress);
            print(&out, a.json)
        }
        "diff" => {
            let (old_disp, new_disp, raw_old, raw_new, old_local, new_local) =
                if let Some(mig_file) = a.migration.as_deref() {
                    let [base_file] = p[..] else {
                        return usage(
                            "with `--migration`, expected BASE schema file or directory",
                            help,
                            a.json,
                        );
                    };
                    let (base_sql, mig_sql) = match read_pair(base_file, mig_file) {
                        Ok(pair) => pair,
                        Err(m) => return usage(&m, help, a.json),
                    };
                    let old_d = sql_display_path(base_file);
                    let new_d = format!(
                        "{}+{}.sql",
                        old_d.trim_end_matches(".sql"),
                        mig_file.trim_end_matches(".sql")
                    );
                    let new_sql = format!("{base_sql}\n-- migration: {mig_file}\n{mig_sql}\n");
                    (old_d, new_d, base_sql, new_sql, false, false)
                } else {
                    let [old_file, new_file] = p[..] else {
                        return usage("expected OLD and NEW model files", help, a.json);
                    };
                    let (ro, rn) = match read_pair(old_file, new_file) {
                        Ok(pair) => pair,
                        Err(m) => return usage(&m, help, a.json),
                    };
                    (
                        sql_display_path(old_file),
                        sql_display_path(new_file),
                        ro,
                        rn,
                        old_file != "-" && !is_sql_input(old_file),
                        new_file != "-" && !is_sql_input(new_file),
                    )
                };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let old_text = if old_disp.ends_with(".sql") && !extra_sql.is_empty() {
                format!("{raw_old}\n{extra_sql}")
            } else {
                raw_old
            };
            let new_text = if new_disp.ends_with(".sql") && !extra_sql.is_empty() {
                format!("{raw_new}\n{extra_sql}")
            } else {
                raw_new
            };
            let _progress = ProgressReporter::start(format!("diff {old_disp} {new_disp}"));
            let out = if let Some(fun_name) = a.diff_of.as_deref() {
                verbs::diff_of_with_extra(
                    &old_disp,
                    &old_text,
                    old_local,
                    &new_disp,
                    &new_text,
                    new_local,
                    fun_name,
                    extra_als.as_deref(),
                    a.over,
                )
            } else {
                verbs::diff_with_options_and_extra(
                    &old_disp,
                    &old_text,
                    old_local,
                    &new_disp,
                    &new_text,
                    new_local,
                    &a.tables,
                    a.with_referencing,
                    extra_als.as_deref(),
                    a.over,
                )
            };
            print(&out, a.json)
        }
        "import" => {
            let [file] = p[..] else {
                return usage("expected FILE (a SQL DDL schema)", help, a.json);
            };
            let raw_sql = match read(file) {
                Ok(t) => t,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let sql = if extra_sql.is_empty() {
                raw_sql
            } else {
                format!("{raw_sql}\n{extra_sql}")
            };
            let opts = elinvar_als::SqlImportOptions::new()
                .temporal(a.temporal)
                .from_empty(a.from_empty)
                .tables(a.tables)
                .with_referencing(a.with_referencing)
                .only_ruled(a.only_ruled);
            let (out, note) = verbs::import_sql_with_extra(
                display_path(file),
                &sql,
                &opts,
                a.strict,
                extra_als.as_deref(),
            );
            if let Some(msg) = note {
                eprintln!("{msg}");
            }
            print(&out, a.json)
        }
        "render" => {
            let [input] = p[..] else {
                return usage(
                    "expected FILE (a result JSON, `.als` model, or `.sql` schema)",
                    help,
                    a.json,
                );
            };
            let input_text = match read(input) {
                Ok(r) => r,
                Err(m) => return usage(&m, help, a.json),
            };
            let is_model = input.ends_with(".als")
                || input.ends_with(".sql")
                || (!input.ends_with(".json") && !input_text.trim_start().starts_with('{'));
            if is_model {
                print(
                    &verbs::render_model_text(
                        display_path(input),
                        &input_text,
                        a.format,
                        input != "-",
                    ),
                    a.json,
                )
            } else {
                let sample_values = match parse_sample_values(&a.values) {
                    Ok(v) => v,
                    Err(m) => return usage(&m, help, a.json),
                };
                let value = match parse_json(&input_text, input) {
                    Ok(v) => v,
                    Err(m) => return usage(&m, help, a.json),
                };
                print(
                    &verbs::render_with_values(&value, a.format, a.state, &sample_values),
                    a.json,
                )
            }
        }
        "eval" => {
            let [file, result, expr] = p[..] else {
                return usage("expected FILE, RESULT, and EXPR", help, a.json);
            };
            let (text, result_text) = match read_pair(file, result) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let (extra_sql, extra_als) = match load_sidecars(&a.with_files) {
                Ok(pair) => pair,
                Err(m) => return usage(&m, help, a.json),
            };
            let combined_text = if extra_sql.is_empty() {
                text
            } else {
                format!("{text}\n{extra_sql}\n")
            };
            let extra_als_opt = extra_als.as_deref();
            let value = match parse_json(&result_text, result) {
                Ok(v) => v,
                Err(m) => return usage(&m, help, a.json),
            };
            let out = verbs::eval_with_options(
                &sql_display_path(file),
                &combined_text,
                &value,
                expr,
                a.state.unwrap_or(0),
                extra_als_opt,
                &a.tables,
                a.with_referencing,
                file != "-" && !is_sql_input(file),
            );
            print(&out, a.json)
        }
        "explain" => {
            if p.len() > 1 {
                return usage(
                    "expected at most one subject (CODE, schema:result, or skill)",
                    help,
                    a.json,
                );
            }
            print(&verbs::explain(p.first().copied()), a.json)
        }
        "serve" => {
            if !a.mcp {
                return usage("`serve` needs a mode: `--mcp`", SERVE_HELP, a.json);
            }
            mcp::serve();
            ExitCode::SUCCESS
        }
        other => usage(format!("unknown verb `{other}`"), HELP, a.json),
    }
}