keleusma-cli 0.2.2

Standalone command-line frontend for Keleusma. Provides a script runner, a bytecode compiler, and an interactive REPL so users can work with Keleusma scripts without writing any Rust host code.
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
2470
2471
#![deny(missing_docs)]
//! Standalone command-line frontend for Keleusma.
//!
//! Provides three subcommands modeled after Rhai's CLI tooling:
//!
//! - `run <file>` parses, compiles, verifies, and executes a Keleusma
//!   script. Pre-registers utility and math natives.
//! - `compile <file> [-o <output>]` produces a serialized bytecode
//!   file that hosts can load through `Vm::load_bytes`.
//! - `repl` starts an interactive prompt where expressions and
//!   declarations accumulate into a session prefix.
//!
//! As a shorthand, any first argument ending in `.kel` is treated as
//! a `run` invocation, so `keleusma hello.kel` runs the script.
//!
//! The CLI gates bytecode execution through optional signing and
//! encryption policies. Discovery of enrolled signing keys from a
//! platform-conventional directory or the `KELEUSMA_TRUSTED_KEYS_DIR`
//! environment variable activates strict signing mode. The strict
//! mode rejects source files, unsigned bytecode, and bytecode signed
//! by non-enrolled keys. See `strict_mode` for the policy mechanics.

mod duration;
mod runtasks;
mod strict_mode;

use std::env;
use std::fs;
use std::io::{self, BufRead, Write};
use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use keleusma::compiler::{CompileOptions, compile_with_options};
use keleusma::lexer::tokenize;
use keleusma::parser::parse;
use keleusma::stddsl;
use keleusma::vm::{DEFAULT_ARENA_CAPACITY, Vm, VmState};
use keleusma::{Arena, Value};

use strict_mode::{PolicyContext, X25519_PRIVATE_KEY_LEN, build_policy_context};

const REPL_BANNER: &str = "Keleusma REPL. Type :help for commands, :quit to exit.";

fn main() -> ExitCode {
    let args: Vec<String> = env::args().collect();
    let subcommand = match args.get(1) {
        Some(s) => s.as_str(),
        None => {
            print_help();
            return ExitCode::SUCCESS;
        }
    };

    match subcommand {
        "run" => run_subcommand(&args[2..]),
        "run-tasks" => run_tasks_subcommand(&args[2..]),
        "compile" => compile_subcommand(&args[2..]),
        "strip" => strip_subcommand(&args[2..]),
        "keygen" => keygen_subcommand(&args[2..]),
        "repl" => repl_subcommand(&args[2..]),
        "--help" | "-h" | "help" => {
            print_help();
            ExitCode::SUCCESS
        }
        "--version" | "-V" | "version" => {
            println!("keleusma {}", env!("CARGO_PKG_VERSION"));
            ExitCode::SUCCESS
        }
        other => {
            // Treat any remaining argument as a script path. This
            // covers both `keleusma file.kel` (extension shorthand)
            // and `keleusma /path/to/extensionless-shebang-script`
            // when the kernel invokes us through a `#!/usr/bin/env
            // keleusma` line. If the file is missing, the error
            // surfaces in `run_file`.
            if std::path::Path::new(other).is_file() {
                let ctx = match build_policy_context() {
                    Ok(c) => c,
                    Err(e) => {
                        eprintln!("error: {}", e);
                        return ExitCode::FAILURE;
                    }
                };
                let verifying = ctx.enrolled_keys.clone();
                let decrypting = ctx.decryption_keys.clone();
                // Shebang/shorthand invocation: the script path is
                // `other` (argv[1]) and everything after it is a script
                // argument. Install argv[0] = script path, the rest as
                // positionals, so `shell::arg`/`arg_count` see the
                // script's own arguments.
                let mut argv = Vec::with_capacity(args.len() - 1);
                argv.push(other.to_string());
                argv.extend(args[2..].iter().cloned());
                stddsl::shell::set_script_args(argv);
                run_file(
                    other,
                    &verifying,
                    &decrypting,
                    &ctx,
                    &LoopRunnerConfig::default(),
                    // The shebang/shorthand form treats every token after the
                    // path as a script argument, so it does not parse CLI run
                    // flags such as --print-memory.
                    false,
                )
            } else {
                eprintln!("error: unknown subcommand or missing file `{}`", other);
                print_help();
                ExitCode::FAILURE
            }
        }
    }
}

fn print_help() {
    println!("keleusma: command-line frontend for the Keleusma scripting language");
    println!();
    println!("Usage:");
    println!("  keleusma <subcommand> [options]");
    println!("  keleusma <file>.kel               (shorthand for `run`)");
    println!();
    println!("Subcommands:");
    println!("  run <file> [--verifying-key <keyfile> ...]");
    println!("             [--decryption-key <keyfile> ...]");
    println!("             [--tick-interval <duration>] [--quiet] [--print-memory]");
    println!("                                    Compile and execute a script.");
    println!("                                    Pass --verifying-key (repeatable) to verify");
    println!("                                    signed compiled bytecode against the");
    println!("                                    supplied 32-byte Ed25519 public-key files.");
    println!("                                    Pass --tick-interval to rate-limit a");
    println!("                                    productive-divergent `loop main` entry");
    println!("                                    point. Accepts humanized durations such as");
    println!("                                    100ms, 1s, 1m, 1h, 1d, 1w. Maximum four");
    println!("                                    weeks. --quiet suppresses the stderr warning");
    println!("                                    that fires when an iteration exceeds the");
    println!("                                    configured interval. --print-memory reports the");
    println!("                                    program's worst-case arena footprint and exits");
    println!("                                    without running, for provisioning a host.");
    println!("  compile <file> [-o <output>] [--signing-key <keyfile>]");
    println!("                 [--encryption-key <keyfile>] [--target <name>] [--debug]");
    println!("                                    Compile to bytecode. With --debug, emit");
    println!("                                    strippable debug metadata (source spans for");
    println!("                                    stack traces); remove it later with `strip`.");
    println!("                                    With --signing-key,");
    println!("                                    sign the output with the supplied 32-byte");
    println!("                                    Ed25519 seed file. The source script must");
    println!("                                    declare the entry function with the");
    println!("                                    `signed` modifier; otherwise the resulting");
    println!("                                    bytecode is unsigned and the toolchain");
    println!("                                    refuses the signing key argument silently.");
    println!("                                    --target selects the target descriptor:");
    println!("                                    host (default), wasm32, embedded_32,");
    println!("                                    embedded_16, embedded_8. Programs are");
    println!("                                    validated against the selected target's");
    println!("                                    word, address, and float widths.");
    println!("  keygen --seed <out> --public <out>");
    println!("                                    Generate a fresh Ed25519 keypair from the");
    println!("                                    OS RNG. Writes the 32-byte signing seed to");
    println!("                                    one file and the 32-byte verifying key to");
    println!("                                    another. Treat the seed as a private");
    println!("                                    secret; the verifying key may be");
    println!("                                    distributed to hosts that load signed");
    println!("                                    bytecode.");
    println!("  run-tasks <manifest.toml> [--quiet]");
    println!("                                    Multi-script runner. Loads tasks from a");
    println!("                                    TOML manifest and drives them through a");
    println!("                                    cooperative scheduler with event queue,");
    println!("                                    supervised restart, and per-task signing");
    println!("                                    and encryption policy. See");
    println!("                                    docs/architecture/RUN_TASKS.md.");
    println!("  strip <file.bin> [-o <output>]");
    println!("                                    Remove debug metadata from compiled");
    println!("                                    bytecode, producing a release artefact byte-");
    println!("                                    identical to a non-debug compile. Output");
    println!("                                    defaults to the input path. Refuses signed or");
    println!("                                    encrypted input; strip before signing.");
    println!("  repl                              Start interactive REPL");
    println!("  help, --help, -h                  Show this help");
    println!("  version, --version, -V            Show version");
    println!();
    println!("Examples:");
    println!("  keleusma run hello.kel");
    println!("  keleusma hello.kel");
    println!("  keleusma compile hello.kel -o hello.kel.bin");
    println!("  keleusma compile hello.kel --debug -o hello.dbg.bin");
    println!("  keleusma strip hello.dbg.bin -o hello.kel.bin");
    println!("  keleusma keygen --seed key.seed --public key.pub");
    println!("  keleusma compile hello.kel --signing-key key.seed -o hello.kel.bin");
    println!("  keleusma run hello.kel.bin --verifying-key key.pub");
    println!("  keleusma repl");
    println!();
    println!("Strict-mode policies (signing and encryption):");
    println!("  Signing: place 32-byte Ed25519 public keys as `*.pub`");
    println!("  files in /etc/keleusma/trusted_keys (Unix) or");
    println!("  %PROGRAMDATA%\\keleusma\\trusted_keys (Windows), or in");
    println!("  the directory named by KELEUSMA_TRUSTED_KEYS_DIR. The");
    println!("  CLI refuses source files, unsigned bytecode, and");
    println!("  bytecode signed by keys not in the trust store. The");
    println!("  --verifying-key argument is rejected. Set");
    println!("  KELEUSMA_REQUIRE_SIGNED=1 to force strict signing mode");
    println!("  even with an empty trust store.");
    println!();
    println!("  Encryption: place 32-byte X25519 private keys as");
    println!("  `*.seed` files in /etc/keleusma/decryption_keys (Unix)");
    println!("  or the equivalent Windows path, or in the directory");
    println!("  named by KELEUSMA_DECRYPTION_KEYS_DIR. The CLI refuses");
    println!("  unencrypted bytecode and bytecode encrypted to a key");
    println!("  not in the decryption-key store. The --decryption-key");
    println!("  argument is rejected. Set KELEUSMA_REQUIRE_ENCRYPTED=1");
    println!("  to force strict encryption mode.");
    println!();
    println!("  The two policies are independent: neither, signing");
    println!("  only, encryption only, or both may be active.");
    println!();
    println!("Examples (encryption):");
    println!("  keleusma keygen --kind encryption --seed dest.seed --public dest.pub");
    println!("  keleusma compile script.kel --signing-key sign.seed \\");
    println!("           --encryption-key dest.pub -o script.kel.bin");
    println!("  keleusma run script.kel.bin --verifying-key sign.pub \\");
    println!("           --decryption-key dest.seed");
}

