ingot-cli 0.5.1

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

use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use anyhow::{bail, Context, Result};
use clap::{Args, Parser, Subcommand, ValueEnum};
use ingot_compiler::{compile_path, compile_source, format_source, Compilation};
use ingot_diagnostics::{codes, ColorChoice as RenderColor};

mod authoring;
mod conform;
mod contained;
mod dev;
mod diff;
mod doctor;
mod image;
mod launch;
mod manifest;
mod memory;
mod package;
mod run;
mod runs;
mod sandbox;
mod studio;
mod tools;
mod trace;

use manifest::{resolve_target, Manifest, Target, MANIFEST_NAME};
use run::{EventFormat, ProviderChoice, RunConfig, TestConfig};
use sandbox::SandboxConfig;

pub(crate) const EXIT_OK: u8 = 0;
pub(crate) const EXIT_DIAGNOSTICS: u8 = 1;
pub(crate) const EXIT_FAILURE: u8 = 2;

#[derive(Parser, Debug)]
#[command(
    name = "ingot",
    version,
    about = "Compile Ingot agent sources to portable Agent IR",
    long_about = "Ingot compiles a statically typed agent language to a target-neutral \
                  Agent IR. Types, effects, policy and budgets are checked before an \
                  agent ever runs."
)]
struct Cli {
    #[command(subcommand)]
    command: Command,

    /// When to colour diagnostics.
    #[arg(long, value_enum, default_value_t = ColorMode::Auto, global = true)]
    color: ColorMode,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum ColorMode {
    Auto,
    Always,
    Never,
}

impl ColorMode {
    fn resolve(self) -> RenderColor {
        match self {
            ColorMode::Always => RenderColor::Always,
            ColorMode::Never => RenderColor::Never,
            ColorMode::Auto => {
                if std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none() {
                    RenderColor::Always
                } else {
                    RenderColor::Never
                }
            }
        }
    }
}

/// `Run` carries far more flags than the others, so the enum is as large as its
/// largest variant. Boxing it to save a few hundred bytes on one value that is
/// constructed once per process, and doing so through clap's derive, costs more
/// clarity than it buys.
#[allow(clippy::large_enum_variant)]
#[derive(Subcommand, Debug)]
enum Command {
    /// Create a new agent project.
    Init(InitArgs),
    /// Create or review a model-assisted authoring proposal.
    New(NewArgs),
    /// Parse, type-check and validate policy without producing output.
    Check(PathArgs),
    /// Rewrite sources in canonical form.
    Fmt(FmtArgs),
    /// Compile to Agent IR and write it to the output directory.
    Build(BuildArgs),
    /// Package the checked Agent IR as an OCI artifact with a lockfile.
    Package(PackageArgs),
    /// Print the Agent IR to standard output.
    Ir(IrArgs),
    /// Compile and execute the agent.
    Run(RunArgs),
    /// Replay recorded cassettes and check every one still runs.
    Test(TestArgs),
    /// Check everything a live or contained run needs without starting it.
    Doctor(DoctorArgs),
    /// Prepare the version-matched local image used by contained runs.
    Image(ImageArgs),
    /// Watch, check and build each source revision; optionally run good ones.
    Dev(DevArgs),
    /// Open the local surface: projects, run history and what this machine can
    /// reach, over the reports the other commands print.
    Studio(StudioArgs),
    /// Run the conformance suite against a backend — including this one.
    Conform(ConformArgs),
    /// Discover MCP schemas and preflight each tool the program declares.
    Tools(ToolsArgs),
    /// Show the boundary each tool server would run inside, derived from the
    /// agent's own policy.
    Sandbox(SandboxArgs),
    /// Explain a diagnostic code in full.
    Explain(ExplainArgs),
    /// The inside half of a supervised run. Not a way to run an agent.
    ///
    /// Hidden because invoking it directly does nothing useful: it reads its
    /// whole configuration from a supervisor on its standard streams, and
    /// without one it refuses. `ingot run --contained` is the command.
    #[command(hide = true)]
    Exec,
    /// The egress proxy a contained server's traffic leaves through.
    ///
    /// Hidden because it is a part rather than a command: a boundary starts one
    /// and points a container at it. Runnable on its own so the thing a sandbox
    /// is trusted to be right about can be watched directly.
    #[command(hide = true)]
    Egress(EgressArgs),
}

#[derive(Args, Debug)]
struct EgressArgs {
    /// A host the proxy will forward to. Repeatable. Matched exactly, because
    /// that is what a policy means by a host.
    #[arg(long = "allow", value_name = "HOST")]
    allow: Vec<String>,

    /// Address to listen on.
    #[arg(long, default_value = "127.0.0.1:0", value_name = "ADDR")]
    bind: String,
}

#[derive(Args, Debug)]
struct InitArgs {
    /// Directory to create. Use `.` to initialise the current directory.
    name: PathBuf,

    /// Maintained starting point for the new project.
    #[arg(long, value_enum, default_value_t = StarterTemplate::Brief)]
    template: StarterTemplate,
}

#[derive(Args, Debug)]
struct NewArgs {
    /// Workflow to author, e.g. "review pull requests for security issues".
    workflow: Vec<String>,

    /// Directory to create. Defaults to a name derived from the workflow.
    #[arg(long, value_name = "DIR", conflicts_with_all = ["previous", "project"])]
    out_dir: Option<PathBuf>,

    /// Maintained offline pattern to start from.
    ///
    /// Without `--provider` this is what `ingot new` writes, and no model call
    /// is made at all.
    #[arg(long, value_enum, conflicts_with_all = ["previous", "project", "provider"])]
    template: Option<StarterTemplate>,

    /// Propose a change to an existing project instead of creating one.
    ///
    /// Nothing is written: the proposal is printed as a diff of the entry
    /// source, and `--apply` is what writes it.
    #[arg(long, value_name = "DIR", conflicts_with = "previous")]
    project: Option<PathBuf>,

    /// Write the proposed source over the project's entry file.
    #[arg(long, requires = "project")]
    apply: bool,

    /// Existing `.ing` source to compare against when reviewing a candidate.
    #[arg(long, value_name = "PATH", requires = "candidate")]
    previous: Option<PathBuf>,

    /// Model-proposed `.ing` source to review before any repair loop applies it.
    #[arg(long, value_name = "PATH", requires = "previous")]
    candidate: Option<PathBuf>,

    /// Follow-up `.ing` source proposals to try after compiler diagnostics.
    #[arg(long = "repair-candidate", value_name = "PATH", requires = "candidate")]
    repair_candidates: Vec<PathBuf>,

    /// Maximum number of repair proposals the authoring loop may consume.
    #[arg(long, value_name = "N", default_value_t = 2)]
    max_repairs: usize,

    /// Where authored source comes from.
    ///
    /// Omitted, nothing reaches a model: `ingot new` writes a maintained
    /// offline template, and reviewing a candidate reads it from disk.
    #[arg(long, value_enum, conflicts_with = "previous")]
    provider: Option<ProviderChoice>,

    /// Authoring exchanges to replay, for `--provider replay`.
    #[arg(long, value_name = "FILE", requires = "provider")]
    cassette: Option<PathBuf>,

    /// Record the authoring exchanges, so the session can be reviewed or replayed.
    #[arg(long, value_name = "FILE", requires = "provider")]
    record: Option<PathBuf>,

    /// Override the model the provider would otherwise choose.
    #[arg(long, value_name = "MODEL", requires = "provider")]
    model: Option<String>,

    /// Reasoning effort: low, medium, high, xhigh or max.
    #[arg(long, value_name = "LEVEL", requires = "provider")]
    effort: Option<String>,

    /// Accept the policy grants the proposal asks for.
    ///
    /// Run once without it to see them. An acceptance given before the list was
    /// printed is not one, so this never applies to a proposal you have not read.
    #[arg(long)]
    accept_policy: bool,
}

#[derive(Args, Debug)]
struct ImageArgs {
    #[command(subcommand)]
    command: ImageCommand,
}

#[derive(Subcommand, Debug)]
enum ImageCommand {
    /// Build the reference image without downloading an unverified image.
    Build(ImageBuildArgs),
}

#[derive(Args, Debug)]
struct ImageBuildArgs {
    /// Ingot source checkout. Defaults to the nearest checkout.
    #[arg(value_name = "SOURCE")]
    source: Option<PathBuf>,
}

/// A small, maintained example of a language pattern rather than a vertical
/// product. Every template checks, builds and replays without a model key.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum StarterTemplate {
    /// One typed input, one model call, one markdown artifact.
    Brief,
    /// Two inputs and a checked-in document transformed for an audience.
    DocumentWorkflow,
}

#[derive(Args, Debug)]
struct PathArgs {
    /// A `.ing` file or a project directory. Defaults to the nearest project.
    path: Option<PathBuf>,
}

#[derive(Args, Debug)]
struct ToolsArgs {
    #[command(flatten)]
    target: PathArgs,

    /// Print one stable discovery and preflight report for editors and CI.
    #[arg(long)]
    json: bool,

    /// Show editable source and manifest proposals; never write them.
    #[arg(long)]
    propose: bool,
}

#[derive(Args, Debug)]
struct FmtArgs {
    #[command(flatten)]
    target: PathArgs,
    /// Report files that are not formatted instead of rewriting them.
    #[arg(long)]
    check: bool,
}

#[derive(Args, Debug)]
struct BuildArgs {
    #[command(flatten)]
    target: PathArgs,
    /// Override the output directory.
    #[arg(long, value_name = "DIR")]
    out_dir: Option<PathBuf>,

    /// What to compile to.
    ///
    /// `ir` writes the target-neutral Agent IR, which is what every backend
    /// consumes. `python` writes one self-contained Python 3 program per agent.
    #[arg(long = "target", value_enum, default_value_t = BuildTarget::Ir)]
    backend: BuildTarget,

    /// Build anyway when the target does not implement something the agent uses.
    ///
    /// The report says what, and the resulting program will not do it. Refused by
    /// default, because a silently dropped construct is worse than a failed build.
    #[arg(long)]
    allow_unimplemented: bool,

    /// Print the portability report as JSON instead of prose.
    ///
    /// `ingot build --target python --json | jq -e '.unimplemented == []'` is a
    /// deployment gate.
    #[arg(long)]
    json: bool,

    /// Build from an Agent IR document instead of from source.
    ///
    /// A backend consumes Agent IR, so it must be possible to hand one an IR
    /// document that no local source produced — an artifact somebody else
    /// built, pulled from a registry, or written by another compiler. Only
    /// meaningful with `--target python`: the `ir` target's input and output
    /// would be the same document.
    #[arg(long, value_name = "FILE")]
    from_ir: Option<PathBuf>,
}

#[derive(Args, Debug)]
struct PackageArgs {
    #[command(flatten)]
    target: PathArgs,

    /// Write the package here instead of `<out-dir>/package`.
    #[arg(long, value_name = "DIR")]
    out_dir: Option<PathBuf>,

    /// Carry this target's portability report in the package. Repeatable.
    ///
    /// Omitted, the package makes no portability claim at all, which is the
    /// honest default: a report is a statement about a target, and a package
    /// should not make one nobody asked for.
    #[arg(long = "report", value_enum, value_name = "TARGET")]
    reports: Vec<ReportTarget>,

    /// Compare the written package with the project instead of writing one.
    ///
    /// Reports every blob, source and agent that moved. Repairs nothing: what
    /// it is for is saying that the artifact and the working tree diverged.
    #[arg(long)]
    verify: bool,

    /// Print one stable JSON report for CI.
    #[arg(long)]
    json: bool,
}

/// A target whose portability report a package can carry.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum ReportTarget {
    /// The self-contained Python 3 backend.
    Python,
}

/// What `ingot build` compiles to.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum BuildTarget {
    /// The target-neutral Agent IR. The default, and what every backend reads.
    Ir,
    /// A self-contained Python 3 program per agent.
    Python,
}

#[derive(Args, Debug)]
struct IrArgs {
    #[command(flatten)]
    target: PathArgs,
    /// Which agent to print when the file declares several.
    #[arg(long, value_name = "NAME")]
    agent: Option<String>,
}

#[derive(Args, Debug)]
struct RunArgs {
    #[command(flatten)]
    target: PathArgs,

    /// An agent input, as `name=value`. Repeat for each one.
    ///
    /// The value is parsed as JSON when it is valid JSON, and taken as a plain
    /// string otherwise. Prefix with `@` to read it from a file:
    /// `--input document=@report.txt`.
    #[arg(long = "input", short = 'i', value_name = "NAME=VALUE")]
    inputs: Vec<String>,

    /// Where completions come from.
    ///
    /// `auto` sends each call to the vendor the artifact pinned with
    /// `model exact "<vendor>/<model>"`, using whichever API keys are exported.
    #[arg(long, value_enum, default_value_t = ProviderChoice::Auto)]
    provider: ProviderChoice,

    /// Cassette to replay, for `--provider replay`.
    #[arg(long, value_name = "FILE")]
    cassette: Option<PathBuf>,

    /// Record this run to a cassette so it can be replayed offline.
    #[arg(long, value_name = "FILE")]
    record: Option<PathBuf>,

    /// Keep no run record.
    ///
    /// A run otherwise writes its event stream to `<out-dir>/runs`, which is
    /// what `ingot studio` reads to show a project's history. Unrelated to
    /// `--record`, which writes a cassette of the model exchanges so a run can
    /// be replayed; this only decides whether what happened is written down.
    #[arg(long)]
    no_history: bool,

    /// Where the agent's persistent memory lives.
    ///
    /// Only used by an agent that declares a `memory { persistent { … } }`
    /// block. Defaults to `<out-dir>/memory/<agent>.json`.
    #[arg(long, value_name = "FILE", conflicts_with = "no_memory")]
    memory: Option<PathBuf>,

    /// Start from the declared initial values and discard what is written.
    #[arg(long, conflicts_with = "migrate_memory")]
    no_memory: bool,

    /// Accept a store written under a different declaration.
    ///
    /// Keeps every field whose name and type still match, drops the rest, and
    /// says what it dropped.
    #[arg(long)]
    migrate_memory: bool,

    /// Stop when the run reaches the checkpoint with this label.
    ///
    /// Only a checkpoint at the top level of a flow can be stopped at; one
    /// inside a branch or a loop is refused, naming why. The run writes a
    /// snapshot and reports where it went.
    #[arg(long, value_name = "LABEL", conflicts_with = "resume")]
    stop_at: Option<String>,

    /// Where a stopped run's snapshot goes.
    ///
    /// Defaults to `<out-dir>/snapshots/<agent>-<label>.json`.
    #[arg(long, value_name = "FILE", requires = "stop_at")]
    snapshot: Option<PathBuf>,

    /// Continue the run this snapshot describes.
    ///
    /// The inputs come from the snapshot, so `--input` is neither needed nor
    /// accepted. An artifact that has changed since the run stopped is refused.
    #[arg(long, value_name = "FILE")]
    resume: Option<PathBuf>,

    /// Override the model the artifact asks for.
    #[arg(long, value_name = "MODEL")]
    model: Option<String>,

    /// Reasoning effort: low, medium, high, xhigh or max.
    #[arg(long, value_name = "LEVEL")]
    effort: Option<String>,

    /// Which agent to run when the file declares several. Defaults to the last.
    #[arg(long, value_name = "NAME")]
    agent: Option<String>,

    /// Write artifacts here instead of to standard output.
    #[arg(long, value_name = "DIR")]
    out_dir: Option<PathBuf>,

    /// How progress is reported on stderr.
    #[arg(long, value_enum, default_value_t = EventFormat::Text)]
    events: EventFormat,

    /// Approve every gate without asking. The artifact asked for a human, so
    /// this is deliberately explicit.
    #[arg(long)]
    yes: bool,

    /// Start no MCP server, whatever the manifest configures. Useful for
    /// checking that an agent fails the way it should when a tool is absent.
    #[arg(long)]
    no_tools: bool,

    /// Run each tool server inside a boundary derived from the agent's policy.
    ///
    /// Needs a container runtime and an `image` on each server. `ingot sandbox`
    /// shows what the boundary would be.
    #[arg(long, conflicts_with_all = ["contained", "supervised"])]
    sandbox: bool,

    /// Run the agent itself inside a boundary derived from its policy.
    ///
    /// Everything is inside: the interpreter, the tool servers, and nothing
    /// else. The model call and the approval gate cross out through a
    /// supervisor, so `network deny` holds and the API key never enters the box.
    /// Needs a container runtime. Uses the version-matched reference image
    /// unless `[run] image` or `--image` deliberately selects another.
    #[arg(long)]
    contained: bool,

    /// The image a contained run happens inside.
    #[arg(long, value_name = "IMAGE")]
    image: Option<String>,

    /// Run over the supervisor channel with no boundary at all.
    ///
    /// For proving the channel works where there is no container runtime. It
    /// enforces nothing and says so on every run.
    #[arg(long, hide = true, conflicts_with = "contained")]
    supervised: bool,

    /// Proceed even where the boundary cannot honour a rule the policy states.
    ///
    /// Applies to `--sandbox` and `--contained`. Refused on its own rather than
    /// ignored: a flag that looks like it loosened something and did nothing is
    /// worse than an error.
    #[arg(long)]
    sandbox_allow_unenforced: bool,

    /// Run even where nothing will keep a reach the artifact declared.
    ///
    /// `!network("arxiv.org")` on a tool says that tool must be bounded to that
    /// host. No arrangement bounds egress yet, so a program that states one
    /// stops rather than running as if it had been kept. This proceeds anyway,
    /// and says which declarations are advisory while it does.
    #[arg(long)]
    allow_unenforced_scopes: bool,

    /// The root the artifact's policy paths are relative to.
    #[arg(long, value_name = "DIR")]
    workspace: Option<PathBuf>,

    /// Stop after this many steps, whatever the artifact's own budget allows.
    #[arg(long, default_value_t = 1000, value_name = "N")]
    max_steps: u32,

    /// Seconds a contained run may go without a word from inside.
    ///
    /// Overrides `[run] timeout-seconds`. Absent, the ceiling is derived from
    /// the tool timeout the guest already honours. `0` waits indefinitely, which
    /// is a choice rather than a default.
    #[arg(long, value_name = "SECONDS")]
    timeout: Option<u64>,
}

#[derive(Args, Debug)]
struct TestArgs {
    #[command(flatten)]
    target: PathArgs,

    /// Directory of cassettes to replay.
    #[arg(long, value_name = "DIR", default_value = run::CASSETTE_DIR)]
    cassettes: PathBuf,

    /// Only run cassettes whose name contains this substring.
    #[arg(value_name = "FILTER")]
    filter: Option<String>,
}

#[derive(Args, Debug)]
struct DoctorArgs {
    #[command(flatten)]
    target: PathArgs,