fn run_subcommand(args: &[String]) -> ExitCode {
    if args.is_empty() {
        eprintln!("error: `run` requires a script path");
        return ExitCode::FAILURE;
    }
    let path = &args[0];

    // Build the policy context at the start of every run invocation.
    // Discovery is fail-closed; a malformed key file in either the
    // signing trust store or the decryption-key store causes the
    // CLI to refuse to start.
    let ctx = match build_policy_context() {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::FAILURE;
        }
    };

    let mut command_line_keys: Vec<ed25519_dalek::VerifyingKey> = Vec::new();
    let mut command_line_decryption_keys: Vec<[u8; X25519_PRIVATE_KEY_LEN]> = Vec::new();
    let mut loop_config = LoopRunnerConfig::default();
    // When set by `--print-memory`, report the program's worst-case arena
    // footprint and exit instead of running it.
    let mut print_memory = false;
    // Positional arguments the launcher passed after the script path.
    // These become the script's own argument vector (after the script
    // path itself) exposed through `shell::arg`/`shell::arg_count`.
    let mut script_args: Vec<String> = Vec::new();
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--verifying-key" => {
                if i + 1 >= args.len() {
                    eprintln!(
                        "error: --verifying-key requires a path to a 32-byte public-key file"
                    );
                    return ExitCode::FAILURE;
                }
                match read_verifying_key(&args[i + 1]) {
                    Ok(k) => command_line_keys.push(k),
                    Err(e) => {
                        eprintln!("error: {}", e);
                        return ExitCode::FAILURE;
                    }
                }
                i += 2;
            }
            "--decryption-key" => {
                if i + 1 >= args.len() {
                    eprintln!(
                        "error: --decryption-key requires a path to a 32-byte X25519 seed file"
                    );
                    return ExitCode::FAILURE;
                }
                match read_x25519_private_key(&args[i + 1]) {
                    Ok(k) => command_line_decryption_keys.push(k),
                    Err(e) => {
                        eprintln!("error: {}", e);
                        return ExitCode::FAILURE;
                    }
                }
                i += 2;
            }
            "--tick-interval" => {
                if i + 1 >= args.len() {
                    eprintln!(
                        "error: --tick-interval requires a humanized duration (for example 100ms, 1s, 1m, 1h, 1d, 1w)"
                    );
                    return ExitCode::FAILURE;
                }
                match duration::parse(&args[i + 1]) {
                    Ok(d) => {
                        loop_config
                            .tick_interval_nanos
                            .store(d.as_nanos() as u64, Ordering::Relaxed);
                    }
                    Err(e) => {
                        eprintln!("error: {}", e);
                        return ExitCode::FAILURE;
                    }
                }
                i += 2;
            }
            "--quiet" => {
                loop_config.quiet = true;
                i += 1;
            }
            "--print-memory" => {
                print_memory = true;
                i += 1;
            }
            // Explicit terminator: everything after `--` is a script
            // argument, even if it looks like a CLI option. This lets a
            // script receive arguments such as `--verbose` without the
            // CLI intercepting them.
            "--" => {
                script_args.extend(args[i + 1..].iter().cloned());
                break;
            }
            // A leading dash on an unrecognized token is a flag typo,
            // not a positional argument; reject it so misspelled CLI
            // options do not silently reach the script.
            other if other.starts_with('-') => {
                eprintln!("error: unknown option `{}`", other);
                return ExitCode::FAILURE;
            }
            // Any other token is a positional argument destined for the
            // script's own argument vector.
            other => {
                script_args.push(other.to_string());
                i += 1;
            }
        }
    }

    // In strict signing mode the trust store is system-managed.
    // The --verifying-key flag is rejected so an unprivileged
    // operator cannot relax the policy at the command line.
    if ctx.strict_signing && !command_line_keys.is_empty() {
        eprintln!(
            "error: strict mode: --verifying-key is rejected; the trust list is system-managed through KELEUSMA_TRUSTED_KEYS_DIR or the platform-conventional directory"
        );
        return ExitCode::FAILURE;
    }

    // In strict encryption mode the decryption-key store is
    // system-managed. The --decryption-key flag is rejected for the
    // same reason as --verifying-key.
    if ctx.strict_encryption && !command_line_decryption_keys.is_empty() {
        eprintln!(
            "error: strict mode: --decryption-key is rejected; the decryption-key store is system-managed through KELEUSMA_DECRYPTION_KEYS_DIR or the platform-conventional directory"
        );
        return ExitCode::FAILURE;
    }

    // Merge the enrolled trust list (used in strict mode) with the
    // command-line keys (used in permissive mode). Only one of the
    // two is non-empty after the rejection check above.
    let mut verifying_keys = ctx.enrolled_keys.clone();
    verifying_keys.extend(command_line_keys);
    let mut decryption_keys = ctx.decryption_keys.clone();
    decryption_keys.extend(command_line_decryption_keys);

    // Install the script's argument vector so `shell::arg`/`arg_count`
    // report the script's own arguments rather than the host process's
    // full argv. Index zero is the script path (`$0` semantics);
    // indices one onward are the collected positional arguments.
    let mut argv = Vec::with_capacity(1 + script_args.len());
    argv.push(path.clone());
    argv.extend(script_args);
    stddsl::shell::set_script_args(argv);

    run_file(
        path,
        &verifying_keys,
        &decryption_keys,
        &ctx,
        &loop_config,
        print_memory,
    )
}

fn run_file(
    path: &str,
    verifying_keys: &[ed25519_dalek::VerifyingKey],
    decryption_keys: &[[u8; X25519_PRIVATE_KEY_LEN]],
    policy: &PolicyContext,
    loop_config: &LoopRunnerConfig,
    print_memory: bool,
) -> ExitCode {
    let bytes = match fs::read(path) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("error: reading {}: {}", path, e);
            return ExitCode::FAILURE;
        }
    };
    // Detect compiled bytecode by magic. The bytecode loader strips
    // a leading shebang line, so check both at offset 0 and after a
    // `#!...\n` envelope.
    let result = if looks_like_bytecode(&bytes) {
        execute_bytecode(
            &bytes,
            verifying_keys,
            decryption_keys,
            policy,
            loop_config,
            print_memory,
        )
    } else if policy.strict_signing || policy.strict_encryption {
        eprintln!(
            "error: strict mode: source execution disabled; compile{} the source before running",
            if policy.strict_encryption {
                ", sign, and encrypt"
            } else {
                " and sign"
            }
        );
        return ExitCode::FAILURE;
    } else if !verifying_keys.is_empty() || !decryption_keys.is_empty() {
        eprintln!(
            "error: --verifying-key or --decryption-key supplied but {} is source, not bytecode",
            path
        );
        return ExitCode::FAILURE;
    } else {
        let source = match core::str::from_utf8(&bytes) {
            Ok(s) => s,
            Err(_) => {
                eprintln!(
                    "error: {} is neither valid UTF-8 source nor recognised bytecode",
                    path
                );
                return ExitCode::FAILURE;
            }
        };
        execute_source(source, loop_config, print_memory)
    };
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {}", e);
            ExitCode::FAILURE
        }
    }
}

fn looks_like_bytecode(bytes: &[u8]) -> bool {
    let after_shebang = if bytes.starts_with(b"#!") {
        match bytes.iter().position(|&b| b == b'\n') {
            Some(nl) => &bytes[nl + 1..],
            None => return false,
        }
    } else {
        bytes
    };
    after_shebang.starts_with(b"KELE")
}

/// `run-tasks <manifest.toml> [--quiet]`. Multi-script runner per
/// `docs/architecture/RUN_TASKS.md`. The manifest argument is
/// required; the `--quiet` flag suppresses scheduler stderr.
fn run_tasks_subcommand(args: &[String]) -> ExitCode {
    if args.is_empty() {
        eprintln!("error: `run-tasks` requires a manifest path");
        return ExitCode::FAILURE;
    }
    let manifest_path = &args[0];
    let mut quiet = false;
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--quiet" => {
                quiet = true;
                i += 1;
            }
            other => {
                eprintln!("error: unknown option `{}`", other);
                return ExitCode::FAILURE;
            }
        }
    }
    let outcome = runtasks::run(std::path::Path::new(manifest_path), quiet);
    outcome.into_exit_code()
}

fn compile_subcommand(args: &[String]) -> ExitCode {
    if args.is_empty() {
        eprintln!("error: `compile` requires a script path");
        return ExitCode::FAILURE;
    }
    let input = &args[0];
    let mut output: Option<String> = None;
    let mut signing_key_path: Option<String> = None;
    let mut encryption_key_path: Option<String> = None;
    let mut target: Option<keleusma::target::Target> = None;
    let mut emit_debug = false;
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "-o" | "--output" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --output requires a path");
                    return ExitCode::FAILURE;
                }
                output = Some(args[i + 1].clone());
                i += 2;
            }
            "--signing-key" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --signing-key requires a path to a 32-byte seed file");
                    return ExitCode::FAILURE;
                }
                signing_key_path = Some(args[i + 1].clone());
                i += 2;
            }
            "--encryption-key" => {
                if i + 1 >= args.len() {
                    eprintln!(
                        "error: --encryption-key requires a path to a 32-byte X25519 public-key file"
                    );
                    return ExitCode::FAILURE;
                }
                encryption_key_path = Some(args[i + 1].clone());
                i += 2;
            }
            "--target" => {
                if i + 1 >= args.len() {
                    eprintln!(
                        "error: --target requires a target name (host, wasm32, embedded_32, embedded_16, embedded_8)"
                    );
                    return ExitCode::FAILURE;
                }
                match parse_target_name(&args[i + 1]) {
                    Ok(t) => target = Some(t),
                    Err(e) => {
                        eprintln!("error: {}", e);
                        return ExitCode::FAILURE;
                    }
                }
                i += 2;
            }
            "--debug" => {
                emit_debug = true;
                i += 1;
            }
            other => {
                eprintln!("error: unknown option `{}`", other);
                return ExitCode::FAILURE;
            }
        }
    }
    let output_path = output.unwrap_or_else(|| default_output_path(input));

    // Encryption requires signing because the wire format ties the
    // two together. The signature covers the encrypted body so an
    // adversary cannot strip the encryption layer.
    if encryption_key_path.is_some() && signing_key_path.is_none() {
        eprintln!(
            "error: --encryption-key requires --signing-key; encrypted artefacts must be signed"
        );
        return ExitCode::FAILURE;
    }

    // Compile-time strict-mode warning. If the local host runs
    // strict signing or strict encryption mode, warn the operator
    // when the compile would produce an artefact that the local
    // host would not accept. The warning does not fail the compile;
    // operators may legitimately produce artefacts for other hosts.
    if let Ok(policy) = build_policy_context() {
        if policy.strict_signing && signing_key_path.is_none() {
            eprintln!(
                "warning: local host runs strict signing mode; the produced artefact will be unsigned and will not run on this host"
            );
        }
        if policy.strict_signing
            && let Some(ref sign_path) = signing_key_path
            && let Ok(signing_key) = read_signing_key(sign_path)
        {
            let verifying = signing_key.verifying_key();
            if !policy.enrolled_keys.contains(&verifying) {
                eprintln!(
                    "warning: the signing key's verifying counterpart is not in this host's trust list; the produced artefact will not run on this host"
                );
            }
        }
        if policy.strict_encryption && encryption_key_path.is_none() {
            eprintln!(
                "warning: local host runs strict encryption mode; the produced artefact will be unencrypted and will not run on this host"
            );
        }
    }

    let source = match fs::read_to_string(input) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: reading {}: {}", input, e);
            return ExitCode::FAILURE;
        }
    };
    let module = match compile_source_with_target(&source, target.as_ref(), emit_debug) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::FAILURE;
        }
    };
    let bytes = match (signing_key_path, encryption_key_path) {
        (Some(sign_path), Some(enc_path)) => {
            // Signed-and-encrypted path.
            let signing_key = match read_signing_key(&sign_path) {
                Ok(k) => k,
                Err(e) => {
                    eprintln!("error: {}", e);
                    return ExitCode::FAILURE;
                }
            };
            let recipient_pk = match read_x25519_public_key(&enc_path) {
                Ok(k) => k,
                Err(e) => {
                    eprintln!("error: {}", e);
                    return ExitCode::FAILURE;
                }
            };
            // Generate a fresh ephemeral X25519 seed from the OS RNG
            // for this module. The ephemeral private key is consumed
            // by the encryption operation and discarded; only the
            // ephemeral public key persists in the artefact.
            let mut ephemeral_seed = [0u8; X25519_PRIVATE_KEY_LEN];
            use rand_core::RngCore;
            rand_core::OsRng.fill_bytes(&mut ephemeral_seed);
            match keleusma::wire_format::module_to_encrypted_signed_wire_bytes(
                &module,
                &signing_key,
                &recipient_pk,
                &ephemeral_seed,
            ) {
                Ok(b) => b,
                Err(e) => {
                    eprintln!("error: encrypting and signing bytecode: {:?}", e);
                    return ExitCode::FAILURE;
                }
            }
        }
        (Some(sign_path), None) => {
            // Signed-only path (existing behavior).
            let signing_key = match read_signing_key(&sign_path) {
                Ok(k) => k,
                Err(e) => {
                    eprintln!("error: {}", e);
                    return ExitCode::FAILURE;
                }
            };
            match keleusma::wire_format::module_to_signed_wire_bytes(&module, &signing_key) {
                Ok(b) => b,
                Err(e) => {
                    eprintln!("error: signing bytecode: {:?}", e);
                    return ExitCode::FAILURE;
                }
            }
        }
        (None, _) => {
            // Unsigned, unencrypted (existing default).
            match module.to_bytes() {
                Ok(b) => b,
                Err(e) => {
                    eprintln!("error: serializing bytecode: {:?}", e);
                    return ExitCode::FAILURE;
                }
            }
        }
    };
    if let Err(e) = fs::write(&output_path, &bytes) {
        eprintln!("error: writing {}: {}", output_path, e);
        return ExitCode::FAILURE;
    }
    eprintln!("wrote {} ({} bytes)", output_path, bytes.len());
    ExitCode::SUCCESS
}