    /// Print one stable JSON report for editors and CI.
    #[arg(long)]
    json: bool,
}

#[derive(Args, Debug)]
struct DevArgs {
    #[command(flatten)]
    target: PathArgs,

    /// Run every successfully built revision. Off by default: saving a prompt
    /// must not silently make a model call.
    #[arg(long)]
    run: bool,

    /// Run even where nothing will keep a reach the artifact declared. The same
    /// flag `ingot run` takes, so the inner loop does not have a looser rule.
    #[arg(long)]
    allow_unenforced_scopes: bool,

    /// An example input as `name=value`; repeat for each input.
    #[arg(
        long = "input",
        short = 'i',
        value_name = "NAME=VALUE",
        requires = "run"
    )]
    inputs: Vec<String>,

    /// Where opt-in runs get completions.
    #[arg(long, value_enum, default_value_t = ProviderChoice::Auto)]
    provider: ProviderChoice,

    /// Cassette used when `--provider replay` is selected.
    #[arg(long, value_name = "FILE", requires = "run")]
    cassette: Option<PathBuf>,

    /// Agent to run when the source declares several.
    #[arg(long, value_name = "NAME", requires = "run")]
    agent: Option<String>,

    /// Progress detail for opt-in runs.
    #[arg(long, value_enum, default_value_t = EventFormat::Quiet)]
    events: EventFormat,

    /// Approve every gate during opt-in runs without prompting.
    #[arg(long, requires = "run")]
    yes: bool,

    /// Stop an opt-in run after this many steps.
    #[arg(long, default_value_t = 1000, value_name = "N")]
    max_steps: u32,
}

#[derive(Args, Debug)]
struct SandboxArgs {
    #[command(flatten)]
    target: PathArgs,

    /// The root the artifact's policy paths are relative to.
    ///
    /// An artifact says `src`; this says where `src` lives. Defaults to the
    /// project directory.
    #[arg(long, value_name = "DIR")]
    workspace: Option<PathBuf>,

    /// Print the plans as JSON, for piping.
    #[arg(long)]
    json: bool,
}

#[derive(Args, Debug)]
struct ExplainArgs {
    /// A diagnostic code such as `ING4001`.
    code: String,
}

#[derive(Args, Debug)]
struct StudioArgs {
    /// Address to listen on. Must be loopback: the studio shows one person's
    /// project paths, variable names and run history, and publishing that to a
    /// network is refused rather than warned about.
    #[arg(long, value_name = "ADDR")]
    bind: Option<String>,
}

#[derive(Args, Debug)]
struct ConformArgs {
    /// The command that runs one case. The request file is appended to it, so
    /// `--backend "python adapter.py"` runs `python adapter.py <request>`.
    ///
    /// Defaults to this binary's own adapter, which is how the reference
    /// interpreter reaches the suite — through the same door a third party
    /// uses, so nothing about it is privileged.
    #[arg(long, value_name = "COMMAND")]
    backend: Option<String>,

    /// Run only the case with this name.
    #[arg(long, value_name = "NAME")]
    case: Option<String>,

    /// Where the suite lives.
    ///
    /// Defaults to the copy built into this binary. A checkout is used instead
    /// when the working directory is inside one, so editing a case in the
    /// repository changes what runs.
    #[arg(long, value_name = "DIR")]
    suite: Option<PathBuf>,

    /// Write the built-in suite here and run nothing.
    ///
    /// For reading the case your backend just failed, and for editing one
    /// before pointing `--suite` back at it.
    #[arg(long, value_name = "DIR")]
    export: Option<PathBuf>,

    /// Print what the suite requires, and run nothing.
    #[arg(long)]
    list: bool,

    /// Run one request file as the reference backend. This *is* the adapter,
    /// and it is what `--backend` defaults to invoking.
    #[arg(long, value_name = "FILE")]
    adapter: Option<PathBuf>,

    /// Report as JSON.
    #[arg(long)]
    json: bool,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let color = cli.color.resolve();

    let result = match &cli.command {
        Command::Init(args) => run_init(args),
        Command::New(args) => run_new(args, color),
        Command::Check(args) => run_check(args, color),
        Command::Fmt(args) => run_fmt(args, color),
        Command::Build(args) => run_build(args, color),
        Command::Package(args) => run_package(args, color),
        Command::Ir(args) => run_ir(args, color),
        Command::Run(args) => run_run(args, color),
        Command::Test(args) => run_test(args, color),
        Command::Doctor(args) => run_doctor(args, color),
        Command::Image(args) => run_image(args),
        Command::Dev(args) => run_dev(args, color),
        Command::Studio(args) => studio::serve(&studio::StudioConfig {
            bind: args.bind.clone(),
        }),
        Command::Conform(args) => run_conform(args),
        Command::Tools(args) => run_tools(args, color),
        Command::Sandbox(args) => run_sandbox(args, color),
        Command::Explain(args) => run_explain(args),
        Command::Egress(args) => run_egress(args),
        Command::Exec => contained::exec(),
    };

    match result {
        Ok(code) => ExitCode::from(code),
        Err(error) => {
            eprintln!("error: {error:#}");
            ExitCode::from(EXIT_FAILURE)
        }
    }
}

// --- init ------------------------------------------------------------------

fn run_init(args: &InitArgs) -> Result<u8> {
    let dir = &args.name;
    let name = project_name_for_dir(dir);
    create_starter_project(dir, &name, args.template, args.template.description())?;

    println!(
        "Created agent project `{name}` from template `{}` in {}",
        args.template.as_str(),
        dir.display()
    );
    println!();
    // Ordered so the first thing somebody does produces a result rather than a
    // green tick, and so nothing here asks for an API key. The recorded fixture
    // ships with the project, which is what makes that possible.
    println!("Next steps — none of these need an API key:");
    if dir != Path::new(".") {
        println!("  cd {}", dir.display());
    }
    println!("  ingot check     # types, effects, policy, budgets");
    println!("  ingot test      # replay the recorded fixture");
    println!("  ingot studio    # the whole project, in one page");
    println!();
    // On its own line and without a comment: it is the longest of them, and
    // it is the one that produces something to look at.
    println!("Then run it, and read what it made:");
    println!("  {}", args.template.replay_command());
    Ok(EXIT_OK)
}

/// The cassette agent name for a recorded authoring session.
///
/// Not an agent in the language — authoring happens before there is one — but a
/// recorded session sits next to run cassettes and has to be identifiable.
const AUTHORING_AGENT: &str = "ingot.authoring";

fn run_new(args: &NewArgs, color: RenderColor) -> Result<u8> {
    if args.previous.is_some() {
        return review_candidate_files(args, color);
    }
    if let Some(project) = &args.project {
        return propose_into_project(args, project, color);
    }
    if !args.repair_candidates.is_empty() {
        bail!("--repair-candidate requires --previous and --candidate");
    }
    create_from_workflow(args, color)
}

/// The workflow as one string, refused when it is empty or carries a secret.
///
/// The scan happens before the words reach a prompt, a manifest or a log: a key
/// pasted into a workflow description is the likeliest way one would enter this
/// command, and the only useful moment to stop it is the first one.
fn workflow_words(args: &NewArgs) -> Result<String> {
    let workflow = args.workflow.join(" ");
    if workflow.trim().is_empty() {
        bail!(
            "describe the workflow to author, or pass --previous and --candidate to review a \
             proposal"
        );
    }
    if let Some(finding) = ingot_package::secrets::scan(&workflow) {
        bail!(
            "the workflow description contains {} and was not sent anywhere\n  \
             remove it and describe the credential by name instead; a value in a workflow \
             would reach the prompt, the manifest and this terminal's history",
            finding.shape
        );
    }
    Ok(workflow)
}

// --- new: reviewing candidate files ----------------------------------------

fn review_candidate_files(args: &NewArgs, color: RenderColor) -> Result<u8> {
    let previous = args.previous.as_ref().expect("checked by the caller");
    let candidate = args
        .candidate
        .as_ref()
        .expect("clap requires --candidate with --previous");

    let previous_source = std::fs::read_to_string(previous)
        .with_context(|| format!("reading {}", previous.display()))?;
    let candidate_source = std::fs::read_to_string(candidate)
        .with_context(|| format!("reading {}", candidate.display()))?;
    let repair_sources = args
        .repair_candidates
        .iter()
        .map(|path| {
            std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))
        })
        .collect::<Result<Vec<_>>>()?;

    let mut candidates = authoring::FixedCandidates::new(&candidate_source, &repair_sources);
    // Two loose files are not a project, so there is no routing table to hold a
    // tool declaration against and none is invented.
    let repair = authoring::author(
        &previous_source,
        &mut candidates,
        &authoring::ToolContext::Unchecked,
        limits(args),
    )?;

    if let Some(code) = report_authoring(&repair, 0, color) {
        return Ok(code);
    }

    let source = repair
        .accepted_source()
        .expect("a compiled loop has source");
    println!("candidate source contains no new policy proposal");
    println!(
        "compiler-verified authoring completed after {} attempt(s)",
        repair.attempts().len()
    );
    print_authoring_attempts(&repair);
    print_proposed_diff(&previous.display().to_string(), &previous_source, source);
    Ok(EXIT_OK)
}

// --- new: proposing into an existing project -------------------------------

fn propose_into_project(args: &NewArgs, project: &Path, color: RenderColor) -> Result<u8> {
    if args.provider.is_none() {
        bail!(
            "--project needs --provider: a maintained template can start a project, but only a \
             model can propose a change to one that already exists\n  \
             use `--provider auto` with a key exported, or `--provider replay --cassette <FILE>`"
        );
    }
    let workflow = workflow_words(args)?;
    let target = resolve_target(Some(project))?;
    let previous_source = std::fs::read_to_string(&target.entry)
        .with_context(|| format!("reading {}", target.entry.display()))?;

    // Real schemas or none: a proposal written against invented tools compiles
    // and cannot run, and the failure would arrive at run time in front of
    // whoever trusted the generator.
    let mcp = target.mcp();
    let tools = if mcp.is_empty() {
        authoring::ToolContext::NoServers
    } else {
        authoring::ToolContext::Routed(tools::routed(&tools::ToolsConfig {
            root: target.root.clone(),
            mcp,
        })?)
    };

    let package = target
        .manifest
        .as_ref()
        .and_then(|manifest| package_name(&manifest.project.name));
    let session = author_with_model(args, &workflow, &previous_source, package, &tools)?;

    if let Some(code) = report_authoring(&session.repair, session.calls, color) {
        return Ok(code);
    }
    let source = session
        .repair
        .accepted_source()
        .expect("a compiled loop has source");

    let entry = target.entry.display().to_string();
    if !print_proposed_diff(&entry, &previous_source, source) {
        println!("the proposal makes no change to {entry}");
        return Ok(EXIT_OK);
    }

    if !args.apply {
        println!();
        println!("nothing was written; re-run with --apply to write this to {entry}");
        return Ok(EXIT_OK);
    }

    std::fs::write(&target.entry, source).with_context(|| format!("writing {entry}"))?;
    println!();
    println!("wrote {entry}");
    println!("check the result and re-record any cassette the change invalidates:");
    println!("  ingot check");
    println!("  ingot test");
    Ok(EXIT_OK)
}

// --- new: creating a project ------------------------------------------------

fn create_from_workflow(args: &NewArgs, color: RenderColor) -> Result<u8> {
    let workflow = workflow_words(args)?;
    let dir = args
        .out_dir
        .clone()
        .unwrap_or_else(|| PathBuf::from(project_slug(&workflow)));
    let name = project_name_for_dir(&dir);
    let description = format!("Authored from workflow: {workflow}");

    let Some(_) = args.provider else {
        let template = args
            .template
            .unwrap_or_else(|| StarterTemplate::for_workflow(&workflow));
        create_starter_project(&dir, &name, template, &description)?;

        println!(
            "Created compiler-verified agent project `{name}` from workflow in {}",
            dir.display()
        );
        println!("Workflow: {workflow}");
        println!("Template: {}", template.as_str());
        println!();
        println!("Next steps:");
        if dir != Path::new(".") {
            println!("  cd {}", dir.display());
        }
        println!("  ingot check");
        println!("  ingot build");
        println!("  ingot test");
        return Ok(EXIT_OK);
    };

    // Settled before the model is asked for anything: a run that would refuse to
    // write its result should not spend a call finding that out.
    if dir.join(MANIFEST_NAME).exists() {
        bail!("{} already contains an {MANIFEST_NAME}", dir.display());
    }

    // A project that does not exist yet configures no tool server, so an
    // authored `tool` declaration cannot be routed by anything.
    let tools = authoring::ToolContext::NoServers;
    let session = author_with_model(args, &workflow, "", package_name(&name), &tools)?;

    if let Some(code) = report_authoring(&session.repair, session.calls, color) {
        return Ok(code);
    }
    let source = session
        .repair
        .accepted_source()
        .expect("a compiled loop has source");

    let compilation = compile_source("main.ing", source);
    let inputs = compilation
        .agents
        .first()
        .map(|agent| agent.inputs.clone())
        .unwrap_or_default();

    let mut manifest = Manifest::new(&name);
    manifest.project.description = Some(description);
    std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?;
    write_new(&dir.join(MANIFEST_NAME), &manifest.to_toml())?;
    write_new(&dir.join("main.ing"), source)?;
    write_new(&dir.join(".gitignore"), "/target\n")?;
    for (input, ty) in &inputs {
        if let Some(path) = example_input_path(input, ty) {
            write_new(&dir.join(&path), &example_input(input, &workflow))?;
        }
    }
    write_new(
        &dir.join("README.md"),
        &authored_readme(&name, &workflow, &inputs),
    )?;

    println!(
        "Created compiler-verified agent project `{name}` from workflow in {}",
        dir.display()
    );
    println!("Workflow: {workflow}");
    println!("Authored by: {}", provider_label(args));
    println!();
    println!("Next steps:");
    if dir != Path::new(".") {
        println!("  cd {}", dir.display());
    }
    println!("  ingot check");
    println!("  ingot build");
    println!("  ingot test");
    println!();
    println!(
        "`ingot test` has no cassette to replay yet, and one is not invented: a recorded \
         answer nothing produced would be a test that proves nothing."
    );
    println!("Record the offline test once, against a configured provider:");
    println!("  {}", record_command(&inputs));
    Ok(EXIT_OK)
}

/// Run the egress proxy until interrupted.
///
/// Every decision is printed, allowed and refused alike. A filter that only
/// reported what it stopped would leave an operator unable to tell "nothing was
/// blocked" from "nothing was tried".
fn run_egress(args: &EgressArgs) -> Result<u8> {
    let bind: std::net::SocketAddr = args
        .bind
        .parse()
        .with_context(|| format!("`--bind {}` is not an address:port", args.bind))?;

    let allow = ingot_egress::Allowlist::new(&args.allow);
    if allow.is_empty() {
        eprintln!("egress: no hosts allowed; every request will be refused");
    } else {
        eprintln!("egress: allowing {}", allow.hosts().join(", "));
    }

    let proxy = ingot_egress::Proxy::start(bind, allow, |decision| eprintln!("egress: {decision}"))
        .context("starting the egress proxy")?;
    println!("{}", proxy.address());

    // Held until the process is stopped; there is nothing else to wait for.
    loop {
        std::thread::park();
    }
}

fn provider_label(args: &NewArgs) -> &'static str {
    match args.provider {
        Some(ProviderChoice::Replay) => "a replayed authoring cassette",
        Some(_) => "a model, verified by the compiler",
        None => "a maintained template",
    }
}

// --- new: the shared authoring loop ----------------------------------------

struct AuthoringSession {
    repair: authoring::RepairLoop,
    calls: usize,
}

fn limits(args: &NewArgs) -> authoring::Limits {
    authoring::Limits {
        max_repairs: args.max_repairs,
        accept_policy: args.accept_policy,
    }
}

/// Ask a provider for source and run it through the same bounded loop the
/// file-backed review uses.
fn author_with_model(
    args: &NewArgs,
    workflow: &str,
    previous_source: &str,
    package: Option<String>,
    tools: &authoring::ToolContext,
) -> Result<AuthoringSession> {
    let selection = run::ProviderSelection {
        // Authoring never resumes a run.
        replay_from: 0,
        choice: args.provider.expect("checked by the caller"),
        cassette: args.cassette.clone(),
        model: args.model.clone(),
        effort: args.effort.clone(),
        // Authoring reads no manifest-declared provider: it may be creating the
        // manifest, and a proposal into an existing project must not depend on
        // one having been declared.
        models: ingot_runtime::ModelConfig::default(),
        strict_replay: false,
    };
    let mut provider = run::Provider::new(
        run::build_model_provider(&selection)?,
        args.record.is_some(),
        AUTHORING_AGENT,
    );

    let (repair, calls) = {
        let request = authoring::AuthoringRequest {
            workflow: workflow.to_string(),
            previous_source: previous_source.to_string(),
            package,
        };
        let mut model = authoring::ModelAuthor::new(provider.as_mut(), request, tools);
        let repair = authoring::author(previous_source, &mut model, tools, limits(args));
        (repair, model.calls())
    };

    // The recording is saved whatever the loop decided. A session that ended in
    // a refusal is the one most worth being able to read again.
    if let Some(path) = &args.record {
        if let Some(cassette) = provider.finish_recording() {
            cassette.save(path).map_err(anyhow::Error::msg)?;
            eprintln!("recorded the authoring session to {}", path.display());
        }
    }

    Ok(AuthoringSession {
        repair: repair?,
        calls,
    })
}

/// Print what the loop did. `Some(code)` when the outcome stops the command.
fn report_authoring(
    repair: &authoring::RepairLoop,
    calls: usize,
    color: RenderColor,
) -> Option<u8> {
    if calls > 0 {
        let usage = repair.usage();
        eprintln!(
            "authoring made {calls} model call(s), using {} input and {} output token(s)",
            usage.input_tokens, usage.output_tokens
        );
    }
    for proposal in repair.accepted_proposals() {
        println!(
            "accepted policy grant: agent {}: {} {}",
            proposal.agent, proposal.subject, proposal.action
        );
    }

    match repair.outcome() {
        authoring::RepairOutcome::Compiled { .. } => None,
        authoring::RepairOutcome::PolicyProposals { proposals } => {
            println!("candidate source requests policy changes");
            println!("these are not part of automatic compiler repair:");
            for proposal in proposals {
                println!(
                    "  agent {}: {} {}",
                    proposal.agent, proposal.subject, proposal.action
                );
            }
            println!();
            println!("review and accept policy changes explicitly before continuing");
            println!("re-run with --accept-policy to accept exactly these grants");
            Some(EXIT_DIAGNOSTICS)
        }
        authoring::RepairOutcome::RetryCeilingReached => {
            print_authoring_attempts(repair);
            println!(
                "compiler repair reached retry ceiling after {} attempt(s)",
                repair.attempts().len()
            );
            if let Some(last) = repair.attempts().last() {
                println!("last source:");
                println!("{}", last.source);
                let compilation = compile_source("candidate.ing", &last.source);
                eprint!("{}", compilation.render_diagnostics(color));
            }
            Some(EXIT_DIAGNOSTICS)
        }
        authoring::RepairOutcome::CredentialRefused { finding } => {
            println!(
                "the proposed source contains {} on line {}",
                finding.shape, finding.line
            );
            println!("nothing was written, and the source was not sent back to the model");
            println!(
                "a credential belongs in the environment, named by `pass-env` in {MANIFEST_NAME}, \
                 never in source"
            );
            Some(EXIT_DIAGNOSTICS)
        }
    }
}