/// Generate a fresh keypair for either signing (Ed25519) or
/// encryption (X25519). The two key kinds are not interchangeable:
/// signing keys authenticate code provenance; encryption keys
/// receive encrypted code. Operators typically generate both for
/// any host that participates in the encrypted delivery flow.
fn keygen_subcommand(args: &[String]) -> ExitCode {
    let mut seed_path: Option<String> = None;
    let mut pub_path: Option<String> = None;
    let mut kind = KeyKind::Signing;
    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--seed" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --seed requires a path");
                    return ExitCode::FAILURE;
                }
                seed_path = Some(args[i + 1].clone());
                i += 2;
            }
            "--public" | "--public-key" | "--verifying-key" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --public requires a path");
                    return ExitCode::FAILURE;
                }
                pub_path = Some(args[i + 1].clone());
                i += 2;
            }
            "--kind" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --kind requires either 'signing' or 'encryption'");
                    return ExitCode::FAILURE;
                }
                kind = match args[i + 1].as_str() {
                    "signing" => KeyKind::Signing,
                    "encryption" => KeyKind::Encryption,
                    other => {
                        eprintln!(
                            "error: --kind must be 'signing' or 'encryption'; got '{}'",
                            other
                        );
                        return ExitCode::FAILURE;
                    }
                };
                i += 2;
            }
            other => {
                eprintln!("error: unknown option `{}`", other);
                return ExitCode::FAILURE;
            }
        }
    }
    let seed_path = match seed_path {
        Some(p) => p,
        None => {
            eprintln!("error: keygen requires --seed <path>");
            return ExitCode::FAILURE;
        }
    };
    let pub_path = match pub_path {
        Some(p) => p,
        None => {
            eprintln!("error: keygen requires --public <path>");
            return ExitCode::FAILURE;
        }
    };
    if Path::new(&seed_path).exists() {
        eprintln!(
            "error: refusing to overwrite existing seed file {}; remove or rename first",
            seed_path
        );
        return ExitCode::FAILURE;
    }
    if Path::new(&pub_path).exists() {
        eprintln!(
            "error: refusing to overwrite existing public-key file {}; remove or rename first",
            pub_path
        );
        return ExitCode::FAILURE;
    }
    let (seed_bytes, public_bytes, kind_label) = match kind {
        KeyKind::Signing => {
            let signing_key = ed25519_dalek::SigningKey::generate(&mut rand_core::OsRng);
            let verifying_key = signing_key.verifying_key();
            (signing_key.to_bytes(), verifying_key.to_bytes(), "Ed25519")
        }
        KeyKind::Encryption => {
            // X25519 private keys can be any 32 bytes; the StaticSecret
            // constructor clamps internally per the X25519 specification.
            // We generate raw bytes from the OS RNG.
            use rand_core::RngCore;
            let mut seed = [0u8; X25519_PRIVATE_KEY_LEN];
            rand_core::OsRng.fill_bytes(&mut seed);
            let public = keleusma::encryption::public_key_from_private(&seed);
            (seed, public, "X25519")
        }
    };
    if let Err(e) = fs::write(&seed_path, seed_bytes) {
        eprintln!("error: writing seed file {}: {}", seed_path, e);
        return ExitCode::FAILURE;
    }
    if let Err(e) = fs::write(&pub_path, public_bytes) {
        eprintln!("error: writing public-key file {}: {}", pub_path, e);
        return ExitCode::FAILURE;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(e) = fs::set_permissions(&seed_path, std::fs::Permissions::from_mode(0o600)) {
            eprintln!(
                "warning: could not tighten permissions on {}: {}",
                seed_path, e
            );
        }
    }
    eprintln!(
        "wrote {} seed to {} (32 bytes; keep secret)",
        kind_label, seed_path
    );
    let public_role = match kind {
        KeyKind::Signing => "distribute to verifiers",
        KeyKind::Encryption => "distribute to compilers producing artefacts for this host",
    };
    eprintln!(
        "wrote {} public key to {} (32 bytes; {})",
        kind_label, pub_path, public_role
    );
    ExitCode::SUCCESS
}

/// Selects the cryptographic primitive family for the `keygen`
/// subcommand. Signing produces Ed25519 keypairs; encryption
/// produces X25519 keypairs.
#[derive(Debug, Clone, Copy)]
enum KeyKind {
    Signing,
    Encryption,
}

/// Read a raw 32-byte Ed25519 seed from `path` and construct a
/// `SigningKey`. Returns an error message string suitable for
/// CLI output if the file is missing, the wrong size, or
/// unreadable.
fn read_signing_key(path: &str) -> Result<ed25519_dalek::SigningKey, String> {
    let bytes = fs::read(path).map_err(|e| format!("reading signing key {}: {}", path, e))?;
    if bytes.len() != 32 {
        return Err(format!(
            "signing key file {} must be exactly 32 bytes (raw Ed25519 seed); got {} bytes",
            path,
            bytes.len()
        ));
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(&bytes);
    Ok(ed25519_dalek::SigningKey::from_bytes(&seed))
}

/// Read a raw 32-byte X25519 private key (seed) from `path`.
/// Used by the run subcommand's `--decryption-key` flag and by
/// the strict-mode decryption-key store discovery.
fn read_x25519_private_key(path: &str) -> Result<[u8; X25519_PRIVATE_KEY_LEN], String> {
    let bytes = fs::read(path).map_err(|e| format!("reading decryption key {}: {}", path, e))?;
    if bytes.len() != X25519_PRIVATE_KEY_LEN {
        return Err(format!(
            "decryption key file {} must be exactly {} bytes (raw X25519 seed); got {} bytes",
            path,
            X25519_PRIVATE_KEY_LEN,
            bytes.len()
        ));
    }
    let mut seed = [0u8; X25519_PRIVATE_KEY_LEN];
    seed.copy_from_slice(&bytes);
    Ok(seed)
}

/// Read a raw 32-byte X25519 public key from `path`. Used by the
/// compile subcommand's `--encryption-key` flag where the operator
/// supplies the destination workstation's public key.
fn read_x25519_public_key(path: &str) -> Result<[u8; X25519_PRIVATE_KEY_LEN], String> {
    let bytes = fs::read(path).map_err(|e| format!("reading encryption key {}: {}", path, e))?;
    if bytes.len() != X25519_PRIVATE_KEY_LEN {
        return Err(format!(
            "encryption key file {} must be exactly {} bytes (raw X25519 public key); got {} bytes",
            path,
            X25519_PRIVATE_KEY_LEN,
            bytes.len()
        ));
    }
    let mut key = [0u8; X25519_PRIVATE_KEY_LEN];
    key.copy_from_slice(&bytes);
    Ok(key)
}

/// Read a raw 32-byte Ed25519 public key from `path` and
/// construct a `VerifyingKey`.
fn read_verifying_key(path: &str) -> Result<ed25519_dalek::VerifyingKey, String> {
    let bytes = fs::read(path).map_err(|e| format!("reading verifying key {}: {}", path, e))?;
    if bytes.len() != 32 {
        return Err(format!(
            "verifying key file {} must be exactly 32 bytes (raw Ed25519 public key); got {} bytes",
            path,
            bytes.len()
        ));
    }
    let mut key_bytes = [0u8; 32];
    key_bytes.copy_from_slice(&bytes);
    ed25519_dalek::VerifyingKey::from_bytes(&key_bytes).map_err(|e| {
        format!(
            "verifying key {} is not a valid Ed25519 public key: {}",
            path, e
        )
    })
}

fn default_output_path(input: &str) -> String {
    let path = Path::new(input);
    if path.extension().and_then(|s| s.to_str()) == Some("kel") {
        format!("{}.bin", input)
    } else {
        format!("{}.kel.bin", input)
    }
}

fn repl_subcommand(_args: &[String]) -> ExitCode {
    println!("{}", REPL_BANNER);
    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut prefix = String::new();
    let mut input = String::new();
    // Per-session shared `.data` slot values. The REPL keeps these
    // across evaluations so a script that declares `shared data
    // state { count: Word }` and writes `state.count = state.count
    // + 1` observes the accumulated value on each invocation. The
    // slot indices are stable across evals because the REPL prefix
    // is append-only.
    //
    // KString variants are materialised to StaticStr before
    // snapshotting so the saved values do not carry stale arena
    // references after the source Vm is dropped.
    //
    // Private `.data` is not persisted here. The persistent region
    // stores `GenericValue` enum instances inline, but those
    // variants contain heap pointers (String for StaticStr, Vec for
    // Tuple, etc.) that a raw byte-copy would alias rather than
    // own. A deep-clone of the private region would require API the
    // VM does not yet expose. The REPL therefore documents private
    // data as eval-local; users wanting persistent state should
    // declare a `shared data` block.
    // The REPL's persistent shared-data buffer (B28 item 2). The buffer is
    // host-owned and lent to each evaluation; it grows and zero-extends as
    // later declarations add shared fields. Because the REPL prefix is
    // append-only, a field's byte offset is stable across evaluations, so
    // growth preserves prior fields and zero-initialises new ones.
    let mut shared_state: Vec<u8> = Vec::new();

    loop {
        {
            let mut out = stdout.lock();
            let _ = out.write_all(b"> ");
            let _ = out.flush();
        }
        input.clear();
        let bytes_read = match stdin.lock().read_line(&mut input) {
            Ok(n) => n,
            Err(e) => {
                eprintln!("error: reading input: {}", e);
                return ExitCode::FAILURE;
            }
        };
        if bytes_read == 0 {
            // EOF (Ctrl-D).
            println!();
            return ExitCode::SUCCESS;
        }
        let line = input.trim();
        if line.is_empty() {
            continue;
        }
        if let Some(stripped) = line.strip_prefix(':') {
            // Split a colon command into its verb and optional argument so
            // `:save program.kel` and `:load program.kel` carry a filename.
            let mut parts = stripped.splitn(2, char::is_whitespace);
            let cmd = parts.next().unwrap_or("");
            let arg = parts.next().map(str::trim).unwrap_or("");
            match cmd {
                "quit" | "q" | "exit" => return ExitCode::SUCCESS,
                "help" | "h" => print_repl_help(),
                "reset" => {
                    prefix.clear();
                    shared_state.clear();
                    println!("session prefix and shared data cleared");
                }
                "show" => {
                    if prefix.is_empty() {
                        println!("(empty session prefix)");
                    } else {
                        println!("{}", prefix);
                    }
                }
                "save" => repl_save(&prefix, arg),
                "load" => repl_load(&mut prefix, &mut shared_state, arg),
                "run" => repl_run(&prefix),
                other => {
                    eprintln!("error: unknown REPL command `:{}`", other);
                }
            }
            continue;
        }
        evaluate_repl_input(&mut prefix, &mut shared_state, line);
    }
}

fn print_repl_help() {
    println!("Keleusma REPL commands:");
    println!("  :help, :h               Show this help");
    println!("  :quit, :q, :exit        Exit the REPL");
    println!("  :reset                  Clear the session prefix");
    println!("  :show                   Display the current session prefix");
    println!("  :save <file>            Write the session program to a .kel file");
    println!("  :load <file>            Replace the session with a .kel file's contents");
    println!("  :run                    Run the session program; step a loop/yield main");
    println!();
    println!("Otherwise, type:");
    println!("  An expression to evaluate it (`1 + 2`, `double(21)`)");
    println!(
        "  A declaration to add to the session prefix (`fn`, `struct`, `enum`, `trait`, `impl`, `use`)"
    );
}

/// Write the accumulated session program to `path` as Keleusma source.
/// The session program is the declaration prefix the user has built up;
/// saving it produces a `.kel` file that can be `:load`ed or run directly.
fn repl_save(prefix: &str, path: &str) {
    if path.is_empty() {
        eprintln!("error: :save requires a filename, e.g. `:save program.kel`");
        return;
    }
    // Write the prefix with a trailing newline so the saved file is a
    // well-formed text file.
    let mut contents = prefix.trim_end().to_string();
    contents.push('\n');
    match std::fs::write(path, &contents) {
        Ok(()) => println!(
            "saved session to {} ({} line(s))",
            path,
            prefix.lines().count()
        ),
        Err(e) => eprintln!("error: writing {}: {}", path, e),
    }
}

/// Replace the active session with the contents of the Keleusma source
/// file at `path`. The shared-data buffer is cleared so the loaded
/// program starts from a clean state. A compile probe reports whether the
/// loaded program is well-formed, which is the per-load feedback.
fn repl_load(prefix: &mut String, shared_state: &mut Vec<u8>, path: &str) {
    if path.is_empty() {
        eprintln!("error: :load requires a filename, e.g. `:load program.kel`");
        return;
    }
    let contents = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: reading {}: {}", path, e);
            return;
        }
    };
    *prefix = contents.trim_end().to_string();
    shared_state.clear();
    // Probe the loaded program so the user sees immediately whether it
    // compiles. A program carrying its own `main` is probed as is; one
    // without is probed under a trivial `main`, matching the declaration
    // path in `evaluate_repl_input`.
    let probe = if has_main(prefix) {
        prefix.clone()
    } else {
        format!("{}\n\nfn main() -> Word {{ 0 }}\n", prefix)
    };
    match compile_source(&probe) {
        Ok(_) => println!("loaded {} ({} line(s))", path, prefix.lines().count()),
        Err(e) => eprintln!("loaded {} with errors:\n{}", path, e),
    }
}