fn print_authoring_attempts(repair: &authoring::RepairLoop) {
    for attempt in repair.attempts() {
        if attempt.has_errors() {
            println!("attempt {} failed compiler verification", attempt.number);
            for diagnostic in &attempt.diagnostics {
                println!("  {}: {}", diagnostic.code, diagnostic.message);
            }
        } else {
            println!("attempt {} passed compiler verification", attempt.number);
        }
    }
}

/// Show the change rather than the result. Returns whether there was one.
fn print_proposed_diff(label: &str, previous: &str, proposed: &str) -> bool {
    match diff::unified(label, previous, "proposed", proposed, diff::CONTEXT) {
        Some(rendered) => {
            print!("{rendered}");
            true
        }
        None => false,
    }
}

fn run_image(args: &ImageArgs) -> Result<u8> {
    match &args.command {
        ImageCommand::Build(args) => image::build(args.source.as_deref()),
    }
}

fn create_starter_project(
    dir: &Path,
    name: &str,
    template: StarterTemplate,
    description: &str,
) -> Result<()> {
    if dir.join(MANIFEST_NAME).exists() {
        bail!("{} already contains an {MANIFEST_NAME}", dir.display());
    }
    std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;

    let mut manifest = Manifest::new(name);
    manifest.project.description = Some(description.to_string());
    write_new(&dir.join(MANIFEST_NAME), &manifest.to_toml())?;
    write_new(&dir.join("main.ing"), &starter_source(name, template))?;
    write_new(&dir.join(".gitignore"), "/target\n")?;
    write_new(&dir.join("README.md"), &starter_readme(name, template))?;
    write_new(
        &dir.join("tests/cassettes/example.json"),
        &starter_cassette(name, template).to_canonical_json(),
    )?;
    if let Some((path, contents)) = template.example_file() {
        write_new(&dir.join(path), contents)?;
    }
    Ok(())
}

fn write_new(path: &Path, contents: &str) -> Result<()> {
    if path.exists() {
        bail!("{} already exists", path.display());
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(path, contents).with_context(|| format!("writing {}", path.display()))
}

const EXAMPLE_DOCUMENT: &str = "Ingot compiles a typed agent language to portable Agent IR. \
The same checked artifact can run through independent backends. Policies and \
budgets travel with the artifact so each backend can enforce them.\n";

impl StarterTemplate {
    fn as_str(self) -> &'static str {
        match self {
            StarterTemplate::Brief => "brief",
            StarterTemplate::DocumentWorkflow => "document-workflow",
        }
    }

    /// The offline run, as `ingot init` prints it.
    ///
    /// The same command the generated README carries, and a test asserts both
    /// forms run: printed instructions that do not work are worse than none.
    fn replay_command(self) -> &'static str {
        match self {
            StarterTemplate::Brief => {
                "ingot run --provider replay --input topic=\"compiler design\""
            }
            StarterTemplate::DocumentWorkflow => {
                "ingot run --provider replay --input document=@examples/document.txt --input audience=\"project leads\""
            }
        }
    }

    fn description(self) -> &'static str {
        match self {
            StarterTemplate::Brief => "A small typed agent that turns a topic into a brief.",
            StarterTemplate::DocumentWorkflow => {
                "A document transformation workflow with two typed inputs."
            }
        }
    }

    fn agent(self) -> &'static str {
        match self {
            StarterTemplate::Brief => "Brief",
            StarterTemplate::DocumentWorkflow => "DocumentWorkflow",
        }
    }

    fn example_file(self) -> Option<(&'static str, &'static str)> {
        match self {
            StarterTemplate::Brief => None,
            StarterTemplate::DocumentWorkflow => Some(("examples/document.txt", EXAMPLE_DOCUMENT)),
        }
    }

    fn for_workflow(workflow: &str) -> StarterTemplate {
        let lowered = workflow.to_ascii_lowercase();
        if [
            "document",
            "documents",
            "doc",
            "docs",
            "file",
            "files",
            "audience",
            "summarise",
            "summarize",
        ]
        .iter()
        .any(|needle| lowered.contains(needle))
        {
            StarterTemplate::DocumentWorkflow
        } else {
            StarterTemplate::Brief
        }
    }
}

pub(crate) fn project_name_for_dir(dir: &Path) -> String {
    dir.file_name()
        .map(|name| name.to_string_lossy().to_string())
        .filter(|name| name != ".")
        .or_else(|| {
            std::env::current_dir()
                .ok()
                .and_then(|dir| dir.file_name().map(|n| n.to_string_lossy().to_string()))
        })
        .unwrap_or_else(|| "agent".to_string())
}

fn project_slug(workflow: &str) -> String {
    let words: Vec<String> = workflow
        .split(|ch: char| !ch.is_ascii_alphanumeric())
        .filter(|word| !word.is_empty())
        .take(5)
        .map(|word| word.to_ascii_lowercase())
        .collect();
    if words.is_empty() {
        "authored-agent".to_string()
    } else {
        words.join("-")
    }
}

/// A package identifier derived from a project name, if one can be.
///
/// Returns `None` when the name cannot become a valid identifier — it is empty,
/// starts with a digit, or collides with a reserved word. `package` is optional
/// in the language, so omitting it beats generating source that will not
/// compile. `ingot init agent` used to produce `package agent`, which is a
/// syntax error.
fn package_name(name: &str) -> Option<String> {
    let sanitised: String = name
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() {
                ch.to_ascii_lowercase()
            } else {
                '_'
            }
        })
        .collect();
    let sanitised = sanitised.trim_matches('_').to_string();

    if sanitised.is_empty() {
        return None;
    }
    if sanitised.starts_with(|ch: char| ch.is_ascii_digit()) {
        return None;
    }
    if ingot_lexer::KEYWORDS.contains(&sanitised.as_str()) {
        return None;
    }
    Some(sanitised)
}

fn starter_source(name: &str, template: StarterTemplate) -> String {
    let package = match package_name(name) {
        Some(package) => format!(
            "package {package}
"
        ),
        None => String::new(),
    };
    match template {
        StarterTemplate::Brief => format!(
            r#"language 0.1
{package}
/// Summarises a topic into a short markdown brief.
agent Brief(topic: string) -> brief<markdown> {{
  model requires {{
    structured_output
  }}

  budget {{
    steps <= 4
    tokens <= 20000
  }}

  policy {{
    network deny
  }}

  flow {{
    emit brief = ask<markdown>(
      "Write a short, factual brief about ${{topic}}. Use headings and bullet points."
    )
  }}
}}
"#
        ),
        StarterTemplate::DocumentWorkflow => format!(
            r#"language 0.1
{package}
/// Rewrites a document for a named audience without changing its facts.
agent DocumentWorkflow(document: text, audience: string) -> summary<markdown> {{
  model requires {{
    structured_output
  }}

  budget {{
    steps <= 4
    tokens <= 20000
  }}

  policy {{
    network deny
  }}

  flow {{
    emit summary = ask<markdown>(
      "Summarise the following document for ${{audience}}. Preserve the important facts.\n\n${{document}}"
    )
  }}
}}
"#
        ),
    }
}

fn starter_readme(name: &str, template: StarterTemplate) -> String {
    // No `--cassette`: a project with one recording replays it by being the
    // only one. The long form still works, and `ingot run` asks the moment
    // there are two. The same string `ingot init` prints, from one place.
    let replay = template.replay_command();
    let dev_replay = replay.replacen("ingot run", "ingot dev --run", 1);
    format!(
        r#"# {name}

An agent written in Ingot from the `{}` template. `main.ing` is the source of
truth: the template, compiler, test and runtime do not hide another workflow
representation behind it.

## First run

These commands work without a model API key:

```bash
ingot check
ingot build
ingot test
{replay}
```

`ingot test` replays the reviewed fixture in `tests/cassettes/`. The final
command runs that same fixture and prints the artifact. Change `main.ing`, then
record a new cassette against a configured provider before accepting its diff.

## Develop

Keep `check` and the canonical IR build current while editing:

```bash
ingot dev
```

Running is opt-in, so a save does not silently call a model. This command runs
each successful revision against the checked-in cassette and example inputs:

```bash
{dev_replay}
```

`ingot build` writes `target/ingot/{}.ir.json`. Agent IR is the canonical,
target-neutral artifact consumed by every backend.
"#,
        template.as_str(),
        template.agent()
    )
}

// --- files for a model-authored project ------------------------------------

/// Where an example value for this input belongs, when a file is the natural
/// way to pass one.
///
/// Prose inputs get a file because `--input document=@examples/document.txt` is
/// how anyone would really pass a document. A scalar goes on the command line,
/// where it is easier to change than in a file nobody remembers exists.
fn example_input_path(name: &str, ty: &str) -> Option<PathBuf> {
    matches!(ty, "text" | "markdown").then(|| PathBuf::from(format!("examples/{name}.txt")))
}

fn example_input(name: &str, workflow: &str) -> String {
    format!(
        "Example `{name}` for: {workflow}\n\n\
         Replace this with real content. It exists so the first run has something \
         to read, and so the recorded cassette is made against a value you chose.\n"
    )
}

/// The `--input` flag for one declared input, with a value of the right shape.
fn input_flag(name: &str, ty: &str) -> String {
    let value = match ty {
        "text" | "markdown" => format!("@examples/{name}.txt"),
        "string" => "\"...\"".to_string(),
        "int" => "0".to_string(),
        "float" => "0.0".to_string(),
        "bool" => "true".to_string(),
        ty if ty.ends_with("[]") => "[]".to_string(),
        _ => "{}".to_string(),
    };
    format!("--input {name}={value}")
}

fn input_flags(inputs: &std::collections::BTreeMap<String, String>) -> String {
    inputs
        .iter()
        .map(|(name, ty)| input_flag(name, ty))
        .collect::<Vec<_>>()
        .join(" ")
}

/// The one command that turns an authored project into a project with an
/// offline test.
fn record_command(inputs: &std::collections::BTreeMap<String, String>) -> String {
    let flags = input_flags(inputs);
    let separator = if flags.is_empty() { "" } else { " " };
    format!("ingot run --record tests/cassettes/example.json{separator}{flags}")
}

fn authored_readme(
    name: &str,
    workflow: &str,
    inputs: &std::collections::BTreeMap<String, String>,
) -> String {
    let record = record_command(inputs);
    let replay = {
        let flags = input_flags(inputs);
        let separator = if flags.is_empty() { "" } else { " " };
        format!(
            "ingot run --provider replay --cassette tests/cassettes/example.json{separator}{flags}"
        )
    };
    format!(
        r#"# {name}

An agent written in Ingot, authored from this workflow:

> {workflow}

`main.ing` is the source of truth. The authoring model wrote it once and has no
further part in this project: the compiler, tests and runtime never call it, and
every command below works without one.

## First run

These commands need no model API key:

```bash
ingot check
ingot build
```

`ingot build` writes the canonical, target-neutral Agent IR under
`target/ingot/`.

## The offline test

There is no cassette yet, and one was not invented for you: a recorded answer
that no model produced would be a test that proves nothing. Record one against a
configured provider, review the answer it captured, and commit it:

```bash
{record}
```

After that, the project replays with no key and no network:

```bash
ingot test
{replay}
```

## Develop

```bash
ingot dev
```

Keeps `check` and the IR build current while you edit. Running is opt-in, so
saving a prompt never silently calls a model. When you change a prompt, the
recorded cassette stops matching on purpose — re-record it and review the diff.

## Changing it with the model again

```bash
ingot new --project . --provider auto "what you want changed"
```

That prints a diff and writes nothing until you pass `--apply`.
"#
    )
}

fn starter_cassette(name: &str, template: StarterTemplate) -> ingot_runtime::Cassette {
    use std::collections::BTreeMap;

    use ingot_runtime::{
        schema::ResponseShape, CompletionRequest, Interaction, ModelSelection, Usage,
    };
    use serde_json::json;

    let (inputs, prompt, value) = match template {
        StarterTemplate::Brief => {
            let inputs: BTreeMap<String, serde_json::Value> =
                [("topic".to_string(), json!("compiler design"))].into();
            (
                inputs,
                "Write a short, factual brief about compiler design. Use headings and bullet points."
                    .to_string(),
                json!("# Compiler design\n\n- A front end understands source.\n- An intermediate representation connects analysis to execution.\n- Backends let one checked program reach more than one target."),
            )
        }
        StarterTemplate::DocumentWorkflow => {
            let inputs: BTreeMap<String, serde_json::Value> = [
                ("audience".to_string(), json!("project leads")),
                ("document".to_string(), json!(EXAMPLE_DOCUMENT)),
            ]
            .into();
            (
                inputs,
                format!(
                    "Summarise the following document for project leads. Preserve the important facts.\n\n{EXAMPLE_DOCUMENT}"
                ),
                json!("# Project brief\n\nIngot turns typed agent source into portable Agent IR. Independent backends consume the same checked artifact, including its policy and budget declarations."),
            )
        }
    };

    let request = CompletionRequest {
        node: "n0".to_string(),
        model: ModelSelection::Capabilities {
            capabilities: vec!["structured_output".to_string()],
            min_context_tokens: None,
        },
        system: None,
        prompt,
        context: Vec::new(),
        response_type: "markdown".to_string(),
        shape: ResponseShape::Prose,
        max_tokens: 20_000,
    };
    let qualified_agent = match package_name(name) {
        Some(package) => format!("{package}.{}", template.agent()),
        None => template.agent().to_string(),
    };
    let mut cassette = ingot_runtime::Cassette::new(qualified_agent);
    cassette.inputs = inputs;
    cassette.interactions.push(Interaction {
        index: 0,
        node: request.node.clone(),
        request_digest: request.digest(),
        response_type: request.response_type,
        value,
        usage: Usage {
            input_tokens: 120,
            output_tokens: 60,
            cache_read_tokens: 0,
        },
        model: Some("template/replay".to_string()),
    });
    cassette
}

// --- check -----------------------------------------------------------------

fn run_check(args: &PathArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.path.as_deref())?;
    let compilation = compile(&target)?;
    report(&compilation, color);
    if !compilation.has_errors() {
        warn_unchargeable_cost(&compilation, &target);
    }
    Ok(exit_code(&compilation))
}

// --- fmt -------------------------------------------------------------------

fn run_fmt(args: &FmtArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.target.path.as_deref())?;
    let original = std::fs::read_to_string(&target.entry)
        .with_context(|| format!("reading {}", target.entry.display()))?;
    let name = target.entry.display().to_string();

    let result = format_source(name.clone(), original.clone());
    if result.diagnostics.has_errors() {
        eprint!(
            "{}",
            ingot_diagnostics::render_all(&result.sources, &result.diagnostics, color)
        );
        eprintln!("cannot format {name}: fix the syntax errors first");
        return Ok(EXIT_DIAGNOSTICS);
    }

    let Some(formatted) = result.formatted else {
        return Ok(EXIT_DIAGNOSTICS);
    };

    if formatted == original {
        if !args.check {
            println!("{name} is already formatted");
        }
        return Ok(EXIT_OK);
    }

    if args.check {
        eprintln!("{name} is not formatted");
        eprintln!("run `ingot fmt` to rewrite it");
        return Ok(EXIT_DIAGNOSTICS);
    }

    std::fs::write(&target.entry, &formatted)
        .with_context(|| format!("writing {}", target.entry.display()))?;
    println!("formatted {name}");
    Ok(EXIT_OK)
}

// --- build -----------------------------------------------------------------

fn run_build(args: &BuildArgs, color: RenderColor) -> Result<u8> {
    if (args.json || args.allow_unimplemented) && args.backend == BuildTarget::Ir {
        bail!(
            "--json and --allow-unimplemented belong to a portability report, and the `ir` \
             target has nothing to report: the IR is what every backend reads, so nothing can \
             fail to express it\n  \
             pass --target python"
        );
    }

    if let Some(document) = &args.from_ir {
        return build_from_ir(document, args);
    }

    let mut target = resolve_target(args.target.path.as_deref())?;
    if let Some(out_dir) = &args.out_dir {
        target.out_dir = out_dir.clone();
    }

    // Machine-readable output must contain exactly one JSON document. Progress
    // remains useful for the ordinary terminal-oriented build.
    if !args.json {
        if let Some(manifest) = &target.manifest {
            println!(
                "building {} {}",
                manifest.project.name, manifest.project.version
            );
        }
    }

    let compilation = compile(&target)?;
    report(&compilation, color);
    if compilation.has_errors() {
        return Ok(EXIT_DIAGNOSTICS);
    }

    if compilation.agents.is_empty() {
        println!("nothing to build: the program declares no agent");
        return Ok(EXIT_OK);
    }

    warn_unchargeable_cost(&compilation, &target);

    // Before anything is written. A build is the last moment a credential is
    // still only in the working tree, and the first moment it would be in an
    // artifact somebody moves.
    package::scan_project(&compilation, &target)?;

    std::fs::create_dir_all(&target.out_dir)
        .with_context(|| format!("creating {}", target.out_dir.display()))?;

    match args.backend {
        BuildTarget::Ir => build_ir(&compilation, &target),
        BuildTarget::Python => build_python(&compilation.agents, &target.out_dir, args),
    }
}

/// Build a target from an Agent IR document nothing local compiled.
///
/// No source, no manifest, no credential scan: there is nothing to scan, and
/// the document has already been through whatever compiler produced it. What
/// this does check is the IR major version, because a target that quietly
/// ignored the parts of a newer document it did not understand would produce a
/// program that does less than the artifact says.
fn build_from_ir(document: &Path, args: &BuildArgs) -> Result<u8> {
    if args.backend != BuildTarget::Python {
        bail!(
            "--from-ir needs a target to build *to*, and the `ir` target's input and output \
             would be the same document\n  \
             pass --target python"
        );
    }
    if args.target.path.is_some() {
        bail!(
            "--from-ir names the document to build, so there is no source path to give as \
             well\n  \
             drop one of them: the two would have to agree and nothing checks that they do"
        );
    }

    let text = std::fs::read_to_string(document)
        .with_context(|| format!("reading {}", document.display()))?;
    let ir = ingot_ir::AgentIr::from_json(&text)
        .map_err(|error| anyhow::anyhow!("{}: {error}", document.display()))?;

    let out_dir = args
        .out_dir
        .clone()
        .unwrap_or_else(|| PathBuf::from("target").join("ingot"));
    std::fs::create_dir_all(&out_dir).with_context(|| format!("creating {}", out_dir.display()))?;

    build_python(&[ir], &out_dir, args)
}