/// Print the decoded shared-data state, one `name = value` per scalar
/// shared slot. Composite shared slots are noted rather than decoded,
/// since the per-slot host API decodes scalars only. Shared slots occupy
/// the low unified indices `[0, names.len())` (the compiler emits them
/// shared-first), so the i-th name pairs with `get_shared(buf, i)`.
fn print_shared_state(vm: &Vm, names: &[String], shared: &[u8]) {
    if names.is_empty() {
        return;
    }
    print!("  shared:");
    for (i, name) in names.iter().enumerate() {
        if i > 0 {
            print!(",");
        }
        match vm.get_shared(shared, i) {
            Ok(v) => {
                print!(" {} = ", name);
                print_value_inline(&v);
            }
            Err(_) => print!(" {} = <composite>", name),
        }
    }
    println!();
}

/// Run the session program interactively (`:run`). For a `loop`/`yield`
/// main this starts the coroutine, runs to the first yield, prints the
/// yielded value and the shared-data state, and enters a stepping
/// sub-prompt where `:resume [tick]` advances to the next yield and
/// `:stop` exits. For an atomic `fn main` it runs once and prints the
/// result. The arena and VM are locals of this scope, so the suspended
/// coroutine lives only while stepping and drops cleanly on exit; this
/// sidesteps storing a `Vm` (which borrows its `Arena`) across the outer
/// REPL loop.
fn repl_run(prefix: &str) {
    if !has_main(prefix) {
        eprintln!(
            "error: :run needs a `main`; define `loop main(tick: Word) -> Word {{ ... yield ... }}` (or `fn main`, `yield main`)"
        );
        return;
    }
    let module = match compile_source(prefix) {
        Ok(m) => m,
        Err(e) => {
            eprintln!("error: {}", e);
            return;
        }
    };
    let entry_kind = match detect_entry_kind(&module) {
        Ok(k) => k,
        Err(e) => {
            eprintln!("error: {}", e);
            return;
        }
    };
    // Capture shared field names before the module moves into the VM, so the
    // stepping sub-prompt can render the shared-data state by name. Shared
    // slots are emitted shared-first, so this order matches the get_shared
    // index space.
    let shared_names: Vec<String> = module
        .data_layout
        .as_ref()
        .map(|dl| {
            dl.slots
                .iter()
                .filter(|s| matches!(s.visibility, keleusma::bytecode::SlotVisibility::Shared))
                .map(|s| s.name.clone())
                .collect()
        })
        .unwrap_or_default();

    let persistent_bytes = keleusma::vm::required_persistent_capacity_for(&module);
    let transient_bytes =
        keleusma::vm::auto_arena_capacity_for(&module, &[]).unwrap_or(DEFAULT_ARENA_CAPACITY);
    let total = (persistent_bytes + transient_bytes).max(DEFAULT_ARENA_CAPACITY);
    let mut arena = Arena::with_capacity(total);
    if let Err(e) = arena.resize_persistent(persistent_bytes) {
        eprintln!("error: arena: resize_persistent: {:?}", e);
        return;
    }
    let mut vm = match Vm::new(module, &arena) {
        Ok(v) => v,
        Err(e) => {
            eprintln!("error: verify: {:?}", e);
            return;
        }
    };
    register_repl_natives(&mut vm);
    let mut shared = vec![0u8; vm.shared_data_bytes()];

    // Atomic fn: run once and print the result; no stepping.
    if matches!(entry_kind, EntryKind::AtomicFn) {
        match vm.call_with_shared(&mut shared, &[]) {
            Ok(VmState::Finished(v)) => {
                print!("=> ");
                print_value_inline_ctx(&v, &arena);
                println!();
            }
            Ok(other) => eprintln!("error: fn main did not finish cleanly: {:?}", other),
            Err(e) => eprintln!("error: vm: {:?}", e),
        }
        return;
    }

    // Stream stepping for loop/yield main. Run to the first yield, drive
    // transparently through `Reset` boundaries (the loop re-entry the VM
    // surfaces between iterations), and read :resume/:stop from a sub-prompt.
    // Tick convention: the loop yields a Word and the next resume value is
    // that Word + 1.
    println!(
        "stepping {}; :resume [tick] to advance, :stop to exit",
        match entry_kind {
            EntryKind::LoopMain => "loop main",
            EntryKind::YieldMain => "yield main",
            EntryKind::AtomicFn => "fn main",
        }
    );
    let stdin = io::stdin();
    let mut tick: i64 = 1;
    let mut state = match vm.call_with_shared(&mut shared, &[Value::Int(tick)]) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: vm: {:?}", e);
            return;
        }
    };
    loop {
        // Drive through Reset boundaries to the next yield or finish, so one
        // :resume always advances to the next yielded value rather than to an
        // intermediate loop re-entry. Resets resume with the current tick.
        while matches!(state, VmState::Reset) {
            state = match vm.resume_with_shared(&mut shared, Value::Int(tick)) {
                Ok(s) => s,
                Err(e) => {
                    eprintln!("error: vm: {:?}", e);
                    return;
                }
            };
        }
        // Present the current state once.
        match &state {
            VmState::Yielded(v) => {
                print!("yield => ");
                print_value_inline_ctx(v, &arena);
                println!();
                print_shared_state(&vm, &shared_names, &shared);
                tick = if let Value::Int(n) = v {
                    n.wrapping_add(1)
                } else {
                    tick.wrapping_add(1)
                };
            }
            VmState::Finished(v) => {
                print!("finished => ");
                print_value_inline_ctx(v, &arena);
                println!();
                print_shared_state(&vm, &shared_names, &shared);
                return;
            }
            VmState::BreakpointHit { chunk, op } => {
                eprintln!("error: unexpected breakpoint at chunk {} op {}", chunk, op);
                return;
            }
            VmState::Reset => unreachable!("reset states are drained above"),
        }
        // Sub-prompt: read commands until a :resume produces the next state.
        let next = loop {
            print!("loop> ");
            let _ = io::stdout().flush();
            let mut line = String::new();
            match stdin.lock().read_line(&mut line) {
                Ok(0) => {
                    println!();
                    return;
                }
                Ok(_) => {}
                Err(e) => {
                    eprintln!("error: reading input: {}", e);
                    return;
                }
            }
            let cmd = line.trim();
            let body = cmd.strip_prefix(':').unwrap_or(cmd);
            let mut it = body.splitn(2, char::is_whitespace);
            let verb = it.next().unwrap_or("");
            let arg = it.next().map(str::trim).unwrap_or("");
            match verb {
                "" | "resume" | "r" | "step" | "s" => {
                    if !arg.is_empty() {
                        match arg.parse::<i64>() {
                            Ok(n) => tick = n,
                            Err(_) => {
                                eprintln!("error: :resume expects an integer tick; got `{}`", arg);
                                continue;
                            }
                        }
                    }
                    match vm.resume_with_shared(&mut shared, Value::Int(tick)) {
                        Ok(s) => break s,
                        Err(e) => {
                            eprintln!("error: vm: {:?}", e);
                            return;
                        }
                    }
                }
                "stop" | "quit" | "q" | "exit" => {
                    println!("stopped stepping");
                    return;
                }
                "shared" => print_shared_state(&vm, &shared_names, &shared),
                "help" | "h" => {
                    println!("stepping commands:");
                    println!(
                        "  :resume [tick]   advance to the next yield (default = last yield + 1)"
                    );
                    println!("  :shared          re-print the shared-data state");
                    println!("  :stop            exit stepping, back to the REPL");
                }
                other => eprintln!(
                    "unknown stepping command `:{}`; :resume to step, :stop to exit",
                    other
                ),
            }
        };
        state = next;
    }
}