pub(crate) fn build_ir(compilation: &Compilation, target: &Target) -> Result<u8> {
    for agent in &compilation.agents {
        let path = target
            .out_dir
            .join(format!("{}.ir.json", short_name(agent)));
        std::fs::write(&path, agent.to_canonical_json())
            .with_context(|| format!("writing {}", path.display()))?;
        println!("{} -> {}", agent.agent, path.display());
    }
    Ok(EXIT_OK)
}

/// Compile for a target that is not the IR.
///
/// The report comes first and always, because the useful moment to learn that a
/// target cannot express something is before the artifact is deployed rather
/// than when the agent reaches the node.
fn build_python(agents: &[ingot_ir::AgentIr], out_dir: &Path, args: &BuildArgs) -> Result<u8> {
    use ingot_backend_python as python;

    let report = python::analyse(python::TARGET, agents);

    if args.json {
        // A deployment gate reads `.unimplemented`; the per-agent detail is
        // there for whoever has to fix it.
        let payload = serde_json::json!({
            "target": report.target,
            "buildable": report.buildable(),
            "unimplemented": report.unimplemented(),
            "agents": report.agents,
        });
        println!("{}", serde_json::to_string_pretty(&payload)?);
    } else {
        eprintln!("{}", report.render());
        eprintln!();
    }

    if !report.buildable() && !args.allow_unimplemented {
        let blocked: Vec<&str> = report
            .blocked()
            .iter()
            .map(|agent| agent.agent.as_str())
            .collect();
        bail!(
            "`{}` does not implement everything these agents use: {}\n  \
             fix the agent, or pass --allow-unimplemented to build one that will not do it",
            python::TARGET,
            blocked.join(", ")
        );
    }

    for agent in agents {
        let source = match python::emit(agent) {
            Ok(source) => source,
            // Reaching here with --allow-unimplemented is the operator getting
            // what they asked for, and it still refuses rather than emitting a
            // program with a hole in it.
            Err(error) => bail!(
                "{} cannot be built for `{}`: {error}",
                agent.agent,
                python::TARGET
            ),
        };
        let path = out_dir.join(format!("{}.{}", short_name(agent), python::EXTENSION));
        std::fs::write(&path, &source).with_context(|| format!("writing {}", path.display()))?;
        if !args.json {
            println!("{} -> {}", agent.agent, path.display());
        }
    }
    Ok(EXIT_OK)
}

// --- package ---------------------------------------------------------------

fn run_package(args: &PackageArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.target.path.as_deref())?;
    let compilation = compile(&target)?;
    if !args.json {
        report(&compilation, color);
    }
    if compilation.has_errors() {
        if args.json {
            report(&compilation, color);
        }
        return Ok(EXIT_DIAGNOSTICS);
    }
    // A package distributes what was checked. Packaging an unchecked revision is
    // the one thing this command must never make easy.
    package::scan_project(&compilation, &target)?;

    package::run(
        &compilation,
        &target,
        &package::PackageConfig {
            out_dir: args.out_dir.clone(),
            reports: args.reports.clone(),
            verify: args.verify,
            json: args.json,
        },
    )
}

/// The last segment of a dotted agent name, which is what a file is named after.
fn short_name(agent: &ingot_ir::AgentIr) -> &str {
    agent.agent.rsplit('.').next().unwrap_or(&agent.agent)
}

// --- ir --------------------------------------------------------------------

fn run_ir(args: &IrArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.target.path.as_deref())?;
    let compilation = compile(&target)?;
    report(&compilation, color);
    if compilation.has_errors() {
        return Ok(EXIT_DIAGNOSTICS);
    }

    let agent = match &args.agent {
        Some(name) => compilation.agent(name).with_context(|| {
            let available: Vec<&str> = compilation
                .agents
                .iter()
                .map(|agent| agent.agent.as_str())
                .collect();
            format!(
                "no agent named `{name}`; this file declares: {}",
                available.join(", ")
            )
        })?,
        None => match compilation.agents.len() {
            0 => bail!("the program declares no agent"),
            1 => &compilation.agents[0],
            _ => {
                let available: Vec<&str> = compilation
                    .agents
                    .iter()
                    .map(|agent| agent.agent.as_str())
                    .collect();
                bail!(
                    "this file declares several agents; pass --agent <name>\navailable: {}",
                    available.join(", ")
                )
            }
        },
    };

    let mut stdout = std::io::stdout().lock();
    stdout
        .write_all(agent.to_canonical_json().as_bytes())
        .context("writing IR to standard output")?;
    Ok(EXIT_OK)
}

// --- run / test --------------------------------------------------------------

fn run_run(args: &RunArgs, color: RenderColor) -> Result<u8> {
    if args.sandbox_allow_unenforced && !args.sandbox && !args.contained {
        bail!(
            "--sandbox-allow-unenforced only means something with --sandbox or --contained; \
             without a boundary there is nothing to leave unenforced"
        );
    }
    if args.image.is_some() && !args.contained {
        bail!("--image only applies to --contained; a run on the host has no image");
    }

    let target = resolve_target(args.target.path.as_deref())?;
    let compilation = compile(&target)?;
    report(&compilation, color);
    if compilation.has_errors() {
        return Ok(EXIT_DIAGNOSTICS);
    }
    warn_unchargeable_cost(&compilation, &target);

    // Replaying a project's own fixture should not require typing its path.
    // Only when there is one to be sure about — see `run::project_cassette`.
    let cassette = match (&args.cassette, args.provider) {
        (None, ProviderChoice::Replay) => Some(run::project_cassette(&target.root)?),
        (chosen, _) => chosen.clone(),
    };

    run::execute(
        &compilation,
        &RunConfig {
            inputs: args.inputs.clone(),
            provider: args.provider,
            cassette,
            record: args.record.clone(),
            model: args.model.clone(),
            effort: args.effort.clone(),
            agent: args.agent.clone(),
            out_dir: args.out_dir.clone(),
            history: (!args.no_history).then(|| target.out_dir.clone()),
            events: args.events,
            build_dir: Some(target.out_dir.clone()),
            stop_at: args.stop_at.clone(),
            resume: args.resume.clone(),
            snapshot: args.snapshot.clone(),
            memory: args.memory.clone(),
            memory_mode: match (args.no_memory, args.migrate_memory) {
                (true, _) => memory::MemoryMode::Disabled,
                (_, true) => memory::MemoryMode::Migrate,
                _ => memory::MemoryMode::Open,
            },
            yes: args.yes,
            max_steps: args.max_steps,
            mcp: target.mcp(),
            root: target.root.clone(),
            no_tools: args.no_tools,
            sandbox: args.sandbox,
            sandbox_allow_unenforced: args.sandbox_allow_unenforced,
            allow_unenforced_scopes: args.allow_unenforced_scopes,
            workspace: workspace(args.workspace.as_deref(), &target)?,
            models: target.model(),
            contained: args.contained,
            supervised: args.supervised,
            image: args
                .image
                .clone()
                .or_else(|| target.image())
                .or_else(|| args.contained.then(image::reference_image)),
            timeout_seconds: args.timeout.or_else(|| target.timeout_seconds()),
        },
    )
}

/// The root policy paths are relative to: the flag, then the manifest, then the
/// project directory.
pub(crate) fn workspace(flag: Option<&Path>, target: &Target) -> Result<PathBuf> {
    let chosen = flag
        .map(Path::to_path_buf)
        .unwrap_or_else(|| target.workspace());
    chosen
        .canonicalize()
        .with_context(|| format!("resolving the workspace {}", chosen.display()))
}

fn run_tools(args: &ToolsArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.target.path.as_deref())?;
    let compilation = compile(&target)?;
    report(&compilation, color);
    if compilation.has_errors() {
        return Ok(EXIT_DIAGNOSTICS);
    }

    tools::inspect(
        &compilation,
        &tools::ToolsConfig {
            mcp: target.mcp(),
            root: target.root.clone(),
        },
        args.json,
        args.propose,
    )
}

fn run_test(args: &TestArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.target.path.as_deref())?;
    let compilation = compile(&target)?;
    report(&compilation, color);
    if compilation.has_errors() {
        return Ok(EXIT_DIAGNOSTICS);
    }

    // Cassette paths are relative to the project, not the working directory,
    // so `ingot test examples/research-agent` works from anywhere.
    let project_root = target
        .entry
        .parent()
        .unwrap_or(Path::new("."))
        .to_path_buf();
    let cassette_dir = if args.cassettes.is_absolute() {
        args.cassettes.clone()
    } else {
        project_root.join(&args.cassettes)
    };

    run::test(
        &compilation,
        &TestConfig {
            cassette_dir,
            filter: args.filter.clone(),
            pricing: target.model().pricing(),
        },
    )
}

// --- doctor ---------------------------------------------------------------

fn run_doctor(args: &DoctorArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.target.path.as_deref())?;
    let compilation = compile(&target)?;
    if !args.json {
        report(&compilation, color);
    }
    doctor::inspect(&target, &compilation, args.json)
}