/// Decide whether a REPL line is a declaration (added to the prefix)
/// or an expression (evaluated against the prefix).
fn is_declaration(line: &str) -> bool {
    let starters = [
        "fn ",
        "yield ",
        "loop ",
        "struct ",
        "enum ",
        "trait ",
        "impl ",
        "use ",
        "data ",
        "shared data ",
        "private data ",
        "const data ",
        "signed fn ",
        "signed yield ",
        "signed loop ",
        "ephemeral fn ",
        "ephemeral yield ",
        "ephemeral loop ",
        "newtype ",
    ];
    starters.iter().any(|s| line.starts_with(s))
}

fn evaluate_repl_input(prefix: &mut String, shared_state: &mut Vec<u8>, line: &str) {
    if is_declaration(line) {
        // Tentatively append; verify it parses and compiles within
        // the prefix before committing.
        let candidate = format!("{}\n{}", prefix.trim_end(), line);
        let candidate = candidate.trim().to_string();
        // Add a trivial main if the prefix lacks one so compilation
        // can proceed. The trivial main is dropped before commit.
        let probe = if has_main(&candidate) {
            candidate.clone()
        } else {
            format!("{}\n\nfn main() -> Word {{ 0 }}\n", candidate)
        };
        match compile_source(&probe) {
            Ok(_) => {
                *prefix = candidate;
                if let Some(name) = extract_decl_name(line) {
                    println!("defined: {}", name);
                } else {
                    println!("declaration accepted");
                }
            }
            Err(e) => {
                eprintln!("error: {}", e);
            }
        }
        return;
    }

    // Try two wrapper shapes in order. The expression wrapper
    // routes the line through `println` so any expression value
    // renders through the CLI's recursive value formatter. The
    // statement wrapper drops the line into a function body
    // verbatim, terminated by `; 0`, so statement-shaped input
    // (mutating `shared data` fields, calling void-returning
    // natives, and so on) executes without forcing a parseable
    // expression position. The expression wrapper is preferred
    // because it auto-prints; the statement wrapper is the
    // fallback for input the expression wrapper cannot parse.
    let expr_form = format!(
        "use println\n{}\n\nfn main() -> Word {{\n    let _ = println({});\n    0\n}}\n",
        prefix.trim_end(),
        line
    );
    match execute_source_repl_silent(&expr_form, shared_state) {
        Ok(()) => {}
        Err(expr_err) => {
            let stmt_form = format!(
                "{}\n\nfn main() -> Word {{\n    {};\n    0\n}}\n",
                prefix.trim_end(),
                line
            );
            match execute_source_repl_silent(&stmt_form, shared_state) {
                Ok(()) => {}
                Err(_) => {
                    // Both wrappers failed. Surface the expression
                    // wrapper's error because it gives a better
                    // diagnostic for typical REPL input.
                    eprintln!("error: {}", expr_err);
                }
            }
        }
    }
}

fn has_main(source: &str) -> bool {
    // Very rough heuristic: look for "fn main", "yield main", or
    // "loop main" at the start of any line. Sufficient for REPL
    // pipelining where users either declare a main themselves or
    // expect the REPL to wrap.
    source.lines().any(|line| {
        let trimmed = line.trim_start();
        trimmed.starts_with("fn main")
            || trimmed.starts_with("yield main")
            || trimmed.starts_with("loop main")
    })
}

fn extract_decl_name(line: &str) -> Option<String> {
    // For declarations, extract the name following the keyword. Used
    // for the REPL "defined: name" feedback.
    let mut tokens = line.split_whitespace();
    let kw = tokens.next()?;
    let name = match kw {
        "fn" | "yield" | "loop" | "struct" | "enum" | "trait" | "data" => {
            let next = tokens.next()?;
            // The name may have boundary characters (`(`, `<`, `{`,
            // `:`) attached without a space. Split at the first such
            // character and take the prefix.
            let end = next.find(['(', '<', '{', ':']).unwrap_or(next.len());
            next[..end].to_string()
        }
        "impl" => {
            // `impl Trait for Type { ... }` -- show "impl Trait for Type".
            let rest = tokens.collect::<Vec<&str>>().join(" ");
            let head = rest.split('{').next().unwrap_or(&rest).trim().to_string();
            format!("impl {}", head)
        }
        "use" => {
            let next = tokens.next()?;
            format!("use {}", next.trim_end_matches([';', ','].as_ref()))
        }
        _ => return None,
    };
    Some(name)
}

/// Compile a complete source program through the standard pipeline,
/// returning either the resulting `Module` or a stringified error
/// with location information.
/// Native signatures the CLI registers on the VM beyond the
/// bundled libraries. Composed with `stddsl::Shell::SIGNATURES`
/// to form the full preamble prepended to every script source
/// before parsing. The names match the closures registered in
/// `drive_to_completion`.
const CLI_NATIVE_SIGNATURES: &str = concat!(
    "use shell::set_tick_interval(Text) -> ()\n",
    "use shell::tick_interval() -> Text\n",
);

/// Concatenate the source-form signature preambles the CLI
/// always installs (Shell bundle plus the CLI-specific
/// tick-interval natives) ahead of the user-supplied source. The
/// prepended `use` declarations register native signatures in the
/// type checker so qualified call sites such as
/// `shell::sleep_ms(500)` are validated at compile time.
fn build_preamble() -> String {
    let mut s = String::new();
    s.push_str(stddsl::Math::SIGNATURES);
    s.push_str(stddsl::Audio::SIGNATURES);
    s.push_str(stddsl::Shell::SIGNATURES);
    s.push_str(CLI_NATIVE_SIGNATURES);
    s
}

/// Count the lines occupied by the preamble. Used by
/// [`format_err`] to subtract the preamble's contribution to
/// error line numbers so operators see line positions in the
/// user-visible source rather than the combined post-preamble
/// source.
fn preamble_line_count() -> u32 {
    build_preamble().bytes().filter(|b| *b == b'\n').count() as u32
}

/// Core of `keleusma strip`: load a plain (unsigned, unencrypted)
/// bytecode buffer, drop every chunk's debug metadata section, and
/// re-encode. The result is byte-identical to a release build compiled
/// without `--debug` (B29 invariant 5). Factored out for testing.
fn strip_module_bytes(bytes: &[u8]) -> Result<Vec<u8>, String> {
    let mut module = keleusma::bytecode::Module::from_bytes(bytes)
        .map_err(|e| format!("reading bytecode: {:?}", e))?;
    for chunk in &mut module.chunks {
        chunk.debug_pool = None;
    }
    module
        .to_bytes()
        .map_err(|e| format!("encoding stripped bytecode: {:?}", e))
}

/// `strip <input.bin> [-o <output.bin>]`. Removes B29 debug metadata
/// from a compiled bytecode artefact. Output defaults to the input path
/// (in place). Signed or encrypted artefacts are refused: stripping
/// rewrites the body, which invalidates a signature, and the stripper
/// holds no key. The supported workflow is compile, then strip, then
/// sign.
fn strip_subcommand(args: &[String]) -> ExitCode {
    if args.is_empty() {
        eprintln!("error: `strip` requires a bytecode path");
        return ExitCode::FAILURE;
    }
    let input = &args[0];
    let mut output: Option<String> = None;
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "-o" | "--output" => {
                if i + 1 >= args.len() {
                    eprintln!("error: --output requires a path");
                    return ExitCode::FAILURE;
                }
                output = Some(args[i + 1].clone());
                i += 2;
            }
            other => {
                eprintln!("error: unknown option `{}`", other);
                return ExitCode::FAILURE;
            }
        }
    }
    let bytes = match fs::read(input) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("error: reading {}: {}", input, e);
            return ExitCode::FAILURE;
        }
    };
    if keleusma::wire_format::header_requires_signature(&bytes)
        || keleusma::wire_format::header_requires_encryption(&bytes)
    {
        eprintln!(
            "error: cannot strip a signed or encrypted artefact; stripping rewrites the body and invalidates the signature. Strip before signing: compile, then strip, then sign."
        );
        return ExitCode::FAILURE;
    }
    let stripped = match strip_module_bytes(&bytes) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("error: {}", e);
            return ExitCode::FAILURE;
        }
    };
    let out_path = output.unwrap_or_else(|| input.clone());
    match fs::write(&out_path, &stripped) {
        Ok(()) => {
            eprintln!(
                "stripped {} -> {} ({} bytes)",
                input,
                out_path,
                stripped.len()
            );
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: writing {}: {}", out_path, e);
            ExitCode::FAILURE
        }
    }
}

fn compile_source(source: &str) -> Result<keleusma::bytecode::Module, String> {
    compile_source_with_target(source, None, false)
}

/// Compile the source through the standard pipeline, routing
/// through [`compile_with_target`] when an explicit target is
/// provided so the compiler validates the program against the
/// target's word, address, and float widths before emitting.
fn compile_source_with_target(
    source: &str,
    target: Option<&keleusma::target::Target>,
    emit_debug: bool,
) -> Result<keleusma::bytecode::Module, String> {
    let mut combined = build_preamble();
    // A script may begin with a `#!/usr/bin/env keleusma` shebang so it
    // is directly executable. The lexer skips a shebang only when it is
    // at byte 0, but the preamble prepended here displaces it, so strip
    // the shebang line before appending the source. A blank line is
    // left in its place to keep source line numbers unchanged for
    // error reporting.
    if let Some(rest) = source.strip_prefix("#!") {
        match rest.find('\n') {
            Some(nl) => {
                combined.push('\n');
                combined.push_str(&rest[nl + 1..]);
            }
            None => {
                // The source is only a shebang line with no body.
            }
        }
    } else {
        combined.push_str(source);
    }
    let preamble_lines = preamble_line_count();
    let tokens = tokenize(&combined)
        .map_err(|e| format_err_with_offset("lex", &e.message, e.span, preamble_lines))?;
    let program = parse(&tokens)
        .map_err(|e| format_err_with_offset("parse", &e.message, e.span, preamble_lines))?;
    // Resolve the target. Absent `--target`, compile for the host,
    // which is what the bare `compile` entry point does.
    let host_target;
    let resolved_target = match target {
        Some(t) => t,
        None => {
            host_target = keleusma::target::Target::host();
            &host_target
        }
    };
    let options = CompileOptions { emit_debug };
    let (module, _warnings) = compile_with_options(&program, resolved_target, &options)
        .map_err(|e| format_err_with_offset("compile", &e.message, e.span, preamble_lines))?;
    Ok(module)
}

/// Resolve a CLI `--target` argument to a [`Target`] preset.
fn parse_target_name(name: &str) -> Result<keleusma::target::Target, String> {
    match name {
        "host" => Ok(keleusma::target::Target::host()),
        "wasm32" => Ok(keleusma::target::Target::wasm32()),
        "embedded_32" => Ok(keleusma::target::Target::embedded_32()),
        "embedded_16" => Ok(keleusma::target::Target::embedded_16()),
        "embedded_8" => Ok(keleusma::target::Target::embedded_8()),
        other => Err(format!(
            "unknown target `{}`; expected one of: host, wasm32, embedded_32, embedded_16, embedded_8",
            other
        )),
    }
}

/// Worst-case arena byte sizing for `module`: the persistent (`.data`)
/// region, the transient stream-iteration region, and the total floored at
/// the working minimum. The total is the arena the runner allocates.
fn module_arena_sizing(module: &keleusma::bytecode::Module) -> (usize, usize, usize) {
    let persistent = keleusma::vm::required_persistent_capacity_for(module);
    let transient =
        keleusma::vm::auto_arena_capacity_for(module, &[]).unwrap_or(DEFAULT_ARENA_CAPACITY);
    let total = (persistent + transient).max(DEFAULT_ARENA_CAPACITY);
    (persistent, transient, total)
}

/// Allocate the worst-case arena for `module` and size its persistent
/// region. An out-of-memory condition becomes a returned `Err` -- surfaced
/// by the caller as a diagnostic and a non-zero exit -- rather than the
/// default `handle_alloc_error` abort. This is the memory-pressure
/// robustness point: a host that cannot provide the program's bounded arena
/// fails actionably rather than with `SIGABRT`.
fn allocate_module_arena(module: &keleusma::bytecode::Module) -> Result<Arena, String> {
    let (persistent, _transient, total) = module_arena_sizing(module);
    let mut arena = Arena::try_with_capacity(total).map_err(|_| {
        format!("out of memory: this program needs a {total}-byte arena, which this host cannot allocate")
    })?;
    arena
        .resize_persistent(persistent)
        .map_err(|e| format!("arena: resize_persistent: {:?}", e))?;
    Ok(arena)
}

/// Print the worst-case arena footprint for `module` to stdout. Backs
/// `run --print-memory`, so an operator can size or qualify a host before
/// deploying, turning the static worst-case-memory bound into an
/// operational figure.
fn print_module_memory(module: &keleusma::bytecode::Module) {
    let (persistent, transient, total) = module_arena_sizing(module);
    println!("arena: {total} bytes total (persistent {persistent}, transient {transient})");
}

/// Run a source program through compile and execute. The runner
/// pre-registers utility and math natives so scripts can use
/// `to_string`, `length`, `concat`, `slice`, `println`, and the
/// `math::*` family without explicit registration.
fn execute_source(
    source: &str,
    loop_config: &LoopRunnerConfig,
    print_memory: bool,
) -> Result<(), String> {
    let module = compile_source(source)?;
    if print_memory {
        print_module_memory(&module);
        return Ok(());
    }
    let entry_kind = detect_entry_kind(&module)?;
    let arena = allocate_module_arena(&module)?;
    let mut vm = Vm::new(module, &arena).map_err(|e| format!("verify: {:?}", e))?;
    drive_to_completion(&mut vm, &arena, entry_kind, loop_config)
}

/// REPL-specific source execution that uses the fixed
/// [`DEFAULT_ARENA_CAPACITY`] instead of auto-sizing per
/// expression. The REPL evaluates ad-hoc expressions whose WCMU
/// bounds are meaningless; auto-sizing would resize the arena on
/// every input. The fixed capacity is the right behaviour for
/// interactive use.
/// REPL expression execution. Suppresses the printing of the
/// wrapper's terminal return value because the REPL wrapper
/// returns a sentinel `Word 0` purely to satisfy the entry-point
/// signature; the actual value the operator wants to see is
/// printed earlier by the wrapper's call to `println(expr)`.
fn execute_source_repl_silent(source: &str, shared_state: &mut Vec<u8>) -> Result<(), String> {
    let module = compile_source(source)?;
    let entry_kind = detect_entry_kind(&module)?;
    if !matches!(entry_kind, EntryKind::AtomicFn) {
        // Non-atomic entries are user declarations, not REPL
        // expressions; fall back to the printing path so the
        // operator sees whatever the script produces. No shared-
        // data restore here because the REPL only persists state
        // through the atomic-fn-main expression path.
        let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
        let mut vm = Vm::new(module, &arena).map_err(|e| format!("verify: {:?}", e))?;
        return drive_to_completion(&mut vm, &arena, entry_kind, &LoopRunnerConfig::default());
    }
    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
    let mut vm = Vm::new(module, &arena).map_err(|e| format!("verify: {:?}", e))?;
    register_repl_natives(&mut vm);

    // Resize the persistent shared buffer to this module's flat layout and
    // lend it to the run (B28 item 2). The REPL prefix is append-only, so a
    // shared field's byte offset is stable across evaluations; `resize`
    // preserves prior fields' bytes and zero-initialises newly declared
    // fields, matching the prior slot model's "new slots keep their default
    // initial values". The run mutates the buffer in place, so on return it
    // already holds the next round's shared state -- no snapshot pass, and no
    // arena handles to materialise, because the buffer is pure bytes.
    shared_state.resize(vm.shared_data_bytes(), 0);
    let result = vm
        .call_with_shared(shared_state.as_mut_slice(), &[])
        .map_err(|e| format!("vm: {:?}", e))?;

    match result {
        VmState::Finished(_) => Ok(()),
        VmState::Yielded(v) => Err(format!("REPL wrapper yielded unexpectedly: {:?}", v)),
        VmState::Reset => Err(String::from("REPL wrapper reset unexpectedly")),
        VmState::BreakpointHit { chunk, op } => Err(format!(
            "REPL wrapper hit a breakpoint at chunk {} op {} unexpectedly",
            chunk, op
        )),
    }
}

/// Register the same natives that `drive_to_completion` would
/// register, omitting the loop-runner-only `shell::set_tick_interval`
/// and `shell::tick_interval` natives since REPL expressions do
/// not need them.
fn register_repl_natives<'a, 'arena>(vm: &mut Vm<'a, 'arena>) {
    vm.register_native_with_ctx_closure("println", |ctx, args| {
        if let Some(arg) = args.first() {
            print_value_inline_ctx(arg, ctx.arena);
        }
        println!();
        Ok(Value::Unit)
    });
    vm.register_library(stddsl::Math);
    vm.register_library(stddsl::Audio);
    vm.register_library(stddsl::Shell);
    // Tick-interval natives are still registered as no-op stubs
    // so REPL expressions that mention them by qualified path do
    // not trap at runtime.
    let stub_interval: Arc<AtomicU64> = Arc::new(AtomicU64::new(0));
    let s1 = stub_interval.clone();
    vm.register_native_closure("shell::set_tick_interval", move |args| {
        let arg = args.first().ok_or_else(|| {
            keleusma::vm::VmError::NativeError(String::from(
                "shell::set_tick_interval: expected one Text argument",
            ))
        })?;
        let s: &str = match arg {
            Value::StaticStr(s) => s.as_str(),
            other => {
                return Err(keleusma::vm::VmError::TypeError(format!(
                    "shell::set_tick_interval: expected Text, got {:?}",
                    other
                )));
            }
        };
        let dur = duration::parse(s).map_err(keleusma::vm::VmError::NativeError)?;
        s1.store(dur.as_nanos() as u64, Ordering::Relaxed);
        Ok(Value::Unit)
    });
    let s2 = stub_interval;
    vm.register_native_closure("shell::tick_interval", move |_args| {
        let nanos = s2.load(Ordering::Relaxed);
        let dur = Duration::from_nanos(nanos);
        Ok(Value::StaticStr(duration::format(dur)))
    });
}

fn execute_bytecode(
    bytes: &[u8],
    verifying_keys: &[ed25519_dalek::VerifyingKey],
    decryption_keys: &[[u8; X25519_PRIVATE_KEY_LEN]],
    policy: &PolicyContext,
    loop_config: &LoopRunnerConfig,
    print_memory: bool,
) -> Result<(), String> {
    let signed = keleusma::wire_format::header_requires_signature(bytes);
    let encrypted = keleusma::wire_format::header_requires_encryption(bytes);

    // In strict signing mode, unsigned bytecode is rejected
    // regardless of how it would normally load.
    if policy.strict_signing && !signed {
        return Err(String::from("strict mode: unsigned bytecode disabled"));
    }

    // In strict encryption mode, unencrypted bytecode is rejected
    // regardless of how it would normally load.
    if policy.strict_encryption && !encrypted {
        return Err(String::from("strict mode: unencrypted bytecode disabled"));
    }

    // Parse the Module first so we can inspect the entry chunk's
    // block type. This allows the runner to choose between the
    // atomic-fn-main path and the productive-divergent loop-main
    // path based on the script's signature.
    let module = load_module(bytes, verifying_keys, decryption_keys, policy)?;

    if print_memory {
        print_module_memory(&module);
        return Ok(());
    }

    // Auto-size the arena from the module's declared bounds and allocate it
    // fallibly, so a host that cannot provide the program's bounded arena
    // fails with a diagnostic rather than aborting.
    let arena = allocate_module_arena(&module)?;

    // Determine the script's entry-block kind. Loop main is driven
    // through the tick-counter convention; atomic fn main runs to
    // completion in a single call.
    let entry_kind = detect_entry_kind(&module)?;

    // Construct the VM. The module was parsed with the policy
    // checks already applied; signature verification (if signed)
    // happened during load_module. The flag is cleared in
    // load_module so Vm::new accepts the module without further
    // checks.
    let mut vm = Vm::new(module, &arena).map_err(|e| format!("verify: {:?}", e))?;
    for key in verifying_keys {
        vm.register_verifying_key(*key);
    }

    drive_to_completion(&mut vm, &arena, entry_kind, loop_config)
}

/// Configuration for the productive-divergent loop runner.
/// `tick_interval_nanos` zero means "no sleep between iterations"
/// (default). Non-zero values activate the rate-limiter with
/// drift compensation. `quiet` suppresses the stderr warning that
/// fires when an iteration exceeds the configured interval.
#[derive(Debug, Clone, Default)]
struct LoopRunnerConfig {
    /// Tick interval, shared with the `shell::set_tick_interval`
    /// and `shell::tick_interval` natives via `Arc<AtomicU64>`.
    /// Stored as nanoseconds. Zero means "no sleep between
    /// iterations" (current default behaviour).
    tick_interval_nanos: Arc<AtomicU64>,
    /// Suppress the stderr warning that fires when an iteration
    /// exceeds the configured interval. Default false (warnings
    /// emitted).
    quiet: bool,
}

/// Outcome of inspecting the loaded module's entry chunk. Drives
/// the dispatch between the three runner shapes.
#[derive(Debug, Clone, Copy)]
enum EntryKind {
    /// Atomic total function. Runs to completion in a single
    /// `vm.call(&[])` invocation. Returns a `Value::Finished`.
    AtomicFn,
    /// Non-atomic total function (`yield main`). Driven by the
    /// tick-counter convention. Terminates when the function
    /// returns (`VmState::Finished`) rather than yielding.
    YieldMain,
    /// Productive divergent loop. Driven by the tick-counter
    /// convention. Terminates only on `shell::exit(code)` or
    /// SIGINT.
    LoopMain,
}