// --- conform ---------------------------------------------------------------

fn run_conform(args: &ConformArgs) -> Result<u8> {
    if let Some(request) = &args.adapter {
        return conform::adapt(request);
    }

    if let Some(dir) = &args.export {
        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
        conform::materialise(dir)?;
        println!(
            "wrote {} case(s) to {}\n  run them with: ingot conform --suite {}",
            conform::cases(dir)?.len(),
            dir.display(),
            dir.display()
        );
        return Ok(EXIT_OK);
    }

    // Held for the whole command: the embedded suite is written into a
    // temporary directory, and dropping the guard removes it.
    let unpacked;
    let suite = match &args.suite {
        Some(path) => path.clone(),
        None => match find_checkout() {
            // A checkout wins, so editing a case in the repository changes what
            // runs. Outside one, the built-in copy is what a downloaded binary
            // has, and it is the whole point of embedding it.
            Some(path) => path,
            None => {
                unpacked = Unpacked::new()?;
                conform::materialise(unpacked.path())?
            }
        },
    };

    if args.list {
        let described = conform::describe(&suite)?;
        if args.json {
            println!("{}", serde_json::to_string_pretty(&described)?);
        } else {
            for case in described["cases"].as_array().into_iter().flatten() {
                println!(
                    "{}\n     {}",
                    case["case"].as_str().unwrap_or_default(),
                    case["what"].as_str().unwrap_or_default()
                );
                for pin in case["pins"].as_array().into_iter().flatten() {
                    println!("     pins {}", pin.as_str().unwrap_or_default());
                }
            }
        }
        return Ok(EXIT_OK);
    }

    let backend = match &args.backend {
        Some(command) => command.clone(),
        None => {
            let exe = std::env::current_exe().context("locating this executable")?;
            format!("{} conform --adapter", exe.display())
        }
    };

    let work = std::env::temp_dir().join(format!("ingot-conform-{}", std::process::id()));
    let report = conform::run(&suite, &backend, args.case.as_deref(), &work)?;
    let _ = std::fs::remove_dir_all(&work);

    if args.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        println!("{}", report.render());
    }
    Ok(if report.conformant() {
        EXIT_OK
    } else {
        EXIT_DIAGNOSTICS
    })
}

/// The suite in the surrounding checkout, if the working directory is in one.
///
/// Absent is the ordinary case for a downloaded binary, and it is not an error:
/// the caller falls back to the copy compiled into this one.
///
/// The path is `crates/ingot-conformance` rather than `specs/conformance`
/// because a package carries its own directory and nothing above it, so the
/// cases have to live inside the crate that ships them.
fn find_checkout() -> Option<PathBuf> {
    let start = std::env::current_dir().ok()?;
    let mut here = start.as_path();
    loop {
        let candidate = here.join("crates").join("ingot-conformance");
        if candidate.join("cases").is_dir() {
            return Some(candidate);
        }
        here = here.parent()?;
    }
}

/// A temporary directory holding the unpacked built-in suite.
///
/// Removed on drop. A run leaves nothing behind, which is what lets
/// `ingot conform` be something you type in any directory.
struct Unpacked(PathBuf);

impl Unpacked {
    fn new() -> Result<Unpacked> {
        let path = std::env::temp_dir().join(format!("ingot-suite-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).with_context(|| format!("creating {}", path.display()))?;
        Ok(Unpacked(path))
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for Unpacked {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

// --- dev ------------------------------------------------------------------

fn run_dev(args: &DevArgs, color: RenderColor) -> Result<u8> {
    let initial = resolve_target(args.target.path.as_deref())?;
    // Resolved once, here, rather than on every revision: a watch loop that
    // re-answered "which cassette?" after each save could change its mind
    // halfway through a session because a file appeared beside the first one.
    let cassette = match (&args.cassette, args.provider, args.run) {
        (None, ProviderChoice::Replay, true) => Some(run::project_cassette(&initial.root)?),
        (chosen, _, _) => chosen.clone(),
    };
    dev::watch(
        args.target.path.as_deref(),
        initial,
        &dev::DevConfig {
            run: args.run,
            inputs: args.inputs.clone(),
            provider: args.provider,
            cassette,
            agent: args.agent.clone(),
            events: args.events,
            yes: args.yes,
            max_steps: args.max_steps,
            allow_unenforced_scopes: args.allow_unenforced_scopes,
            color,
        },
    )
}

// --- sandbox ---------------------------------------------------------------

fn run_sandbox(args: &SandboxArgs, color: RenderColor) -> Result<u8> {
    let target = resolve_target(args.target.path.as_deref())?;
    let compilation = compile(&target)?;
    report(&compilation, color);
    if compilation.has_errors() {
        return Ok(EXIT_DIAGNOSTICS);
    }

    sandbox::inspect(
        &compilation,
        &SandboxConfig {
            workspace: workspace(args.workspace.as_deref(), &target)?,
            mcp: target.mcp(),
            json: args.json,
        },
    )
}

// --- explain ---------------------------------------------------------------

fn run_explain(args: &ExplainArgs) -> Result<u8> {
    match codes::explain(&args.code) {
        Some(text) => {
            println!("{}\n", args.code.to_ascii_uppercase());
            println!("{text}");
            Ok(EXIT_OK)
        }
        None => {
            eprintln!("no long-form explanation for `{}`", args.code);
            eprintln!();
            eprintln!("explained codes: {}", codes::EXPLAINED_CODES.join(", "));
            Ok(EXIT_FAILURE)
        }
    }
}

// --- shared ----------------------------------------------------------------

pub(crate) fn compile(target: &Target) -> Result<Compilation> {
    compile_path(&target.entry).with_context(|| format!("compiling {}", target.entry.display()))
}

/// Warn when an agent states a `cost` budget this project cannot charge.
///
/// The compiler cannot know this. A price is deployment configuration, and the
/// source is deliberately deployment-independent — so the check lives where both
/// halves are visible, which is here. Saying it at `check` time is the point:
/// the alternative is learning it after the money is spent.
///
/// Only fires when the project configures **no** price at all. With some
/// configured, whether the one that answers is among them is a question only the
/// run can settle, and the run reports every model it could not price.
pub(crate) fn warn_unchargeable_cost(compilation: &Compilation, target: &Target) {
    if !target.model().prices.is_empty() {
        return;
    }
    let budgeted: Vec<&str> = compilation
        .agents
        .iter()
        .filter(|agent| agent.budget.cost.is_some())
        .map(|agent| agent.agent.as_str())
        .collect();
    let Some(first) = budgeted.first() else {
        return;
    };

    eprintln!(
        "warning[{}]: `{}` states a cost budget that nothing can charge",
        codes::COST_BUDGET_NOT_CHARGED,
        first
    );
    for agent in budgeted.iter().skip(1) {
        eprintln!("             so does `{agent}`");
    }
    eprintln!("  = note: this project configures no `[[model.price]]`, so the budget is");
    eprintln!("          reported as uncharged rather than enforced");
    eprintln!(
        "  = help: add a price, or remove the budget; `ingot explain {}`",
        codes::COST_BUDGET_NOT_CHARGED
    );
}

/// Print diagnostics, then a one-line summary.
///
/// Everything here goes to stderr, including the success line: stdout carries
/// machine-readable output such as `ingot ir`, and a status message must never
/// end up in a pipe someone is parsing.
pub(crate) fn report(compilation: &Compilation, color: RenderColor) {
    if !compilation.diagnostics.is_empty() {
        eprint!("{}", compilation.render_diagnostics(color));
    }

    let errors = compilation.error_count();
    let warnings = compilation.warning_count();
    match (errors, warnings) {
        (0, 0) => eprintln!("ok"),
        (0, warnings) => eprintln!("ok, {warnings} warning(s)"),
        (errors, 0) => eprintln!("failed: {errors} error(s)"),
        (errors, warnings) => eprintln!("failed: {errors} error(s), {warnings} warning(s)"),
    }
}

fn exit_code(compilation: &Compilation) -> u8 {
    if compilation.has_errors() {
        EXIT_DIAGNOSTICS
    } else {
        EXIT_OK
    }
}

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

    #[test]
    fn a_plain_name_becomes_a_package() {
        assert_eq!(
            package_name("research-agent").as_deref(),
            Some("research_agent")
        );
        assert_eq!(package_name("My Agent").as_deref(), Some("my_agent"));
    }

    #[test]
    fn a_reserved_word_yields_no_package() {
        // `ingot init agent` used to generate `package agent`, which is a
        // syntax error, so the generated project would not compile.
        for reserved in ["agent", "tool", "flow", "type", "policy"] {
            assert_eq!(package_name(reserved), None, "`{reserved}` is reserved");
        }
    }

    #[test]
    fn a_name_that_cannot_start_an_identifier_yields_no_package() {
        assert_eq!(package_name("2fa"), None);
        assert_eq!(package_name("---"), None);
        assert_eq!(package_name(""), None);
    }

    #[test]
    fn the_generated_source_omits_an_unusable_package_line() {
        let source = starter_source("agent", StarterTemplate::Brief);
        assert!(!source.contains("package"), "{source}");
        assert!(
            source.starts_with(
                "language 0.1
"
            ),
            "{source}"
        );
    }

    #[test]
    fn the_generated_source_keeps_a_usable_package_line() {
        let source = starter_source("research-agent", StarterTemplate::Brief);
        assert!(source.contains("package research_agent"), "{source}");
    }
}