fn detect_entry_kind(module: &keleusma::bytecode::Module) -> Result<EntryKind, String> {
    let entry_idx = module
        .entry_point
        .ok_or_else(|| String::from("module has no entry point; cannot determine entry kind"))?;
    let entry = module
        .chunks
        .get(entry_idx)
        .ok_or_else(|| format!("entry_point {} out of bounds", entry_idx))?;
    use keleusma::bytecode::BlockType;
    match entry.block_type {
        BlockType::Func => {
            if entry.param_count != 0 {
                return Err(format!(
                    "fn main: CLI runner expects zero parameters; got {}",
                    entry.param_count
                ));
            }
            Ok(EntryKind::AtomicFn)
        }
        BlockType::Stream => {
            if entry.param_count != 1 {
                return Err(format!(
                    "loop main: CLI runner expects exactly one parameter (tick: Word); got {}",
                    entry.param_count
                ));
            }
            Ok(EntryKind::LoopMain)
        }
        BlockType::Reentrant => {
            if entry.param_count != 1 {
                return Err(format!(
                    "yield main: CLI runner expects exactly one parameter (tick: Word); got {}",
                    entry.param_count
                ));
            }
            Ok(EntryKind::YieldMain)
        }
    }
}

/// Parse a Module from the on-disk bytes, applying the policy
/// gates for signature verification and decryption. Returns the
/// Module with the FLAG_REQUIRES_SIGNATURE flag cleared so the
/// caller can construct a Vm without the signed-module gate
/// triggering.
pub(crate) fn load_module(
    bytes: &[u8],
    verifying_keys: &[ed25519_dalek::VerifyingKey],
    decryption_keys: &[[u8; X25519_PRIVATE_KEY_LEN]],
    policy: &PolicyContext,
) -> Result<keleusma::bytecode::Module, String> {
    let signed = keleusma::wire_format::header_requires_signature(bytes);
    let encrypted = keleusma::wire_format::header_requires_encryption(bytes);

    if encrypted {
        if decryption_keys.is_empty() {
            return Err(String::from(
                "encrypted bytecode requires --decryption-key or an enrolled decryption-key store",
            ));
        }
        // Try each decryption key. A key whose `recipient_key_id` does not
        // match the artefact produces `WrongRecipient`; a key that decrypts
        // the artefact but whose embedded signature is not from an enrolled
        // verifying key produces `InvalidSignature`. Those two failures mean
        // very different things to an operator -- a key-set problem versus an
        // untrusted-provenance problem -- so they are reported distinctly
        // rather than both as "no decryption key matches".
        let mut last_err: Option<keleusma::bytecode::LoadError> = None;
        let mut signature_rejected = false;
        for key in decryption_keys {
            match keleusma::wire_format::decrypt_encrypted_signed_to_signed_bytes(
                bytes,
                verifying_keys,
                key,
            ) {
                Ok(plaintext) => {
                    let mut module = keleusma::bytecode::Module::from_bytes(&plaintext)
                        .map_err(|e| format!("decoded module: {:?}", e))?;
                    // Clear the signed flag so Vm::new accepts the
                    // module; signature verification already
                    // happened inside decrypt_encrypted_signed_to_signed_bytes.
                    module.flags &= !keleusma::wire_format::FLAG_REQUIRES_SIGNATURE;
                    return Ok(module);
                }
                Err(e) => {
                    // An `InvalidSignature` means a key did decrypt the
                    // artefact, so the failure is provenance, not the key set.
                    if matches!(e, keleusma::bytecode::LoadError::InvalidSignature) {
                        signature_rejected = true;
                    }
                    last_err = Some(e);
                }
            }
        }
        let err = last_err.expect("at least one key attempted");
        Err(if policy.strict_encryption {
            if signature_rejected {
                String::from(
                    "strict mode: artefact decrypted but its signature is not from an enrolled key (InvalidSignature)",
                )
            } else {
                format!(
                    "strict mode: no enrolled decryption key matches the artefact ({:?})",
                    err
                )
            }
        } else {
            format!("decrypt_encrypted_signed_to_signed_bytes: {:?}", err)
        })
    } else if signed {
        keleusma::wire_format::verify_module_signature(bytes, verifying_keys).map_err(|e| {
            if policy.strict_signing {
                format!(
                    "strict mode: signature does not match any enrolled key ({:?})",
                    e
                )
            } else {
                format!("verify_module_signature: {:?}", e)
            }
        })?;
        let mut module = keleusma::bytecode::Module::from_bytes(bytes)
            .map_err(|e| format!("module: {:?}", e))?;
        module.flags &= !keleusma::wire_format::FLAG_REQUIRES_SIGNATURE;
        Ok(module)
    } else {
        if !verifying_keys.is_empty() {
            return Err(String::from(
                "--verifying-key supplied but the bytecode does not carry FLAG_REQUIRES_SIGNATURE",
            ));
        }
        if !decryption_keys.is_empty() {
            return Err(String::from(
                "--decryption-key supplied but the bytecode does not carry FLAG_ENCRYPTED",
            ));
        }
        keleusma::bytecode::Module::from_bytes(bytes).map_err(|e| format!("module: {:?}", e))
    }
}

fn drive_to_completion(
    vm: &mut Vm,
    arena: &Arena,
    entry_kind: EntryKind,
    config: &LoopRunnerConfig,
) -> Result<(), String> {
    // Register the standard DSL bundles on every CLI-driven script.
    // Hosts that embed the library directly choose which libraries
    // to register; the CLI registers all of them so scripts run
    // from the command line have access to math, audio, shell, and
    // the bundled utility natives by default.
    keleusma::utility_natives::register_utility_natives(vm);
    // Override the bundled println with one that writes to stdout.
    // The library default is a no-op suitable for no_std hosts; the
    // CLI is std-only and benefits from real output.
    vm.register_native_with_ctx_closure("println", |ctx, args| {
        if let Some(arg) = args.first() {
            print_value_inline_ctx(arg, ctx.arena);
        }
        println!();
        Ok(Value::Unit)
    });
    vm.register_library(stddsl::Math);
    vm.register_library(stddsl::Audio);
    vm.register_library(stddsl::Shell);

    // CLI-specific tick-interval natives sharing the host-side
    // atomic. Registered after the Shell library so the names
    // (shell::set_tick_interval and shell::tick_interval) are
    // logical extensions of the Shell namespace. The atomic is
    // cloned into each closure.
    let interval_for_set = config.tick_interval_nanos.clone();
    vm.register_native_closure("shell::set_tick_interval", move |args| {
        let arg = args.first().ok_or_else(|| {
            keleusma::vm::VmError::NativeError(String::from(
                "shell::set_tick_interval: expected one Text argument",
            ))
        })?;
        let s: &str = match arg {
            Value::StaticStr(s) => s.as_str(),
            other => {
                return Err(keleusma::vm::VmError::TypeError(format!(
                    "shell::set_tick_interval: expected Text, got {:?}",
                    other
                )));
            }
        };
        let dur = duration::parse(s).map_err(keleusma::vm::VmError::NativeError)?;
        interval_for_set.store(dur.as_nanos() as u64, Ordering::Relaxed);
        Ok(Value::Unit)
    });
    let interval_for_get = config.tick_interval_nanos.clone();
    vm.register_native_closure("shell::tick_interval", move |_args| {
        let nanos = interval_for_get.load(Ordering::Relaxed);
        let dur = Duration::from_nanos(nanos);
        Ok(Value::StaticStr(duration::format(dur)))
    });

    match entry_kind {
        EntryKind::AtomicFn => drive_atomic_fn(vm, arena),
        EntryKind::YieldMain => drive_yield_main(vm, arena, config),
        EntryKind::LoopMain => drive_loop_main(vm, arena, config),
    }
}

/// Drive an `fn main()` to completion in a single call. Prints the
/// returned value and returns. Yielded or Reset states from an
/// atomic fn are unexpected and produce an error.
fn drive_atomic_fn(vm: &mut Vm, arena: &Arena) -> Result<(), String> {
    // Lend the script a zeroed host-owned shared-data buffer for this run
    // (B28 item 2). A module with no shared data needs a zero-length buffer,
    // for which `call_with_shared` behaves exactly like `call`.
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    match vm
        .call_with_shared(&mut shared, &[])
        .map_err(|e| format!("vm: {:?}", e))?
    {
        VmState::Finished(v) => {
            print_value(&v, arena);
            Ok(())
        }
        VmState::Yielded(v) => Err(format!(
            "fn main yielded unexpectedly (atomic fn should run to completion): {:?}",
            v
        )),
        VmState::Reset => Err(String::from(
            "fn main reset unexpectedly (atomic fn should run to completion)",
        )),
        VmState::BreakpointHit { chunk, op } => Err(format!(
            "fn main hit a breakpoint at chunk {} op {}; the CLI does not arm breakpoints",
            chunk, op
        )),
    }
}

/// Drive a `loop main(tick: Word) -> Word` indefinitely. Termination
/// happens only when the script calls `shell::exit(code)` (which
/// terminates the process via `std::process::exit`) or when the OS
/// delivers SIGINT (which terminates the process via the default
/// signal disposition).
///
/// Tick mechanics per the V0.2.1 convention:
/// - Initial call passes tick = 1.
/// - Script yields a `Word` value.
/// - Host computes `next_tick = yielded_value.wrapping_add(1)`.
/// - Host resumes with `Value::Int(next_tick)`.
/// - Yield value 0 produces next_tick 1 (reset-equivalent).
/// - Yield value `Word::MAX` produces next_tick 0 (overflow indicator).
///
/// Reset events (script triggers `Op::Reset`) are transparent to
/// the tick mechanism. The arena is cleared by the VM; the host
/// continues to the next iteration with the current tick state
/// preserved.
fn drive_loop_main(vm: &mut Vm, _arena: &Arena, config: &LoopRunnerConfig) -> Result<(), String> {
    let mut tick: i64 = 1;
    let mut iteration_start = Instant::now();
    // One host-owned shared buffer for the whole stream; the script reads and
    // writes it in place each tick, so shared state persists across resumes
    // (B28 item 2). Zero-length when the module has no shared data.
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    let mut state = vm
        .call_with_shared(&mut shared, &[Value::Int(tick)])
        .map_err(|e| format!("vm: {:?}", e))?;
    loop {
        match state {
            VmState::Finished(v) => {
                return Err(format!(
                    "loop main finished unexpectedly (productive divergent loops should never return): {:?}",
                    v
                ));
            }
            VmState::Yielded(v) => {
                let elapsed = iteration_start.elapsed();
                // The yielded value must be a Word per the loop
                // main signature. Anything else is an error.
                let yielded = match v {
                    Value::Int(n) => n,
                    other => {
                        return Err(format!(
                            "loop main yielded a non-Word value (signature requires Word): {:?}",
                            other
                        ));
                    }
                };
                tick = yielded.wrapping_add(1);
                apply_tick_interval(elapsed, config);
                iteration_start = Instant::now();
                state = vm
                    .resume_with_shared(&mut shared, Value::Int(tick))
                    .map_err(|e| format!("vm: {:?}", e))?;
            }
            VmState::BreakpointHit { chunk, op } => {
                return Err(format!(
                    "loop main hit a breakpoint at chunk {} op {}; the CLI does not arm breakpoints",
                    chunk, op
                ));
            }
            VmState::Reset => {
                // The script triggered a Reset (Op::Reset). The VM
                // has cleared the transient arena region; the
                // persistent .data section is preserved. Continue
                // the loop with the current tick state. Apply the
                // tick interval here too so the rate-limiter
                // covers both yield and reset transitions.
                let elapsed = iteration_start.elapsed();
                apply_tick_interval(elapsed, config);
                iteration_start = Instant::now();
                state = vm
                    .resume_with_shared(&mut shared, Value::Int(tick))
                    .map_err(|e| format!("vm: {:?}", e))?;
            }
        }
    }
}

/// Drive a `yield main(tick: Word) -> Word` finite-stream entry
/// point. Shares the tick-counter convention with `loop main`. The
/// distinction is termination: a yield-main script eventually
/// returns instead of yielding, at which point the runner
/// terminates cleanly. The final returned value is printed if
/// non-Unit so the script can communicate its outcome to the
/// operator.
fn drive_yield_main(vm: &mut Vm, _arena: &Arena, config: &LoopRunnerConfig) -> Result<(), String> {
    let mut tick: i64 = 1;
    let mut iteration_start = Instant::now();
    // One host-owned shared buffer for the whole stream (B28 item 2).
    let mut shared = vec![0u8; vm.shared_data_bytes()];
    let mut state = vm
        .call_with_shared(&mut shared, &[Value::Int(tick)])
        .map_err(|e| format!("vm: {:?}", e))?;
    loop {
        match state {
            VmState::Finished(v) => {
                // Normal termination for a yield-main script. Print
                // the final value when it carries information.
                match v {
                    Value::Unit => {}
                    other => println!("{:?}", other),
                }
                return Ok(());
            }
            VmState::Yielded(v) => {
                let elapsed = iteration_start.elapsed();
                let yielded = match v {
                    Value::Int(n) => n,
                    other => {
                        return Err(format!(
                            "yield main yielded a non-Word value (signature requires Word): {:?}",
                            other
                        ));
                    }
                };
                tick = yielded.wrapping_add(1);
                apply_tick_interval(elapsed, config);
                iteration_start = Instant::now();
                state = vm
                    .resume_with_shared(&mut shared, Value::Int(tick))
                    .map_err(|e| format!("vm: {:?}", e))?;
            }
            VmState::BreakpointHit { chunk, op } => {
                return Err(format!(
                    "yield main hit a breakpoint at chunk {} op {}; the CLI does not arm breakpoints",
                    chunk, op
                ));
            }
            VmState::Reset => {
                let elapsed = iteration_start.elapsed();
                apply_tick_interval(elapsed, config);
                iteration_start = Instant::now();
                state = vm
                    .resume_with_shared(&mut shared, Value::Int(tick))
                    .map_err(|e| format!("vm: {:?}", e))?;
            }
        }
    }
}

/// Apply the configured tick interval after an iteration. Sleeps
/// for `interval - elapsed` when positive; emits a stderr warning
/// when elapsed exceeds the interval (unless `quiet`). A zero
/// interval (the default) is a no-op; the runner spins as fast as
/// the script yields.
fn apply_tick_interval(elapsed: Duration, config: &LoopRunnerConfig) {
    let nanos = config.tick_interval_nanos.load(Ordering::Relaxed);
    if nanos == 0 {
        return;
    }
    let interval = Duration::from_nanos(nanos);
    if elapsed >= interval {
        if !config.quiet {
            eprintln!(
                "warning: iteration time ({}) exceeded tick interval ({}); resuming immediately without sleep",
                duration::format(elapsed),
                duration::format(interval),
            );
        }
        return;
    }
    std::thread::sleep(interval - elapsed);
}

/// Format a compile-pipeline error with span information.
/// Subtracts the preamble line count so the reported line points
/// at the user-visible source rather than the combined
/// post-preamble source. Errors whose original line falls inside
/// the preamble window are reported with a `[preamble line N]`
/// marker so bundle-side mistakes are not silently attributed to
/// user code.
fn format_err_with_offset(
    stage: &str,
    msg: &str,
    span: keleusma::token::Span,
    preamble_lines: u32,
) -> String {
    if span.line == 0 && span.column == 0 {
        return format!("{}: {}", stage, msg);
    }
    if span.line <= preamble_lines {
        return format!(
            "{}: [preamble line {}:{}] {}",
            stage, span.line, span.column, msg
        );
    }
    let adjusted_line = span.line - preamble_lines;
    format!("{}: {}:{}: {}", stage, adjusted_line, span.column, msg)
}

/// Format a value as a human-readable string. Recursively
/// formats composite values so REPL and `println` output is
/// readable without the `Debug` impl's wrapper noise.
pub(crate) fn format_value(v: &Value) -> String {
    match v {
        Value::Int(n) => n.to_string(),
        Value::Float(f) => f.to_string(),
        Value::Bool(b) => b.to_string(),
        Value::StaticStr(s) => s.clone(),
        Value::Unit => "()".to_string(),
        Value::None => "None".to_string(),
        // A boxed tuple holds its elements and formats recursively. A
        // flat tuple is pure bytes with no layout, so this typeless
        // display path cannot decode its fields element-wise without the
        // static type, which it does not have here (B28 P2). It renders
        // a placeholder noting the byte length. This is an interim
        // limitation of REPL display for transitively-scalar tuples;
        // the typed marshalling path decodes such tuples for hosts that
        // know the type, and the V0.4 native backend bakes display.
        Value::Tuple(keleusma::bytecode::TupleBody::Boxed(items)) => {
            let parts: Vec<String> = items.iter().map(format_value).collect();
            format!("({})", parts.join(", "))
        }
        Value::Tuple(keleusma::bytecode::TupleBody::Flat(fc)) => {
            format!("(<flat tuple: {} bytes>)", fc.byte_len())
        }
        Value::Array(keleusma::bytecode::ArrayBody::Boxed(items)) => {
            let parts: Vec<String> = items.iter().map(format_value).collect();
            format!("[{}]", parts.join(", "))
        }
        // As with a flat tuple, the typeless display path cannot recover
        // the element kind of a flat array; the typed marshalling path
        // decodes it for hosts that know the type (B28 P2 interim).
        Value::Array(keleusma::bytecode::ArrayBody::Flat(fc)) => {
            format!("[<flat array: {} bytes>]", fc.byte_len())
        }
        Value::Enum(keleusma::bytecode::EnumBody::Boxed(b)) => {
            if b.type_name == "Option" && b.variant == "Some" {
                if let Some(f) = b.fields.first() {
                    format!("Some({})", format_value(f))
                } else {
                    "Some".to_string()
                }
            } else if b.fields.is_empty() {
                b.variant.clone()
            } else {
                let parts: Vec<String> = b.fields.iter().map(format_value).collect();
                format!("{}({})", b.variant, parts.join(", "))
            }
        }
        Value::Struct(keleusma::bytecode::StructBody::Boxed(b)) => {
            let parts: Vec<String> = b
                .fields
                .iter()
                .map(|(k, v)| format!("{}: {}", k, format_value(v)))
                .collect();
            format!("{} {{ {} }}", b.type_name, parts.join(", "))
        }
        // As with a flat tuple or array, the typeless display path cannot
        // recover a flat struct's field names or kinds; the typed
        // marshalling path decodes it for hosts that know the type
        // (B28 P2 interim).
        Value::Struct(keleusma::bytecode::StructBody::Flat(fc)) => {
            format!("<flat struct: {} bytes>", fc.byte_len())
        }
        other => format!("{:?}", other),
    }
}

/// Print a value to stdout without a trailing newline. Used by the
/// CLI's `println` override. The full `print_value` variant adds the
/// trailing newline.
fn print_value_inline(v: &Value) {
    print!("{}", format_value(v));
}

/// Like [`print_value_inline`] but resolves a top-level `KStr` through the
/// arena before printing. A string constant now loads as a rodata `KStr`
/// rather than an owned `StaticStr` (B28 P3 item 4), so `println("x")` would
/// otherwise render the handle through `format_value`'s debug fallback instead
/// of the text. A stale handle prints a placeholder rather than dereferencing
/// reclaimed memory.
fn print_value_inline_ctx(v: &Value, arena: &Arena) {
    match v {
        Value::KStr(h) => match h.get(arena) {
            Ok(s) => print!("{}", s),
            Err(_) => print!("<stale KStr>"),
        },
        other => print_value_inline(other),
    }
}

fn print_value(v: &Value, arena: &Arena) {
    match v {
        Value::KStr(h) => match h.get(arena) {
            Ok(s) => println!("{}", s),
            Err(_) => println!("<stale KStr>"),
        },
        other => println!("{}", format_value(other)),
    }
}

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

    #[test]
    fn shebang_line_is_skipped() {
        // A leading shebang makes a script Unix-executable through
        // `#!/usr/bin/env keleusma`. It must compile the same as the
        // same script without it; the preamble the CLI prepends must
        // not defeat the lexer's shebang handling.
        let with = compile_source("#!/usr/bin/env keleusma\nfn main() -> Word { 42 }\n");
        assert!(
            with.is_ok(),
            "shebang script failed to compile: {:?}",
            with.err()
        );
    }

    #[test]
    fn no_shebang_still_compiles() {
        assert!(compile_source("fn main() -> Word { 42 }\n").is_ok());
    }

    #[test]
    fn compile_debug_then_strip_reproduces_release_bytes() {
        let src = "fn helper() -> Word { 1 }\nfn main() -> Word { helper() }";

        // Release build (no debug).
        let release_bytes = compile_source_with_target(src, None, false)
            .expect("compile release")
            .to_bytes()
            .expect("encode release");

        // Debug build carries a debug pool on the calling chunk.
        let debug_module = compile_source_with_target(src, None, true).expect("compile debug");
        assert!(
            debug_module.chunks.iter().any(|c| c.debug_pool.is_some()),
            "a --debug compile should attach debug metadata"
        );
        let debug_bytes = debug_module.to_bytes().expect("encode debug");
        assert_ne!(
            debug_bytes, release_bytes,
            "the debug build should differ from the release build before stripping"
        );

        // Stripping the debug bytes reproduces the release bytes exactly.
        let stripped = strip_module_bytes(&debug_bytes).expect("strip");
        assert_eq!(
            stripped, release_bytes,
            "stripped debug bytecode must be byte-identical to the release build"
        );

        // Stripping is idempotent: stripping already-release bytes is a no-op.
        let restripped = strip_module_bytes(&release_bytes).expect("re-strip");
        assert_eq!(restripped, release_bytes);
    }

    #[test]
    fn shebang_preserves_source_line_numbers() {
        // An error on source line 3 must report line 3, so stripping
        // the shebang must leave a blank line in its place rather than
        // shifting subsequent lines up.
        let err =
            compile_source("#!/usr/bin/env keleusma\nfn main() -> Word {\n  undefined_thing\n}\n")
                .expect_err("undefined identifier should fail to compile");
        assert!(
            err.contains("3:"),
            "expected an error on line 3, got: {}",
            err
        );
    }
}