noxid-cli 0.2.1

The Noxid compiler command line: check, build, test, adapt, and the agent surface
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
mod ai;
mod app;
mod data_security;
mod db;
mod deployment;
mod farm;
mod mcp;
mod modules;
mod npm_admission;
mod project;
mod queue;
mod repair_transaction;
mod scaffold;
mod scenario_test;
mod sha256;
mod task;

use noxid_compiler_core::{devtools_javascript, runtime_javascript_for_imports};
use noxid_formatter::format_source;
use noxid_ir::SemanticId;
use noxid_semantic_ops::{Provenance, plan_project_rename, rename_symbol};
use noxid_source::{SourceFile, SourceId};
use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Instant;

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(message) => {
            eprintln!("noxid: {message}");
            ExitCode::FAILURE
        }
    }
}

fn run() -> Result<(), String> {
    let mut args = env::args().skip(1);
    let command = args.next().ok_or_else(usage)?;
    if command == "--help" || command == "help" {
        println!("{}", usage());
        return Ok(());
    }
    if command == "lsp" {
        if args.next().is_some() {
            return Err("noxid lsp does not accept a source path".into());
        }
        return noxid_lsp::run_stdio();
    }
    if command == "port" {
        return run_port_command(args);
    }
    if command == "db" {
        return db::run(args);
    }
    if command == "task" {
        return task::run(args);
    }
    if command == "queue" {
        return queue::run(args);
    }
    if command == "describe" {
        return ai::run_describe(args);
    }
    if command == "test" {
        // `cd my-app && noxid test --gate` is the loop the scaffolded project
        // teaches, so an omitted path means the current directory. Every other
        // command still requires its input explicitly.
        let mut input = PathBuf::from(".");
        let mut gate = false;
        let mut json_only = false;
        let mut saw_input = false;
        let mut seed = None;
        let mut property = None;
        while let Some(argument) = args.next() {
            match argument.as_str() {
                "--gate" => gate = true,
                "--json" => json_only = true,
                "--seed" => {
                    if seed.is_some() {
                        return Err("noxid test accepts --seed at most once".into());
                    }
                    let value = args
                        .next()
                        .ok_or("noxid test --seed requires an unsigned 64-bit integer")?;
                    seed = Some(value.parse::<u64>().map_err(|_| {
                        format!(
                            "noxid test --seed requires an unsigned 64-bit integer, got `{value}`"
                        )
                    })?);
                }
                "--property" => {
                    if property.is_some() {
                        return Err("noxid test accepts --property at most once".into());
                    }
                    property = Some(
                        args.next()
                            .ok_or("noxid test --property requires a semantic property ID")?,
                    );
                }
                other if other.starts_with("--") => {
                    return Err(format!("unknown test argument `{other}`\n{}", usage()));
                }
                other if saw_input => {
                    return Err(format!(
                        "noxid test accepts one file or project; received a second, `{other}`\n{}",
                        usage()
                    ));
                }
                other => {
                    input = PathBuf::from(other);
                    saw_input = true;
                }
            }
        }
        if property.is_some() && seed.is_none() {
            return Err(
                "PROPERTY_REPLAY_SEED_REQUIRED: noxid test --property selects a seeded replay; add --seed <n>, or omit --property to run every declared property"
                    .into(),
            );
        }
        if gate && seed.is_some() {
            return Err(
                "PROPERTY_REPLAY_GATE_CONFLICT: noxid test --gate enforces the 100-run property floor and cannot be combined with --seed; run the gate without --seed, then run --seed <n> with --property <semantic-id> separately to replay one case"
                    .into(),
            );
        }
        // `test` resolves its own input because the path is optional, so it
        // settles an interrupted `repair --safe` here rather than through the
        // shared positional hook below.
        if input.exists() {
            repair_transaction::recover_before_read(&input)?;
        }
        return scenario_test::run(
            &input,
            scenario_test::Options { gate, json_only },
            seed,
            property.as_deref(),
        );
    }
    if command == "vet" {
        // `vet` takes no path: with a package name it vets an npm release, and
        // with none it checks the vendored plugins of the project it is run in.
        // It is dispatched before the shared positional input so `noxid vet
        // --sync` is not read as a file name.
        return npm_admission::run_vet_command(args);
    }
    let input = PathBuf::from(args.next().ok_or_else(usage)?);
    // WO-51: `repair --inspect` is the remedy a refused journal's error names,
    // so it is the one reader that must run *before* the recovery hook — the
    // hook is exactly what it exists to unblock. It reads the journals and
    // changes nothing unless `--discard` names one.
    let repair_args: Vec<String> = if command == "repair" {
        args.by_ref().collect()
    } else {
        Vec::new()
    };
    if repair_args.iter().any(|argument| argument == "--inspect") {
        return repair_transaction::run_inspect(&input, &repair_args);
    }
    // An interrupted `repair --safe` is settled before this command reads a
    // single source byte, so no entry point ever compiles a project that is
    // part repaired and part original. The guard keeps the hook off the
    // commands whose "input" is a name rather than a path (`example`,
    // `agent-guide`, `vet`, `new`).
    if input.exists() {
        repair_transaction::recover_before_read(&input)?;
    }
    if command == "drift" {
        let after = PathBuf::from(
            args.next()
                .ok_or("noxid drift requires before and after files or projects")?,
        );
        if args.next().is_some() {
            return Err("noxid drift accepts exactly two files or projects".into());
        }
        if after.exists() {
            // `drift` reads two projects; both are settled before either is read.
            repair_transaction::recover_before_read(&after)?;
        }
        return ai::run_drift(&input, &after);
    }
    if command == "agent-guide" {
        if args.next().is_some() {
            return Err("noxid agent-guide accepts one topic".into());
        }
        let topic = input.to_string_lossy();
        println!("{}", agent_guide(topic.as_ref())?);
        return Ok(());
    }
    if command == "example" {
        if args.next().is_some() {
            return Err("noxid example accepts one example name".into());
        }
        println!("{}", compiler_example(input.to_string_lossy().as_ref())?);
        return Ok(());
    }
    if command == "new" {
        let mut render: Option<String> = None;
        let mut template = "counter".to_string();
        while let Some(argument) = args.next() {
            match argument.as_str() {
                "--render" => {
                    render = Some(args.next().ok_or("--render requires client or universal")?)
                }
                "--template" => {
                    template = args.next().ok_or_else(|| {
                        format!(
                            "--template requires one of {}",
                            scaffold::TEMPLATE_NAMES.join(", ")
                        )
                    })?
                }
                other => return Err(format!("unknown new argument `{other}`")),
            }
        }
        let target = scaffold::resolve_target(&input)?;
        scaffold::scaffold_project(&target, &template, render.as_deref())?;
        // The target is echoed exactly as it was typed. The counter template's
        // output — file set, bytes, and this line — stays byte-identical to the
        // pre-WO-50 scaffolder, which reported the argument verbatim.
        println!(
            "created Noxid {} project -> {}",
            scaffold::output_label(&template, render.as_deref()),
            input.display()
        );
        return Ok(());
    }
    if command == "mcp" {
        if args.next().is_some() {
            return Err("noxid mcp accepts exactly one project or .nox path".into());
        }
        return mcp::run(&input);
    }
    if command == "mcp-http" {
        let mut bind = "127.0.0.1:4321".to_string();
        let mut token_env = "NOXID_MCP_TOKEN".to_string();
        let mut allowed_origins = Vec::new();
        let mut stream_responses = false;
        while let Some(argument) = args.next() {
            match argument.as_str() {
                "--bind" => bind = args.next().ok_or("--bind requires an address")?,
                "--token-env" => {
                    token_env = args.next().ok_or("--token-env requires a variable name")?
                }
                "--allow-origin" => allowed_origins.push(
                    args.next()
                        .ok_or("--allow-origin requires an exact origin")?,
                ),
                "--stream" => stream_responses = true,
                other => {
                    return Err(format!("unknown mcp-http argument `{other}`\n{}", usage()));
                }
            }
        }
        return mcp::run_http(&input, bind, &token_env, allowed_origins, stream_responses);
    }
    if command == "undo" {
        let transaction_id = args
            .next()
            .ok_or("noxid undo requires a local transaction ID")?;
        if args.next().is_some() {
            return Err(
                "noxid undo accepts exactly one file or project and one transaction ID".into(),
            );
        }
        println!("{}", mcp::undo_local(&input, &transaction_id)?);
        return Ok(());
    }
    if matches!(
        command.as_str(),
        "plan"
            | "context"
            | "manifest"
            | "simulate"
            | "test-affected"
            | "index"
            | "search"
            | "repair"
            | "scaffold"
    ) {
        return ai::run(&command, &input, repair_args.into_iter().chain(args));
    }
    let operation_symbol = if matches!(command.as_str(), "impact" | "rename") {
        Some(
            args.next()
                .ok_or_else(|| format!("noxid {command} requires a semantic ID"))?,
        )
    } else {
        None
    };
    let rename_name = if command == "rename" {
        Some(
            args.next()
                .ok_or("noxid rename requires a new identifier")?,
        )
    } else {
        None
    };
    if command == "vue-island" {
        if input.extension().and_then(|value| value.to_str()) != Some("vue") || !input.is_file() {
            return Err(format!(
                "noxid vue-island requires an existing `.vue` file: {}",
                input.display()
            ));
        }
        let default_name = input
            .file_stem()
            .and_then(|value| value.to_str())
            .ok_or("Vue island input has no valid file stem")?
            .to_string();
        let mut name = default_name;
        let mut props = Vec::new();
        let mut events = Vec::new();
        let mut write_adapter = false;
        while let Some(arg) = args.next() {
            match arg.as_str() {
                "--name" => name = args.next().ok_or("--name requires a component name")?,
                "--prop" => props.push(parse_vue_island_field(
                    &args.next().ok_or("--prop requires name:Type")?,
                )?),
                "--event" => events.push(parse_vue_island_field(
                    &args.next().ok_or("--event requires name:Type")?,
                )?),
                "--write" => write_adapter = true,
                _ => return Err(format!("unknown vue-island argument `{arg}`\n{}", usage())),
            }
        }
        let file_name = input
            .file_name()
            .and_then(|value| value.to_str())
            .ok_or("Vue island input has no valid file name")?;
        let contract = noxid_vue_island::VueIslandContract {
            component: name.clone(),
            source: format!("./{file_name}"),
            props,
            events,
        };
        let javascript = contract.javascript().map_err(|diagnostics| {
            diagnostics
                .into_iter()
                .map(|item| format!("error[{}]: {}", item.code, item.message))
                .collect::<Vec<_>>()
                .join("\n")
        })?;
        if write_adapter {
            let output = input.with_file_name(format!("{name}.vue-island.js"));
            write(&output, &javascript)?;
            println!("generated Vue island adapter -> {}", output.display());
        } else {
            print!("{javascript}");
        }
        return Ok(());
    }
    let mut out_dir = PathBuf::from("dist");
    let mut out_dir_explicit = false;
    let mut json_diagnostics = false;
    let mut entry = None;
    let mut title = None;
    let mut port = 4173_u16;
    let mut adapter = None;
    let mut write_changes = false;
    let mut check_format = false;
    let mut agent_output = false;
    let mut strict_npm = false;
    while let Some(arg) = args.next() {
        if arg == "--out-dir" {
            out_dir = PathBuf::from(args.next().ok_or("--out-dir requires a path")?);
            out_dir_explicit = true;
        } else if arg == "--json" {
            json_diagnostics = true;
        } else if arg == "--entry" {
            entry = Some(args.next().ok_or("--entry requires a component name")?);
        } else if arg == "--title" {
            title = Some(args.next().ok_or("--title requires text")?);
        } else if arg == "--strict-npm" {
            strict_npm = true;
        } else if arg == "--port" {
            port = args
                .next()
                .ok_or("--port requires a number")?
                .parse()
                .map_err(|_| "--port must be an integer from 1 to 65535")?;
            if port == 0 {
                return Err("--port must be an integer from 1 to 65535".into());
            }
        } else if arg == "--adapter" {
            adapter = Some(args.next().ok_or("--adapter requires a target")?);
        } else if arg == "--write" {
            write_changes = true;
        } else if arg == "--check" {
            check_format = true;
        } else if arg == "--agent" {
            agent_output = true;
        } else {
            return Err(format!("unknown argument `{arg}`\n{}", usage()));
        }
    }
    if command == "port-vue" {
        if out_dir_explicit
            || entry.is_some()
            || title.is_some()
            || adapter.is_some()
            || write_changes
            || check_format
        {
            return Err("noxid port-vue only supports the input path and --json".into());
        }
        let report = noxid_port_vue::analyze_path(&input, &noxid_port_vue::PortOptions::default())
            .map_err(|error| format!("cannot analyze {}: {error}", input.display()))?;
        if json_diagnostics {
            println!("{}", report.to_json());
        } else {
            println!("{}", report.render_human());
            println!(
                "migration summary: {} converted, {} TODO, {} blocked, {} externalized, {} ignored",
                report.summary.converted,
                report.summary.todo,
                report.summary.blocked,
                report.summary.externalized,
                report.summary.ignored,
            );
        }
        if report.has_blockers() {
            return Err(format!(
                "migration is blocked by {} unsafe or unsupported construct(s)",
                report.summary.blocked
            ));
        }
        return Ok(());
    }
    if command == "headless" {
        if json_diagnostics
            || entry.is_some()
            || title.is_some()
            || adapter.is_some()
            || write_changes
            || check_format
        {
            return Err("noxid headless only supports a recipe list and --out-dir".into());
        }
        let recipes = input
            .to_string_lossy()
            .split(',')
            .map(parse_headless_recipe)
            .collect::<Result<Vec<_>, _>>()?;
        if recipes.is_empty() {
            return Err("noxid headless requires at least one component recipe".into());
        }
        let imports = noxid_headless_components::runtime_imports_for(recipes.iter().copied())
            .into_iter()
            .map(str::to_string)
            .collect::<BTreeSet<_>>();
        let mut javascript = format!(
            "import {{ {} }} from \"./noxid-runtime.js\";\n",
            imports.iter().cloned().collect::<Vec<_>>().join(", ")
        );
        javascript.push_str(&noxid_headless_components::javascript_for(
            recipes.iter().copied(),
        ));
        fs::create_dir_all(&out_dir)
            .map_err(|error| format!("cannot create {}: {error}", out_dir.display()))?;
        write(&out_dir.join("noxid-headless.js"), &javascript)?;
        write(
            &out_dir.join("noxid-runtime.js"),
            &runtime_javascript_for_imports(&imports),
        )?;
        println!(
            "generated {} native headless recipe(s) -> {}",
            recipes.len(),
            out_dir.display()
        );
        return Ok(());
    }
    if project::is_project_input(&input) {
        if entry.is_some() {
            return Err("folder-routed projects select entries from +page.nox files; --entry is not supported".into());
        }
        if !out_dir_explicit {
            out_dir = project::default_out_dir(&input, command == "dev");
        }
        let options = project::ProjectBuildOptions {
            out_dir: out_dir.clone(),
            title: title.clone(),
            development: command == "dev",
            strict_npm,
        };
        return match command.as_str() {
            "build" => {
                let build = project::build_project(&input, &options)?;
                project::prerender_output(&out_dir, &build)?;
                if agent_output {
                    println!(
                        "{{\"ok\":true,\"command\":\"build\",\"routes\":{},\"endpoints\":{},\"components\":{},\"assets\":{},\"cacheHit\":{},\"output\":\"{}\"}}",
                        build.routes,
                        build.endpoints,
                        build.components,
                        build.assets,
                        build.persistent_cache_hit,
                        noxid_source::json_escape(&out_dir.display().to_string())
                    );
                } else {
                    println!(
                        "built {} -> {} ({} route(s), {} endpoint(s), {} SSR route(s), {} prerender route pattern(s)/{} concrete output(s), {} ISR route(s), {} SWR route(s), {} route loader(s), {} component chunk(s), {} middleware module(s), {} emitted asset(s), persistent cache: {})",
                        input.display(),
                        out_dir.display(),
                        build.routes,
                        build.endpoints,
                        build.ssr_routes,
                        build.prerender_routes,
                        build.prerender_entries,
                        build.isr_routes,
                        build.swr_routes,
                        build.route_loaders,
                        build.components,
                        build.middleware,
                        build.assets,
                        if build.persistent_cache_hit {
                            "hit"
                        } else {
                            "miss"
                        },
                    );
                }
                Ok(())
            }
            "bundle" => {
                let build = farm::bundle_project(&input, &out_dir, title)?;
                if agent_output {
                    println!(
                        "{{\"ok\":true,\"command\":\"bundle\",\"routes\":{},\"endpoints\":{},\"components\":{},\"cacheHit\":{},\"output\":\"{}\"}}",
                        build.routes,
                        build.endpoints,
                        build.components,
                        build.persistent_cache_hit,
                        noxid_source::json_escape(&out_dir.display().to_string())
                    );
                } else {
                    println!(
                        "bundled {} with {} -> {} ({} route(s), {} endpoint(s), {} component chunk(s), persistent compiler cache: {})",
                        input.display(),
                        if build.native_esm_eligible {
                            "Farm native ESM"
                        } else {
                            "Farm runtime"
                        },
                        out_dir.display(),
                        build.routes,
                        build.endpoints,
                        build.components,
                        if build.persistent_cache_hit {
                            "hit"
                        } else {
                            "miss"
                        },
                    );
                }
                Ok(())
            }
            "adapt" => {
                let plan = deployment::adapt_project(&input, &out_dir, title, adapter.as_deref())?;
                println!(
                    "adapted {} for {} -> {}",
                    input.display(),
                    plan.selected,
                    out_dir.display(),
                );
                Ok(())
            }
            "dev" => project::serve_project(input, options, port),
            "benchmark" => {
                println!("{}", project::benchmark_json(&input)?);
                Ok(())
            }
            "routes" => {
                println!("{}", project::routes_json(&input)?);
                Ok(())
            }
            "graph" => {
                println!("{}", project::graph_json(&input)?);
                Ok(())
            }
            "impact" => {
                println!(
                    "{}",
                    project::impact_json(
                        &input,
                        operation_symbol.as_deref().expect("impact symbol")
                    )?
                );
                Ok(())
            }
            "product" => {
                println!("{}", project::product_json(&input)?);
                Ok(())
            }
            "accessibility" | "design-system" | "devtools" => {
                println!("{}", project::mcp_resource_json(&input, &command)?);
                Ok(())
            }
            other => Err(format!(
                "project input supports build, bundle, adapt, dev, benchmark, routes, graph, impact, product, accessibility, design-system, or devtools; received `{other}`"
            )),
        };
    }
    ensure_noxid_source(&input)?;
    if command == "benchmark" {
        let text = fs::read_to_string(&input)
            .map_err(|error| format!("cannot read {}: {error}", input.display()))?;
        let mut parse_samples = Vec::new();
        let mut compile_samples = Vec::new();
        for index in 0..30 {
            let source = SourceFile::new(SourceId(index), &input, text.clone());
            let started = Instant::now();
            let parsed = noxid_parser::parse(&source);
            parse_samples.push(started.elapsed().as_secs_f64() * 1_000.0);
            std::hint::black_box(parsed);
            let started = Instant::now();
            let compiled = noxid_compiler_core::compile(&source);
            compile_samples.push(started.elapsed().as_secs_f64() * 1_000.0);
            std::hint::black_box(compiled);
        }
        parse_samples.sort_by(f64::total_cmp);
        compile_samples.sort_by(f64::total_cmp);
        println!(
            "{{\"schemaVersion\":1,\"kind\":\"file\",\"samples\":30,\"sourceBytes\":{},\"parseMedianMs\":{:.3},\"parseP95Ms\":{:.3},\"compileMedianMs\":{:.3},\"compileP95Ms\":{:.3}}}",
            text.len(),
            parse_samples[15],
            parse_samples[28],
            compile_samples[15],
            compile_samples[28],
        );
        return Ok(());
    }
    if command == "format" {
        if json_diagnostics || entry.is_some() || title.is_some() || adapter.is_some() {
            return Err("noxid format only supports --write or --check".into());
        }
        if write_changes && check_format {
            return Err("noxid format cannot combine --write and --check".into());
        }
        let source = fs::read_to_string(&input)
            .map_err(|error| format!("cannot read {}: {error}", input.display()))?;
        let formatted = format_source(&source);
        if check_format {
            if formatted.changed {
                return Err(format!("{} is not formatted", input.display()));
            }
            println!("{}: formatted", input.display());
        } else if write_changes {
            if formatted.changed {
                write(&input, &formatted.text)?;
            }
            println!("formatted {}", input.display());
        } else {
            print!("{}", formatted.text);
        }
        return Ok(());
    }
    if command == "dev" {
        if json_diagnostics {
            return Err("noxid dev does not support --json".into());
        }
        if !out_dir_explicit {
            let stem = input
                .file_stem()
                .and_then(|value| value.to_str())
                .ok_or("input has no valid file stem")?;
            out_dir = PathBuf::from("target/noxid-dev").join(stem);
        }
        return app::serve(
            input,
            app::AppOptions {
                entry,
                title,
                out_dir,
                development: true,
            },
            port,
        );
    }
    // A bare file name has an empty parent; the import root is the current
    // directory in that case, so `noxid compile Counter.nox` works in place.
    let (source_root, auto_components) = match project::source_import_context(&input)? {
        Some(context) => context,
        None => {
            let source_root = input
                .parent()
                .filter(|parent| !parent.as_os_str().is_empty())
                .unwrap_or_else(|| Path::new("."))
                .to_path_buf();
            let auto_components = source_root.join("components");
            (source_root, auto_components)
        }
    };
    let module_graph = modules::compile_module_graph_with_options(
        &input,
        &source_root,
        auto_components
            .exists()
            .then_some(auto_components.as_path()),
        &std::collections::BTreeMap::new(),
        // A single-file door still honors the enclosing project's declared
        // `[server] secrets`, so `noxid check server/models/X.nox` agrees with
        // `noxid build .` instead of refusing a legitimately declared key.
        &project::project_analysis_options(&source_root),
    )?;
    let source = &module_graph.root().source;
    let output = &module_graph.root().compilation;
    if json_diagnostics {
        println!("{}", output.diagnostics_json());
    } else {
        for diagnostic in &output.diagnostics {
            eprintln!("{}", diagnostic.render(source));
        }
    }

    match command.as_str() {
        "a11y" => {
            let findings = output
                .diagnostics
                .iter()
                .filter(|diagnostic| diagnostic.code.starts_with("A11Y_"))
                .count();
            if findings != 0 {
                return Err(format!("{findings} accessibility diagnostic(s)"));
            }
            if !json_diagnostics {
                println!("{}: accessible", input.display());
            }
        }
        "check" => {
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
            if agent_output {
                println!("{{\"ok\":true,\"diagnostics\":0}}");
            } else if !json_diagnostics {
                println!("{}: valid", input.display());
            }
        }
        "inspect" => {
            println!("{}", output.program.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "graph" => {
            print!("{}", module_graph.merged_graph().render_text());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "impact" => {
            let id = SemanticId::parse(operation_symbol.as_deref().expect("impact symbol"))
                .ok_or("impact requires a stable semantic ID such as state:Counter.count")?;
            let graph = module_graph.merged_graph();
            let impact = graph
                .impact(&id)
                .ok_or_else(|| format!("unknown semantic symbol `{id}`"))?;
            println!("{}", impact.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "product" => {
            println!("{}", output.program.product_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "rename" => {
            if output.has_errors() {
                return Err("semantic rename requires a valid source file".into());
            }
            let id = SemanticId::parse(operation_symbol.as_deref().expect("rename symbol"))
                .ok_or("rename requires a stable semantic ID")?;
            let graph = module_graph.merged_graph();
            if graph
                .nodes
                .get(&id)
                .is_some_and(|node| node.kind == noxid_graph::NodeKind::TypeDefinition)
            {
                let sources = module_graph
                    .modules()
                    .map(|(_, module)| module.source.clone())
                    .collect::<Vec<_>>();
                plan_project_rename(
                    &sources,
                    &graph,
                    &id,
                    rename_name.as_deref().expect("rename name"),
                    Provenance::default(),
                )?;
            }
            let result = rename_symbol(
                source,
                &graph,
                &id,
                rename_name.as_deref().expect("rename name"),
            )?;
            let candidate = SourceFile::new(SourceId(0), &input, result.source.clone());
            let parsed = noxid_parser::parse(&candidate);
            if !parsed.diagnostics.is_empty() {
                return Err(format!(
                    "rename was rejected because the transformed source has {} syntax diagnostic(s)",
                    parsed.diagnostics.len()
                ));
            }
            if write_changes {
                write(&input, &result.source)?;
            }
            println!("{}", result.to_json());
        }
        "machines" => {
            println!("{}", output.machines.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "collections" => {
            println!("{}", output.collections.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "resources" => {
            println!("{}", output.resources.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "streams" => {
            println!("{}", output.streams.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "agents" => {
            println!("{}", output.agents.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "execution" => {
            println!("{}", output.execution.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "validators" => {
            println!("{}", output.validation.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "styles" => {
            println!("{}", output.styles.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "devtools" => {
            println!("{}", output.devtools.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "accessibility" => {
            println!("{}", output.accessibility.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "design-system" => {
            println!("{}", output.design.to_json());
            if output.has_errors() {
                return Err(format!("{} diagnostic(s)", output.diagnostics.len()));
            }
        }
        "compile" => {
            if output.has_errors() {
                return Err(format!(
                    "{} diagnostic(s); no output emitted",
                    output.diagnostics.len()
                ));
            }
            fs::create_dir_all(&out_dir)
                .map_err(|error| format!("cannot create {}: {error}", out_dir.display()))?;
            let stem = input
                .file_stem()
                .and_then(|value| value.to_str())
                .ok_or("input has no valid file stem")?;
            if let Some(generated) = &output.generated {
                if generated.modules.is_empty() {
                    write(&out_dir.join(format!("{stem}.js")), &generated.javascript)?;
                } else {
                    for module in &generated.modules {
                        write(
                            &out_dir.join(format!("{}.js", module.component)),
                            &module.javascript,
                        )?;
                    }
                    if !generated
                        .modules
                        .iter()
                        .any(|module| module.component == stem)
                    {
                        let legacy = out_dir.join(format!("{stem}.js"));
                        if legacy.exists() {
                            fs::remove_file(&legacy).map_err(|error| {
                                format!("cannot remove stale {}: {error}", legacy.display())
                            })?;
                        }
                    }
                }
                let css = module_graph
                    .modules()
                    .map(|(_, module)| {
                        module
                            .compilation
                            .generated
                            .as_ref()
                            .map(|item| item.css.as_str())
                            .unwrap_or("")
                    })
                    .collect::<Vec<_>>()
                    .join("\n");
                write(&out_dir.join(format!("{stem}.css")), &css)?;
            }
            for (_, module) in module_graph.modules() {
                if std::ptr::eq(module, module_graph.root()) {
                    continue;
                }
                let generated = module.compilation.generated.as_ref().ok_or_else(|| {
                    format!(
                        "{} did not generate JavaScript",
                        module.source.path().display()
                    )
                })?;
                if generated.modules.is_empty() {
                    let component =
                        module
                            .compilation
                            .program
                            .components
                            .first()
                            .ok_or_else(|| {
                                format!("{} exports no component", module.source.path().display())
                            })?;
                    write(
                        &out_dir.join(format!("{}.js", component.name)),
                        &generated.javascript,
                    )?;
                } else {
                    for component in &generated.modules {
                        write(
                            &out_dir.join(format!("{}.js", component.component)),
                            &component.javascript,
                        )?;
                    }
                }
            }
            if let Some(validators) = &output.generated_validators {
                write(&out_dir.join(format!("{stem}.validators.js")), validators)?;
            }
            if let Some(resources) = &output.generated_resources {
                write(&out_dir.join(format!("{stem}.resources.js")), resources)?;
            }
            if let Some(streams) = &output.generated_streams {
                write(&out_dir.join(format!("{stem}.streams.js")), streams)?;
            }
            if let Some(agents) = &output.generated_agents {
                write(&out_dir.join(format!("{stem}.agents.js")), agents)?;
            }
            if output.generated.is_some()
                || output.generated_resources.is_some()
                || output.generated_streams.is_some()
                || output.generated_agents.is_some()
            {
                let runtime_imports = module_graph
                    .modules()
                    .flat_map(|(_, module)| module.compilation.runtime_imports())
                    .collect::<BTreeSet<_>>();
                write(
                    &out_dir.join("noxid-runtime.js"),
                    &runtime_javascript_for_imports(&runtime_imports),
                )?;
                write(&out_dir.join("noxid-devtools.js"), devtools_javascript())?;
                write(
                    &out_dir.join(format!("{stem}.bundle.json")),
                    &output.bundle_json(),
                )?;
            }
            write(
                &out_dir.join(format!("{stem}.meta.json")),
                &output.metadata_json(),
            )?;
            write(
                &out_dir.join(format!("{stem}.devtools.json")),
                &output.devtools.to_json(),
            )?;
            println!("compiled {} -> {}", input.display(), out_dir.display());
        }
        "build" => {
            let build = app::build_app(
                &input,
                output,
                Some(&module_graph),
                &app::AppOptions {
                    entry,
                    title,
                    out_dir: out_dir.clone(),
                    development: false,
                },
            )?;
            println!(
                "built {} as component:{} -> {} ({} component chunk(s), {} emitted asset(s))",
                input.display(),
                build.entry,
                out_dir.display(),
                build.components.len(),
                build.assets.len()
            );
        }
        other => return Err(format!("unknown command `{other}`\n{}", usage())),
    }
    Ok(())
}

fn ensure_noxid_source(path: &Path) -> Result<(), String> {
    if path.extension().and_then(|extension| extension.to_str()) == Some("nox") {
        return Ok(());
    }
    Err(format!(
        "Noxid source files must use the `.nox` extension: {}",
        path.display()
    ))
}

fn write(path: &Path, contents: &str) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)
            .map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
    }
    fs::write(path, contents).map_err(|error| format!("cannot write {}: {error}", path.display()))
}

fn parse_vue_island_field(value: &str) -> Result<noxid_vue_island::VueIslandField, String> {
    let (name, ty) = value
        .split_once(':')
        .ok_or_else(|| format!("Vue island field `{value}` must use name:Type"))?;
    Ok(noxid_vue_island::VueIslandField {
        name: name.into(),
        ty: ty.into(),
    })
}

fn run_port_command(mut args: impl Iterator<Item = String>) -> Result<(), String> {
    let kind = args.next().ok_or_else(usage)?;
    let input = PathBuf::from(args.next().ok_or_else(usage)?);
    let mut out_dir = PathBuf::from("ported-noxid");
    let mut write_changes = false;
    let mut json = false;
    let mut include_generated = false;
    while let Some(argument) = args.next() {
        match argument.as_str() {
            "--out-dir" => out_dir = PathBuf::from(args.next().ok_or("--out-dir requires a path")?),
            "--write" => write_changes = true,
            "--json" => json = true,
            "--include-generated" => include_generated = true,
            other => return Err(format!("unknown port argument `{other}`\n{}", usage())),
        }
    }
    let options = noxid_port_vue::PortOptions {
        include_generated,
        ..noxid_port_vue::PortOptions::default()
    };
    match kind.as_str() {
        "project" | "nuxt" | "vue-project" => {
            let forced = match kind.as_str() {
                "nuxt" => Some(noxid_port_vue::project::VueProjectKind::Nuxt),
                "vue-project" => Some(noxid_port_vue::project::VueProjectKind::Vue),
                _ => None,
            };
            let plan = noxid_port_vue::project::plan_project(&input, forced, &options)
                .map_err(|error| format!("cannot plan project port: {error}"))?;
            if json {
                println!("{}", plan.to_json());
            } else {
                println!("{}", plan.render_human());
            }
            if write_changes {
                write_project_port(&plan, &out_dir)?;
                println!("ported and validated project -> {}", out_dir.display());
            }
        }
        "vue-package" | "package" => {
            let plan = noxid_port_vue::package::plan_package(&input, &options)
                .map_err(|error| format!("cannot plan Vue package port: {error}"))?;
            if json {
                println!("{}", plan.to_json());
            } else {
                println!("{}", plan.render_human());
            }
            if write_changes {
                write_package_port(&plan, &out_dir)?;
                println!("ported Vue package -> {}", out_dir.display());
            }
        }
        other => {
            return Err(format!(
                "unknown port kind `{other}`; expected project, nuxt, vue-project, or vue-package"
            ));
        }
    }
    Ok(())
}

fn fresh_port_staging(out_dir: &Path) -> Result<PathBuf, String> {
    if out_dir.exists() {
        return Err(format!(
            "port output already exists; refusing to replace {}",
            out_dir.display()
        ));
    }
    let parent = out_dir.parent().unwrap_or_else(|| Path::new("."));
    fs::create_dir_all(parent)
        .map_err(|error| format!("cannot create {}: {error}", parent.display()))?;
    let name = out_dir
        .file_name()
        .and_then(|value| value.to_str())
        .unwrap_or("ported-noxid");
    let staging = parent.join(format!(".{name}.noxid-port-{}", std::process::id()));
    if staging.exists() {
        return Err(format!(
            "stale port staging directory exists: {}",
            staging.display()
        ));
    }
    fs::create_dir_all(&staging)
        .map_err(|error| format!("cannot create {}: {error}", staging.display()))?;
    Ok(staging)
}

fn commit_port_staging(staging: &Path, out_dir: &Path) -> Result<(), String> {
    fs::rename(staging, out_dir).map_err(|error| {
        format!(
            "cannot commit port output {} -> {}: {error}",
            staging.display(),
            out_dir.display()
        )
    })
}

fn write_project_port(
    plan: &noxid_port_vue::project::VueProjectPort,
    out_dir: &Path,
) -> Result<(), String> {
    let staging = fresh_port_staging(out_dir)?;
    let result = (|| {
        for file in &plan.files {
            let Some(content) = &file.content else {
                continue;
            };
            write(&staging.join(&file.output), content)?;
        }
        write(
            &staging.join("noxid-port-report.json"),
            &plan.manifest_json(),
        )?;
        project::routes_json(&staging)
            .map_err(|error| format!("ported route graph failed validation: {error}"))?;
        commit_port_staging(&staging, out_dir)
    })();
    if result.is_err() && staging.exists() {
        let _ = fs::remove_dir_all(&staging);
    }
    result
}

fn write_package_port(
    plan: &noxid_port_vue::package::VuePortPackage,
    out_dir: &Path,
) -> Result<(), String> {
    let staging = fresh_port_staging(out_dir)?;
    let result = (|| {
        for component in &plan.components {
            let Some(content) = &component.noxid_source else {
                continue;
            };
            write(&staging.join(&component.output), content)?;
        }
        write(
            &staging.join("noxid-port-report.json"),
            &plan.manifest_json(),
        )?;
        commit_port_staging(&staging, out_dir)
    })();
    if result.is_err() && staging.exists() {
        let _ = fs::remove_dir_all(&staging);
    }
    result
}

fn parse_headless_recipe(
    value: &str,
) -> Result<noxid_headless_components::ComponentRecipe, String> {
    use noxid_headless_components::ComponentRecipe;
    match value.trim() {
        "Dialog" => Ok(ComponentRecipe::Dialog),
        "AlertDialog" => Ok(ComponentRecipe::AlertDialog),
        "Popover" => Ok(ComponentRecipe::Popover),
        "Tooltip" => Ok(ComponentRecipe::Tooltip),
        "Menu" => Ok(ComponentRecipe::Menu),
        "Select" => Ok(ComponentRecipe::Select),
        "Listbox" => Ok(ComponentRecipe::Listbox),
        "Tabs" => Ok(ComponentRecipe::Tabs),
        "Toolbar" => Ok(ComponentRecipe::Toolbar),
        "ToggleGroup" => Ok(ComponentRecipe::ToggleGroup),
        "Accordion" => Ok(ComponentRecipe::Accordion),
        "Collapsible" => Ok(ComponentRecipe::Collapsible),
        other => Err(format!("unknown native headless recipe `{other}`")),
    }
}

fn usage() -> String {
    base_usage().replace(
        "       noxid vet <package[@version]>\n       noxid vet [--sync]",
        "       noxid queue work [--queue name]\n       noxid queue status [--queue name]\n       noxid vet <package[@version]>\n       noxid vet [--sync]",
    )
}

fn base_usage() -> String {
    "usage: noxid <check|a11y|accessibility|design-system|inspect|graph|impact|rename|format|product|routes|machines|collections|resources|streams|agents|execution|validators|styles|devtools|compile|build|bundle|adapt|dev|benchmark> <file.nox|project-directory|Noxid.toml> [options]\n       noxid test [file.nox|project-directory|Noxid.toml] [--gate] [--json] [--seed <n> [--property <semantic-id>]]  (default: the current directory)\n         stdout is exactly one line, the JSON report; the run's logs and every [server] tracing record go to stderr as NDJSON\n         property timeout measures validator CPU time; a timeout + 1s wall-clock backstop kills synchronous hangs\n       noxid plan <file|project> <goal> [--constraint <text>] [--symbol <semantic-id>]\n       noxid context <file|project> <task> [--max-bytes <n>] [--max-nodes <n>] [--no-edges]\n       noxid manifest <file|project> [--projection compact|agent|full]\n       noxid describe <feature|operation|type|diagnostic|guide> [name]\n       noxid simulate <file|project> <component-id> <action-id>... [--state <machine-id=variant-id>]\n       noxid drift <before-file|project> <after-file|project>\n       noxid test-affected <file|project> <semantic-id>...\n       noxid index <file|project>\n       noxid search <file|project> <query> [--limit <n>]\n       noxid repair <file|project> [--safe|--inspect [--discard <transaction-id>]]\n         plan only by default; --safe applies the automatic set atomically and revalidates\n         --inspect lists the repair journals a refused recovery is blocking on and settles none;\n         --discard <id> then abandons that transaction, leaving every target exactly as it is\n       noxid scaffold <directory> <component|route|form|list-page|resource|state-machine> <Name> [contract options] [--write]\n       noxid undo <file.nox|project-directory|Noxid.toml> <transaction-id>\n       noxid new <directory> [--template app|counter] [--render client|universal]\n       noxid db new <name>\n       noxid db migrate\n       noxid db status\n       noxid vet <package[@version]>\n       noxid vet [--sync]\n       noxid agent-guide <core|scaffolding|interop|types|routing|storage|realtime|observability|reactivity|motion|remote-actions|ssr|testing|semantic-tools>\n       noxid example <counter|routed-app|reactive-effects|keyed-list|interactive-list|state-machine>\n       noxid mcp <file.nox|project-directory|Noxid.toml>\n       noxid mcp-http <file.nox|project-directory|Noxid.toml> [--bind <loopback-address>] [--token-env <name>] [--allow-origin <loopback-origin>]... [--stream]\n       noxid port <project|nuxt|vue-project|vue-package> <directory> [--out-dir <directory>] [--write] [--json]\n       noxid port-vue <file.vue|directory> [--json]\n       noxid vue-island <component.vue> [--name <name>] [--prop <name:Type>]... [--event <name:Type>]... [--write]\n       noxid headless <Recipe[,Recipe...]> [--out-dir <directory>]\n       noxid lsp".into()
}

const CONTEXT_PREAMBLE: &str = "Context first: call query_project { operation: \"context\" } with a byte budget and read only the surface it points you to; reach for this guide's detail after that, not before.";

const ROUTING_GUIDE_HEAD: &str = "Noxid routing\n- src/routes/+page.nox defines a page; +layout.nox wraps descendants.\n- Folder names form paths; [id] is a typed dynamic segment. Top-level `/server`, `/public`, `/netlify`, and `/.vercel` are compiler-owned deployment roots; put similarly named pages below a product prefix such as `/docs/server`.\n- Optional query inputs are consumed with `page ?? 1`, or exhaustively rendered with `#match page { Some(value) { ... } None { ... } }`; missing values use the compiler's Optional representation.\n- route { title: \"...\" render: ssr } opts into SSR.\n- Typed HTTP endpoints are .nox files under server/api/ (with /api prefix) or server/routes/ (root paths). End filenames with one explicit .get.nox, .post.nox, .put.nox, .patch.nox, or .delete.nox method.\n- endpoint Name { version: 1 params { ... } query { ... } body { ... } result: Type ... } declares the whole JSON boundary. Versions are positive and default to 1. Array query fields use one JSON-array query value, never repeated keys.\n- A bodyless endpoint is implemented by the exact `endpoint:<Name>@<version>` key in server/host.ts or server/host.js. Declared timeout, rate limit, idempotency, capabilities, and middleware are enforced; builds emit server/security.manifest.json.";

const ROUTING_GUIDE_TAIL: &str = "\n- `noxid adapt` forwards only the exact compiler-derived typed endpoint path shapes and enabled live/presence/OpenAPI/MCP doors to the generated handler; unrelated assets and prerendered routes keep static ownership. `noxid bundle`, `noxid dev`, and server-capable adaptation require `@farmfe/core`; the project installation takes precedence over the compiler installation. If a relocated compiler cannot find either, install it in the project with `pnpm add -D @farmfe/core@^1.7.0` to resolve `BUILD_HOST_MISSING`.\n- Browser middleware lives in src/middleware/<name>.js and may be declared by a layout, page, component, or endpoint. Its server-only variant lives in server/route-middleware/<name>.ts (or .js).\n- Modules directly under server/middleware/ are auto-discovered global server middleware. They run on every server request in lexical filename order before route middleware; no registration is required.\n- Browser code is emitted per route/component; unrelated chunks are not loaded.\n- GET endpoints may declare `cache: swr <seconds>` or `cache: isr <seconds>`; invalidate the versioned `endpoint:<Name>@<version>` tag through `/_noxid/revalidate`.\n- Every build emits `dist/api-contract.json`; commit the project-root `api-contract.json`. `noxid test --gate` rejects removed endpoints or fields, narrowed types, new required inputs, and method/path changes unless that endpoint's version increments. Additive changes update the baseline only after the whole gate passes.\n- An optional endpoint `description: \"...\"` supplies OpenAPI and MCP prose without changing authority. Every build emits deterministic OpenAPI 3.1 to `dist/api.openapi.json` (or the selected output directory), including the compiler-owned `x-noxid-signature`.\n- `[server] api_docs = true` serves `/_noxid/openapi.json`; `[server] mcp = true` serves streamable HTTP at `POST /_noxid/mcp` with exactly one typed tool per endpoint. Both default false and 404 while disabled. MCP reuses endpoint validation, capabilities, middleware, sessions, limits, and implementation dispatch. The security manifest records both opt-ins under `surfaces`.\n- Breaking contract differences fail with `error[API_CONTRACT_BREAKING_CHANGE]` and name every required endpoint version decision.\n- Netlify and Cloudflare publish only the filtered `public/` subtree; server bundles, API contracts, and compiler `app.*.json` metadata stay outside direct static hosting.\n- A page route and a `server/routes/` endpoint may not overlap the same request path, including through dynamic or catch-all segments. `ROUTE_PATH_CONFLICT` names both owners; move the endpoint under `server/api/` or give them distinct static segments.";

/// The routing guide quotes the multipart parser's uniform ceilings, so it
/// is generated rather than written down. The numbers have exactly one
/// source — the `noxid_ir` constants the emitted parser, the security
/// manifest, and OpenAPI are all built from — and spelling them here as
/// prose would create a fourth copy that can drift without failing a build.
static ROUTING_GUIDE: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
    format!(
        concat!(
            "{head}",
            "\n- Uploads are declared, never inferred: a mutating endpoint body may use `File(maxSize: 10mb, types: [image/png])` or `Array<File(...)>`. Both constraints are mandatory; the magic-byte allow-list is image/png, image/jpeg, image/gif, image/webp, application/pdf, application/zip, or text/plain. Only declared upload endpoints accept multipart; each part is cut at its own limit plus one byte, and Content-Type is never trusted. OpenAPI and security.manifest.json publish every constraint. Put scalar sibling fields BEFORE the file parts in a multipart body: a streaming parser cannot see a later part, so a scalar sent after a file is only refused once that file has been fully ingested. An empty part is refused with UPLOAD_EMPTY_FILE — there are no bytes to verify a declared type against. The manifest and OpenAPI also publish the parser's own uniform ceilings, and these are the numbers the emitted parser enforces: maxParts: {parts} for Array<File> and 1 otherwise, aggregateMaxSizeBytes = maxSizeBytes x maxParts, partHeaderMaxBytes: {header}, scalarFieldsMaxBytes: {scalar}, filenameMaxBytes: {filename} UTF-8 bytes, truncated at a code-point boundary rather than refused. Refusals are MULTIPART_PART_LIMIT, MULTIPART_HEADERS_TOO_LARGE, and ENDPOINT_BODY_TOO_LARGE; an Array<File> field's real bound is its per-part cap times maxParts.",
            "{tail}"
        ),
        head = ROUTING_GUIDE_HEAD,
        tail = ROUTING_GUIDE_TAIL,
        parts = noxid_ir::MULTIPART_MAX_PARTS,
        header = noxid_ir::MULTIPART_PART_HEADER_MAX_BYTES,
        scalar = noxid_ir::MULTIPART_SCALAR_MAX_BYTES,
        filename = noxid_ir::UPLOAD_FILENAME_MAX_BYTES,
    )
});

fn agent_guide(topic: &str) -> Result<String, String> {
    Ok(format!("{CONTEXT_PREAMBLE}\n{}", agent_guide_body(topic)?))
}

fn agent_guide_body(topic: &str) -> Result<&'static str, String> {
    match topic {
        "core" => Ok(
            "Noxid agent quick reference\n- Source files use .nox; projects use Noxid.toml and src/routes/+page.nox.\n- Start from `noxid new <dir> --template app` (or `--template counter` for the minimal single-page project), then `pnpm install --frozen-lockfile`; the `scaffolding` topic states what that template already contains and how its vendored plugins stay honest.\n- Run `noxid check <file>` or `noxid build <project>`; do not infer success from prose.\n- Author typed scenario blocks for component behavior and run `noxid test [file-or-project] --gate` (the path defaults to the current directory); it executes emitted JavaScript and returns structured results.\n- Components use state, computed, actions, view, and style blocks. Actions batch writes.\n- Expressions support + - * / == != < <= > >= && || ??, unary ! and unary -, Int, Float, String, and Boolean literals. Int and Float never mix implicitly; arrays, maps, structs, and tagged variants compare recursively by language value.\n- Compiler-owned pure scalar functions need no import: len, contains, startsWith, trim, lower, upper, min, max, abs, round, floor, ceil, toFloat, toInt, and toString. They are free functions, not methods; toInt truncates toward zero, and numeric overloads never mix Int with Float.\n- Use `maybe ?? fallback` to consume Optional<T>; the fallback must be T (or Optional<T> for chaining), and the result is typed by the compiler. Use exhaustive `#match maybe { Some(value) { ... } None { ... } }` when the cases render different structure.\n- Views branch with #if / #else if / #else; conditions must be Boolean. Use `#if open transition 200ms { ... }` for a compiler-visible bounded exit that can be interrupted without remounting.\n- Actions support `let` locals, if/else statements, calls to sibling actions (recursion is rejected), and struct field assignment like todo.note.text = next.\n- Event handlers take arguments evaluated at event time: +click={remove(todo.id)}. The bare form +click={save} receives the typed DOM event.\n- Components compose with one <slot />: <Card>...</Card> children render in the parent's scope.\n- File-scoped `fn name(params): Type` declares pure reusable functions (defined before use); backtick template strings interpolate: `Hello {name}`. Share components, document types, and file-scoped functions with `import { Card, Incident, severityLabel } from \"./domain.nox\"`; each name keeps the defining module's stable semantic ID, and cross-file cycles are rejected.\n- Scalar builtins include len, contains, startsWith, endsWith, trim, lower, upper, capitalize, camelCase, kebabCase, snakeCase, padStart, padEnd, repeat, replaceAll, min, max, abs, clamp, round, roundTo, floor, ceil, toInt, toFloat, toString, and range(a, b) for numeric loops.\n- Prefer tagged machines and exhaustive #match over correlated booleans.\n- Prefer keyed #for and explicit +event handlers. There is no VDOM.\n- An LLM call is a declared boundary: `model Name { provider: anthropic|openai|openai-compatible id: \"...\" secret: DECLARED_KEY }` in a direct server/models/<name>.nox file. Server modules import models/types/generateText/generateObject/streamText from \"noxid:server\". generateObject validates the answer through the emitted boundary validator, retries up to the declared `retries:` (re-attempts after the first, so `retries: N` makes at most N+1 provider attempts), then fails MODEL_OUTPUT_INVALID. Scenarios stub with `given: model Name = text|object|tokens|fails ...`; an unstubbed call fails MODEL_STUB_REQUIRED naming the model and the call site, and never reaches a provider.\n- An agent becomes a server-side loop when it declares `model:`; without it, it stays the client-only typed session. Add `instructions:` (inline prose or a `server/agents/<name>.md` path embedded at build time) and optional `maxTurns:` (1..64, default 8).\n- An agent has no separate tool definitions: its tools are the endpoints whose declared capabilities its `can` covers in full and its `cannot` does not touch. A denied endpoint is absent from the registry, never described to the model, and not in `server/security.manifest.json` under `agents[].tools`. A tool call crosses the endpoint's own validator, middleware, limits, and audit, under `Principal.Agent { id: AgentId(<name>), actingFor }`.\n- The generated doors are `POST /_noxid/agents/<Agent>/runs` (capability `agents.<name>.run`) and `POST /_noxid/agents/<Agent>/runs/<runId>/resume` (`agents.<name>.resume`). A host authorizer that answers \"defer\" pauses the run durably and emits PermissionRequired then Paused(runId); `#stream` exhaustiveness requires the Paused case and `session.resume(runId)` continues it.\n- ToolStarted/ToolCompleted/PermissionRequired payloads are filled by the loop, so their declared type must be String or a record whose fields are among name, tool, endpoint, capability, arguments, summary, status, ok, code, message, runId, turn, agent, result. Anything else is AGENT_EVENT_UNREPRESENTABLE at build time.\n- Query the local semantic compiler with query_project before reading many files.\n- Reference prose is chunked: `noxid describe guide <topic>` returns one topic under 6 KB, and `llms.txt` indexes byte-sized `llms/<topic>.txt` chunks. Load the index and the chunk your task needs, never `llms-full.txt`.\n- MCP is local-only; remote binds and origins are rejected.",
        ),
        "scaffolding" => Ok(
            "Noxid scaffolding\n- Start from `noxid new <dir> --template app`, then `pnpm install --frozen-lockfile`: a compile-tested full-stack project that passes `noxid test --gate`, `noxid build`, and `noxid adapt node` with zero edits and no service running (SQLite through Node's builtin node:sqlite). It already contains one route with a typed form, one typed endpoint under server/api with params/result/capabilities/timeout/limit plus a scenario that makes a real request through the shipped handler, one scoped and one unscoped table in server/utils/schema.ts that the endpoint reads and the action writes through the vendored Drizzle adapter, a forward migration, global session middleware, three requirements with passing scenarios, and a `live` resource rendered over every lifecycle case. The scaffold is secure by default and there is no anonymous principal in it: the page shows a sign-in form until there is a session and the board once there is, `signIn`/`signOut` mint and expire the signed noxid_session cookie inside server/middleware/session.ts, and every other endpoint and remote action arriving without that cookie is refused before any handler runs — an endpoint answers 403 with error.code SESSION_PRINCIPAL_REQUIRED and a teaching message, a remote action answers the runtime's own 403 BOUNDARY_MIDDLEWARE_DENIED carrying x-noxid-refusal: SESSION_PRINCIPAL_REQUIRED, because direct middleware responses are reserved to SSR routes. The sign-in action is a starter placeholder that signs a cookie for the display name the page collected; replace it with the identity provider you actually run and keep the shape — one principal resolved in middleware, a refusal when there is none. `noxid new` runs no package manager: it vendors the vetted plugin files into plugins/ byte-identically with a hash ledger (.noxid-plugins.json), pins the reviewed package versions, and `noxid build` refuses a drifted file (PLUGIN_VENDOR_DRIFT) or a lockfile that disagrees (NPM_IMPORT_UNVETTED). Run `noxid vet` inside the project to compare those vendored files with the copies your `noxid` embeds, and `noxid vet --sync` to rewrite the drifted ones and the ledger from your compiler; neither ever updates a file silently. Edit that shape instead of assembling one; `--template counter` is the minimal single-page project. `noxid new` refuses a non-empty directory (SCAFFOLD_TARGET_NOT_EMPTY), refuses a target outside the current directory (SCAFFOLD_TARGET_ESCAPES), and never overwrites.",
        ),
        "interop" => Ok(
            "Noxid JavaScript interop\n- Every import is typed by declarations, typed JSDoc, or an adjacent `.nox-contract`; untyped JavaScript fails closed.\n- `pure` functions may be used in typed expressions.\n- `impure` functions may be evaluated only inside explicit client actions; calls, arguments, returned values, reads, writes, and graph invocation edges stay compiler-visible.\n- Impure calls remain illegal in state initializers, computed values, views, file-scoped functions, effects, watches, SSR/server/edge/worker actions, and remote bodies.\n- External return values cross generated validators before trusted application state can observe them. Promise-like results fail closed.\n- Project-local JavaScript is copied into deterministic external assets by `noxid build`; `[assets] directory = \"src/assets\"` declares additional regular files. Symlinks and output collisions are rejected.",
        ),
        "types" => Ok(
            "Noxid types and data vocabulary\n- `type UserId = distinct String` declares a nominal scalar over String, Int, Float, or Date. It inherits nothing: equality with itself, plus whatever the declaration opts into with `allow [concat|add|subtract|compare]`. No implicit widening to the base, no builtins, no cross-distinct operations. Construct with `UserId(value)` and unwrap with `.base()`; both have stable semantic IDs and appear as invokes edges wherever they occur, including inside action, effect, and handler bodies, so `noxid impact <project> distinct-unwrap:UserId` lists every site where an id leaves its type. Construction and `.base()` erase to the value itself in all three emitters, so the wire and database representation is always the base; boundary validators re-check the base shape, and OpenAPI and `api-contract.json` keep the distinct name. Imported structs carry their distinct field types across the file boundary. Use `.base()` where a plain scalar is structurally required, such as a `#for` key.\n- `PrincipalId` and `AgentId` are compiler-owned `distinct String` types with an empty allow list, and `Principal` is the compiler-owned union of `System`, `User { id: PrincipalId }`, and `Agent { id: AgentId, actingFor: Optional<PrincipalId> }`. All three are pre-declared in every program: declaring one refuses with `PRINCIPAL_ID_RESERVED`, and constructing one in source — `PrincipalId(value)`, `AgentId(value)`, any `Principal` variant, or the named-field spelling `User(id = value)` — refuses with `PRINCIPAL_CONSTRUCTION_RESERVED`, because only the generated server request boundary builds a principal, from the middleware context. A compiler-owned `handler` for an endpoint, task, or queue binds `context`, whose single field is `principal: Principal`; those three are the only surfaces that bind it today, a remote action receives no `context` (pass what it needs as a typed parameter) and a live resource has no compiler-owned handler; consume it with an exhaustive statement `#match context.principal { System { } User(user) { } Agent(actor) { } }`. Omitting a case fails to compile, and the `Agent` case is real: an agent acting for a user resolves scoped access through `actingFor`, never through its own id. `user.id` is a `PrincipalId`; `.base()` is the deliberate way out and every unwrap is graph-visible, so `noxid impact <project> distinct-unwrap:PrincipalId` lists every place a principal leaves its type. Client and SSR code never sees a principal, and `Principal` is not a wire type; `PrincipalId` and `AgentId` are, erasing to `String` and publishing as named OpenAPI/MCP schemas. Where a Noxid declaration names a scoped table's principal column, its type must be `PrincipalId` (`SCOPED_COLUMN_REQUIRES_PRINCIPAL_ID`).\n- Struct rows are removed by key with items.removeWhere(field, value).\n- Collection queries are typed Array/Map methods. Arrays support count, countWhere, where, firstWhere, first, last, reversed, unique, sum, average, take, drop, contains, join, sortBy, sortByDesc, minOf, maxOf, sumOf, averageOf, groupBy, and countBy. Maps support get, count, keys, values, and entries. first/last/minOf/maxOf/average/get return Optional values (use ?? or #match). Field-based forms take a bare field name; there are no lambdas.\n- Dates are instants: parseDate(s) -> Optional<Date>; formatDate(date, pattern, tz) and startOfDay(date, tz) require an explicit IANA timezone; addDays/addHours/addMinutes/addSeconds and diffMillis/diffDays are fixed-duration math; dateFromMillis/dateToMillis bridge Int; Date compares with == < > etc. There is no now() yet - time enters through data.\n- Arrays derive values with items.count(); Array<Struct> adds countWhere/where and scalar-field groupBy/countBy. Maps are frozen plain objects with no v1 literals or mutation; consume them with get/count/keys/values/entries, whose key-facing views are sorted. entries returns Array<MapEntry<K,V>> for keyed #for. Use bare typed field names, not predicate closures or items.length.",
        ),
        "routing" => Ok(ROUTING_GUIDE.as_str()),
        "storage" => Ok(
            "Noxid storage\n- Server host, utility, and middleware modules may `import { storage } from \"noxid:server\"`. `storage(namespace)` provides async JSON get/set/delete/list; set accepts `{ ttl: seconds }`. `[server] storage = \"memory\"` is the default; use `\"fs\"` for one-process persistence or `\"postgres\"` for shared state across replicas. `[server] db_pool` defaults to 10 and configures the database adapter and queue pool; serverless functions with an external pooler should normally set it to 1. The Node adapter drains requests, tasks, the current queue job, and SSE on SIGTERM/SIGINT; `[server] shutdown_timeout_ms` defaults to 20000. It refuses startup with `SERVER_LIFECYCLE_EXPORT_MISSING` when the Farm handler lacks a lifecycle export required by the built features.\n- Hosts receive an opaque FileRef with sniffedType, size, sha256, sanitized metadata-only name, plus stream(), bounded bytes(), and store(namespace). `[server] blob_dir` defaults to `.noxid/blobs`; stored paths are namespace/content-hash only.\n- Database migrations are forward-only SQL files under server/db/migrations/. Use `noxid db new <name>`, inspect the SQL, then run `noxid db migrate`; `noxid db status` reports applied and pending files. Applied checksums are immutable. DATABASE_URL accepts `postgres://`, `mysql://`, `sqlite://<path>`, or `sqlite::memory:`. Install the selected network driver with `pnpm add postgres@3.4.9` or `pnpm add mysql2@3.23.4`; the migration runner uses project-rooted Node resolution, including hoisted workspace dependencies, and never falls back to the compiler installation. Relative SQLite paths resolve from the project root and require an existing parent; SQLite uses Node 22.16+'s full builtin node:sqlite API with transactional DDL. MySQL reports its implicit DDL-commit limit while retaining transactional DML apply.\n- Scoped database access takes only a runtime-created endpoint/task/queue context, the adapter-owned eq predicate, and db.transaction. Missing, mismatched, system-only, raw-Drizzle, or fabricated authority fails with DATA_SCOPE_VIOLATION. PostgreSQL adds forced RLS through transaction-local noxid.principal; MySQL and SQLite retain the same adapter enforcement. Agents have closed typed endpoints and no raw SQL surface. Runtime adapter enforcement is the security boundary. Compiler-emitted server output is eval-free and limited to an exact literal driver-import allowlist. Developer-authored server/host.* and server/** modules are a trusted deployment tier and are not policed by the generated-output scanner. Queue principals serialize stably and legacy NULL _noxid_jobs.principal rows mean system.\n- Redis is the lower-latency shared storage option: set `[server] storage = \"redis\"`, declare `REDIS_URL` in `[server] secrets`, and provide one `redis://` or TLS `rediss://` endpoint. Cluster and sentinel layouts fail closed in v1. During a disconnect, rate admission denies, cache reads miss, and idempotent requests return a retryable 503; the driver never falls back to process memory.\n- Durable jobs live in direct server/queues/<name>.nox files as `queue Name { payload { ... } retry: 3 backoff: 30s }`. Omit the handler for the exact `queue:<Name>` host key. Payloads validate on enqueue and Postgres claim; exhausted retries are queryable as dead-letter. Server modules import `enqueue` from `noxid:server`. Run `noxid queue work [--queue name]` or `noxid queue status [--queue name]`; `[server] queue_worker = true` embeds the Node worker. Queues require a shared `postgres://` DATABASE_URL; when a MySQL, SQLite, or other non-Postgres URL is known during build or adaptation, the compiler refuses with `QUEUE_REQUIRES_SHARED_DATABASE` instead of emitting an unusable worker. Queue scenarios require `when: enqueue(...)` and an explicit UTC clock.\n- Startup modules in server/plugins/*.{ts,js} default-export a function receiving frozen { environment, storage, host }; they run once in lexical filename order, and a throw aborts startup.\n- Scheduled server work lives in server/tasks/<name>.nox as `task Name { schedule: \"0 3 * * *\" handler { ... } }`; cron has exactly five fields and no seconds. Omit the handler to use the exact `task:<Name>` host key; builds emit server/tasks.manifest.json.\n- Task triggers use POST /_noxid/tasks/<name> and require the `tasks.run` capability. Run one manually with `noxid task run <name>`; adapters own production scheduling.",
        ),
        "realtime" => Ok(
            "Noxid realtime\n- Add bare `live` inside a resource declaration to enable compiler-owned invalidation publication. Successful actions, mutating endpoints, and completed queues derive one module-local live target; multiple live candidates require `invalidates [Name]` or `invalidates none`. GET/stream reads never publish and cannot declare invalidation. Existing action invalidation of non-live cache resources is unchanged. Publication follows result validation or durable completion and uses the exact request/restored queue principal.\n- Compiler-owned live publishing follows `[server] storage`: memory/fs use process fan-out, Postgres uses LISTEN/NOTIFY, and Redis extends the first-party RESP connection roles. `[server] live_driver` may override with memory/postgres/redis; `[server] live_coalescing_ms` defaults to 250. A project with live resources or presence must declare a deployment-stable `[app] id` matching `[a-z][a-z0-9_]{0,31}`; replicas and rolling versions reuse it, while unrelated applications sharing a backend use distinct IDs. Topics are derived from that application security domain, semantic IDs, and the runtime-owned canonical principal; invalidations carry no payload, and the substrate is byte-pruned without `live`/presence declarations. Commit and publication are deliberately separate: a post-commit driver failure is reported but cannot pretend to roll application state back.\n- Live resource acquisition has no authored subscription API. The compiler installs one project SSE controller at `<base>/_noxid/live`; mounted live resources register internally and invalidations flow through the existing Refreshing(previous) -> Ready validated refetch lifecycle. The endpoint replays only the compiler-selected route middleware, authorizes each resource capability, partitions by the canonical principal, and emits only semantic resource IDs. Bursts coalesce per resource, dirty in-flight requests earn one trailing refetch, and every fresh/resumed exact set receives a cursor-free sync fence after subscription installation. Resume cursors are bounded to the exact principal, route, and resource set; unsafe cursors reset and invalidate once. Client and server transport bytes are pruned when no resource is live.\n- Declare typed ephemeral membership inside a client-owned component with `presence { ttl 30s name: String = displayName cursor: Optional<Point> = cursor }`. The compiler creates component-qualified record/member/snapshot types and the fixed exhaustive `#stream presence` cases Snapshot, Joined, Updated, Left, Completed, and Failed. There are no authored channels, tokens, member IDs, joins, subscriptions, or transport calls. Fields are reactive; writes and heartbeats serialize; owner disposal leaves; transient failure rejoins from a fresh Snapshot with the same bounded credential; permanent failure closes the typed stream.\n- Presence shares the live SSE controller, canonical WO-40 principal, compiler-selected typed route middleware, pub/sub driver, storage driver, and generic development trace capture door. Storage, rate/lease/sweep keys, logical topics, and physical driver channels are partitioned first by `[app] id`, then by canonical principal plus route instance as appropriate; every external record/event is validated closed. A finite shared lease serializes mutations and TTL repair, and unclean expiry emits one Left without persisting to application tables. Operational abuse/join/member admission accepts bounded authenticated middleware/session identity, bounded host-adapter `environment.requestIdentity`, or a canonical non-system principal independently of visibility; request-controlled forwarding headers are never trusted. Anonymous system-principal writes without one fail 403 before rate buckets are created, and membership is authenticated before selecting a member bucket. SSR/prerender-only ownership and unstubbed scenarios are rejected.\n- Typed server push is `stream endpoint Name { result: Stream<T> timeout: 5m ... }` in `server/api/**/*.get.nox`. The exact `endpoint:<Name>@<version>` host function returns AsyncIterable<T>; every event is validated before compiler-framed SSE emission.\n- Stream endpoint timeout and rate limit apply per connection. Heartbeats and bounded Last-Event-ID resume are generated; body, cache, idempotency, compiler-owned handlers, ordinary endpoint scenarios, non-GET methods, and server/routes placement fail closed. Client code consumes a matching ordinary stream through `streams` and exhaustive `#stream`; WebSocket syntax is not available in phase one.",
        ),
        "observability" => Ok(
            "Noxid observability\n- `[server] tracing = \"requests\"` is the default and emits one-line `noxid.trace.v1` request start/end JSON to stdout. Use `\"full\"` for middleware, endpoint/action, refusal, capability-denial, task, queue, queue-worker, and live publish/delivery duration spans keyed by semantic IDs; use `\"off\"` for silence. `[server] tracing_export = \"stdout\"` is the default; select `\"otlp\"` for the first-party OTLP/HTTP JSON exporter. Declare `OTEL_EXPORTER_OTLP_ENDPOINT` and credential-bearing `OTEL_EXPORTER_OTLP_HEADERS` in `[server] secrets`; OTLP without an endpoint declaration fails with `TRACING_EXPORT_ENDPOINT_REQUIRED`. OTLP `service.name` uses the declared `[app] title`, then the package name, then `noxid.application`; set `[server] tracing_service_name` for an explicit deployment identity. `durationMs`/`noxid.duration_ms` appears only for measured intervals; unmeasured starts, refusals, and state transitions omit it. Valid W3C `traceparent` propagates and wins over `x-noxid-trace`; its remote parent attaches only to the request root, while endpoint and loader work nest locally. Span fields are allowlisted: bodies, arguments, queue/live payloads, middleware context, environment data, and secret names or values are never logged. Generated server entry points expose a bounded tracing drain hook; development handlers expose one schema-generic capture door for all spans, while production handlers prune that capture door completely.",
        ),
        "reactivity" => Ok(
            "Noxid reactivity\n- state values are signals; computed dependencies are compiler-derived.\n- watch observes selected state; effect owns side effects and cleanup. Neither returns a value.\n- +input/+change/+click are explicit listeners. value:bind is explicit two-way state binding.\n- Call-form handlers +click={remove(item.id)} evaluate arguments when the event fires, so keyed #for rows pass their current values.\n- Actions are batched transactions; `let` locals are not reactive, and struct field assignment replaces the whole signal so subscribers see one change.\n- Resource identity is derived from declaration plus ordered typed arguments; equal identities share one cache entry and in-flight request. Declare `cache 30s`, `refresh on focus`, `refresh on reconnect`, and `refresh every 5m`; unused trigger runtime is pruned.\n- Use `prefetch on hover` / `prefetch on visible` on supported route links or resource-owning component invocations with inputs available before mount. Prefetch fills the ordinary shared cache.\n- Array and Map queries are typed derived expressions whose base, field, and value references remain reactive dependencies; grouping maps update keyed #for regions through the ordinary entries() Array.\n- Dynamic regions own subscriptions and dispose deterministically. `#if condition transition 200ms` keeps the same owner reactive during exit, cancels false-to-true interruption without remounting, and force-disposes at the deadline.\n- #for must have a stable key when identity matters.",
        ),
        "motion" => Ok(
            "Noxid motion\n- Property transitions and enter animations use ordinary scoped CSS.\n- Use `#if open transition 200ms { ... }` for a compiler-visible, bounded, interruptible exit lifetime.\n- Use `<ul attach:animate={ duration: 150ms }>` only on an element whose direct dynamic region is a keyed #for. The duration is a bounded literal, not an expression.\n- attach:animate installs after client mount or hydration adoption and is destroyed with the owning Owner; SSR renders unchanged markup.\n- The vetted @formkit/auto-animate adapter and its runtime feature are pruned when no attachment declares them.\n- Unknown names/keys, non-keyed containers, and direct exit-transition conflicts fail with structured teaching diagnostics.",
        ),
        "remote-actions" => Ok(
            "Noxid typed remote actions\n- A client action may perform one top-level sequential remote await: `let outcome = await siblingRemote(name: value)`.\n- Every remote argument is named and statically checked against the sibling server, edge, or worker action.\n- Consume the binding immediately and exhaustively with `#match outcome { Ok(value) { ... } Err(error) { ... } }`.\n- The result is `Result<T, RemoteError>`; RemoteError has compiler-owned String fields `code` and `message`, so remote failure is not a JavaScript exception channel.\n- State writes before await commit in the first action transaction. The remote boundary runs outside a transaction; the selected arm and following statements run in a second transaction.\n- After success, resource invalidation is graph-derived when exactly one target exists. Multiple candidates fail with `AMBIGUOUS_RESOURCE_INVALIDATION`; write `invalidates [Products]` or `invalidates none` on the remote action. Failures do not invalidate.\n- There is no implicit retry, parallel await, cancellation, discarded result, or nested await in v1. Unsupported shapes fail with structured diagnostics.\n- Executable scenarios must stub the exact boundary with `given action = Ok(<literal>)` or `given action = Err(RemoteError(code = \"...\", message = \"...\"))`. Unstubbed remote awaits fail closed and never reach the network.\n- SSR never executes actions, and production runtime options cannot forge scenario boundary stubs.",
        ),
        "ssr" => Ok(
            "Noxid rendering\n- Client is the default. route render: ssr plus render { mode: universal } enables SSR and hydration.\n- Default-slot children render through a parent-scope server thunk; eager hydration adopts the matching slot marker range and preserves node identity. Deferred-hydration islands with slot children are rejected.\n- On SSR routes, default-slot children keep the parent's scope; eager hydration adopts their server marker range without recreating DOM. Deferred-hydration islands with slot children fail closed.\n- SSR-validated resource snapshots seed the shared client cache with the server `renderedAt` timestamp. Transit time counts toward `cache <duration>`, so an already-stale snapshot hydrates as Refreshing rather than restarting its TTL.\n- Exit-transition timing is client-only: SSR renders the final #if state, while eager hydration adopts a true region and then enforces its declared owned deadline.\n- Server-only components emit no browser module. Islands hydrate by declared strategy.\n- Use loaders for request data and keep host implementations in the auto-detected server/host.ts (or server/host.js); [server] runtime and secrets remain in Noxid.toml, but [server] entry was removed.\n- Keep shared server modules under server/utils/. Global server middleware in server/middleware/ runs before route middleware on SSR documents and action requests.\n- Build output is route-isolated and exposes a server fetch handler only when needed.",
        ),
        "testing" => Ok(
            "Noxid testing\n- `noxid test` writes exactly one line to stdout: the JSON report. The run's logs and every [server] tracing record go to stderr as NDJSON, so stdout parses as one JSON object even under `tracing = \"full\"`.\n- Write `scenario Name` blocks beside the component behavior they verify.\n- `given: state = literal` accepts deterministic typed literals only.\n- Stub an owned resource with its closed lifecycle, such as `given customers = Ready([...])`; add deterministic cache age with `given customers = Ready([...]) aged 45s`. `aged` requires a cached resource and Ready/Refreshing data; unaged givens pass no age.\n- Resource scenario seeds are compiler-authorized and non-I/O. Successful stubbed remote mutations still apply derived or explicit invalidation; `invalidates none` preserves Ready. Request-count/dedup proof belongs in runtime behavioral tests because scenarios have no request-count or JavaScript escape expression.\n- Stub an owned stream with a finite typed event array, such as `given feed = [Started, Completed(result)]`. Compiler-owned presence uses the same closed boundary: `given presence = [Snapshot(...), Joined(...), Left(\"member-id\")]`; scenario expressions may assert the exact sequence, but actions and general views cannot inspect the buffer.\n- Only acquisitions named by validated givens are stubbed, so resource factories, network requests, stream connectors, and live presence transport do not run. Agents and unstubbed external boundaries fail closed.\n- Coalescing and principal isolation are transport properties, proven against the generated memory driver with two canonical principals and exactly one same-principal delivery; do not invent scenario counters or a JavaScript escape.\n- `when: action(args)` invokes compiler-checked client actions; remote actions fail closed.\n- A task scenario uses `when: run()` to invoke its handler directly. A bodyless task may be stubbed with `given: TaskName = value`; the scheduler is never mocked, and compiler-owned task handlers cannot be replaced.\n- Test the loop with a `scenario` block on the agent: `given: agent Name = turns [ text \"...\", tool <Endpoint> { field = value }, final { field = value } ]`, optional `given: authorizer defers <capability>`, `when: run(input: <typed input>, resume: true)`, and `expect:` over emitted, tools, output, refusal, paused, resumed, turns. Scripted turns are checked against the registry and the tool endpoint's contract at build time; an unscripted turn fails MODEL_STUB_REQUIRED and never reaches a provider.\n- Endpoint scenarios use `given: [\"file <body-field> bytes <canonical-base64> as <mime>\"]` for deterministic success, oversize, and wrong-magic cases.\n- `expect: booleanExpression` observes state and computed values through the ordinary typed expression grammar.\n- Typed `invariant` assertions run after mount, after every given, and after every action; a breach stops later steps and reports its semantic ID, checkpoint, expression, and actual referenced values.\n- Equal arrays, maps, structs, and tagged variants compare recursively by language value, so a compound literal given can be asserted directly.\n- Run `noxid test <file-or-project> --gate`; stdout is deterministic JSON and stderr is the human summary.\n- `--gate` requires every requirement to have a passing covering scenario and rejects prose-only scenarios.\n- Use local read-scoped MCP `run_scenarios` for the same JSON report, or `run_affected_tests` to execute only graph-selected scenarios; neither operation writes project files.\n- Pagination/infinite resources and automatic optimistic rollback are phase 2; do not invent scenario syntax for them.\n- Prose steps and prose invariant assertions are migration documentation, not proof, and emit warnings.\n- Scenario execution uses compiler-emitted component or task JavaScript and the feature-pruned runtime rather than a Rust interpreter.\n- Endpoint and queue boundaries may declare `property Name { runs: 100 expect: validates or refuses }` or `expect: refusal is structured`; this is a closed vocabulary.\n- Property generation is deterministic from the property identity plus run index and mixes compiler-known type categories with the versioned hostile corpus, including getter, prototype-key, and cyclic JS shapes.\n- Property failures report the exact seed, faithful shrunk JavaScript value, and a paste-ready seeded CLI replay command. Omitted runs default to 100, and `--gate` enforces a 100-run floor.\n- Tasks have no input contract, so task properties fail closed; use task scenarios for cron handler behavior.\n- Pagination/infinite resources, property roundtrip, custom property predicates, and automatic optimistic rollback are later phases; do not invent syntax for them.\n- Property execution uses compiler-emitted boundary-validator JavaScript and the feature-pruned runtime rather than a Rust interpreter.\n- On an input with multiple properties, replay with `--seed <n> --property <semantic-id>`; the selector prevents one property's seed from being applied to another. Run replay separately from `--gate`, which always owns the full 100-run floor. A boundary's `timeout:` bounds validator CPU time after import; the runner also kills validation after that timeout plus a 1s wall-clock backstop so synchronous hangs stay killable.",
        ),
        "semantic-tools" => Ok(
            "Noxid semantic tools\n- Start with query_project operation=summary and reuse its snapshot.\n- Use operation=delta with since=<snapshot> after edits.\n- Set limit/maxBytes on queries.\n- semantic_edit accepts a stable-ID operation and JSON payload, validates, then requires confirmation.\n- validate_project returns structured diagnostics and a repairPlan.\n- Every classified diagnostic carries classification (automatic|review), rewrite, the uniqueness condition, the before/after span text, and the alternatives the diagnostic already enumerates. Read alternatives instead of guessing a name.\n- `noxid repair <file|project>` plans only and writes nothing; `--safe` applies just the automatic set as one compiler-revalidated transaction and restores byte-exact originals on failure.\n- A multi-file rename is not atomic on POSIX, so the promise is about the compiler's view: every command that reads project sources settles an interrupted `repair --safe` before it reads a source byte. A journal whose renames all finished is completed; any other rolls back to the originals byte for byte. You never need to run `repair` to clean up after one — `check` will do it, and says so on stderr with the transaction id.\n- A repair is automatic only when the diagnostic determines it uniquely: array `.length` to `count()`, a single near-candidate rename for a collection query, function, or field, `toFloat(...)` on the Int side of an Int/Float mix, an Int literal in a declared Float position, dropping a pure `??` fallback, one expected punctuation token, and a mismatched closing tag. Each applied repair carries a proof: the recompile, the noxid drift result, and the graph scope it stayed inside.\n- Everything else is review with a concrete proposed edit: missing cases, placeholder values, duplicates, units, imports, accessibility meaning, and every security or styling boundary. Apply those yourself; the compiler will not.\n- `noxid dev` exposes a development-only semantic panel with compiler/build overview, exact route matching, bounded graph/impact traversal, reverse DOM ownership, and reduced {id,title,description?} route cards. Impact follows emitted graph edges only and never invents cross-wire relationships.\n- Production runtimes prune the panel, recorder, and DevTools runtime feature; app.devtools.json remains inert compiler metadata.\n- The published context surface is budgeted the same way as query_project: `llms.txt` indexes every `llms/<topic>.txt` chunk with its exact byte size and a one-line scope (each chunk at most 24 KB), and the MCP describe operation takes kind=guide for one agent-guide topic. Point a model at the index and a chunk, never at `llms-full.txt`.\n- stdio is preferred; MCP HTTP is loopback-only and bearer authenticated.",
        ),
        _ => Err(format!("unknown agent-guide topic `{topic}`")),
    }
}

fn compiler_example(name: &str) -> Result<&'static str, String> {
    match name {
        "counter" => Ok(
            "component Counter {\n    state { count: Int = 0 }\n    computed { doubled = count * 2 }\n    actions { increment() { count = count + 1 } }\n    view { <button +click={increment}>Count {count}; double {doubled}</button> }\n}",
        ),
        "routed-app" => Ok(
            "src/routes/+page.nox\ncomponent HomePage {\n    route { title: \"Home\" }\n    view { <main><h1>Home</h1><a href=\"/about\">About</a></main> }\n}",
        ),
        "reactive-effects" => Ok(
            "state { query: String = \"\" change: String = \"Waiting\" }\ncomputed { label = \"Filter: \" + query }\neffects { watch query as recordQuery(current, previous) { change = previous + \" -> \" + current } }\nview { <input value:bind={query} /><p>{label}</p><p>{change}</p> }",
        ),
        "keyed-list" => Ok(
            "state { items: Array<Int> = [1, 2, 3] }\nview { <ul>#for item in items key item { <li>{item}</li> }</ul> }",
        ),
        "interactive-list" => Ok(
            "state { items: Array<Int> = [1, 2, 3] selected: Int = 0 }\nactions {\n    select(value: Int) { selected = value }\n    drop(value: Int) { items.remove(value) }\n}\nview {\n    <ul>\n        #for item in items key item {\n            <li>\n                {item}\n                <button +click={select(item)}>select</button>\n                <button +click={drop(item)}>delete</button>\n            </li>\n        }\n    </ul>\n    #if selected > 0 {\n        <p>selected: {selected}</p>\n    } #else {\n        <p>nothing selected</p>\n    }\n}",
        ),
        "state-machine" => Ok(
            "machine Request { Idle; Loading; Ready(String); Failed(String); Idle -> Loading on submit; Loading -> Ready on resolve; Loading -> Failed on reject; }\nstate { request: Request = Idle }\n#match request { Idle { <p>Idle</p> } Loading { <p>Loading</p> } Ready(value) { <p>{value}</p> } Failed(message) { <p>{message}</p> } }",
        ),
        _ => Err(format!("unknown compiler example `{name}`")),
    }
}

#[cfg(test)]
mod tests {
    use super::scaffold::scaffold_project;
    use super::{agent_guide, ensure_noxid_source, parse_headless_recipe, parse_vue_island_field};
    use std::fs;
    use std::path::Path;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[test]
    fn accepts_noxid_sources() {
        assert!(ensure_noxid_source(Path::new("Counter.nox")).is_ok());
    }

    #[test]
    fn rejects_non_noxid_sources() {
        let error = ensure_noxid_source(Path::new("Counter.txt")).unwrap_err();
        assert!(error.contains("`.nox`"));
    }

    #[test]
    fn parses_typed_vue_island_fields() {
        let field = parse_vue_island_field("value:Optional<String>").unwrap();
        assert_eq!(field.name, "value");
        assert_eq!(field.ty, "Optional<String>");
        assert!(parse_vue_island_field("value").is_err());
    }

    #[test]
    fn headless_recipe_names_are_closed() {
        assert!(parse_headless_recipe("Dialog").is_ok());
        assert!(parse_headless_recipe("Tabs").is_ok());
        assert!(parse_headless_recipe("UnknownWidget").is_err());
    }

    #[test]
    fn core_agent_guide_exposes_the_closed_scalar_builtin_vocabulary() {
        let guide = agent_guide("core").expect("core guide");
        for builtin in [
            "len",
            "contains",
            "startsWith",
            "trim",
            "lower",
            "upper",
            "min",
            "max",
            "abs",
            "round",
            "floor",
            "ceil",
            "toFloat",
            "toInt",
            "toString",
        ] {
            assert!(guide.contains(builtin), "core guide omitted `{builtin}`");
        }
        assert!(guide.contains("free functions, not methods"));
        assert!(guide.contains("toInt truncates toward zero"));
    }

    #[test]
    fn remote_action_agent_guide_exposes_the_closed_await_contract() {
        let guide = agent_guide("remote-actions").expect("remote action guide");
        for contract in [
            "one top-level sequential remote await",
            "Result<T, RemoteError>",
            "second transaction",
            "given action = Ok",
            "Unstubbed remote awaits fail closed",
        ] {
            assert!(
                guide.contains(contract),
                "remote guide omitted `{contract}`"
            );
        }
    }

    #[test]
    fn agent_guides_describe_the_auto_discovered_server_layout() {
        let routing = agent_guide("routing").expect("routing guide");
        for contract in [
            "server/route-middleware/<name>.ts",
            "server/middleware/",
            "lexical filename order",
            "no registration is required",
            "server/api/",
            "endpoint:<Name>@<version>",
            "server/security.manifest.json",
            "one JSON-array query value",
            "description: \"...\"",
            "api.openapi.json",
            "x-noxid-signature",
            "[server] api_docs = true",
            "[server] mcp = true",
            "/_noxid/openapi.json",
            "/_noxid/mcp",
            "default false and 404",
            "surfaces",
            "api-contract.json",
            "API_CONTRACT_BREAKING_CHANGE",
        ] {
            assert!(
                routing.contains(contract),
                "routing guide omitted `{contract}`"
            );
        }

        // WO-53 split the oversized routing guide into routing/storage/realtime.
        // The persistence and background-work surface now lives in `storage`.
        let storage = agent_guide("storage").expect("storage guide");
        for contract in [
            "noxid:server",
            "storage(namespace)",
            "server/db/migrations/",
            "DATA_SCOPE_VIOLATION",
            "server/queues/<name>.nox",
            "queue:<Name>",
            "noxid queue work",
            "noxid queue status",
            "queue_worker = true",
            "server/plugins/*.{ts,js}",
            "frozen { environment, storage, host }",
            "server/tasks/<name>.nox",
            "exactly five fields and no seconds",
            "task:<Name>",
            "server/tasks.manifest.json",
            "POST /_noxid/tasks/<name>",
            "tasks.run",
            "noxid task run <name>",
        ] {
            assert!(
                storage.contains(contract),
                "storage guide omitted `{contract}`"
            );
        }

        // Merging WO-53 with main's tracing growth pushed `routing` over the
        // 6 KB budget, so the `[server] tracing` surface split off into its own
        // `observability` topic under the same rule that produced `storage`,
        // `realtime`, and `types`.
        let observability = agent_guide("observability").expect("observability guide");
        for contract in [
            "tracing = \"requests\"",
            "noxid.trace.v1",
            "x-noxid-trace",
            "tracing_service_name",
            "secret names or values are never logged",
        ] {
            assert!(
                observability.contains(contract),
                "observability guide omitted `{contract}`"
            );
        }

        // The live/presence/stream surface now lives in `realtime`.
        let realtime = agent_guide("realtime").expect("realtime guide");
        for contract in [
            "stream endpoint Name",
            "AsyncIterable<T>",
            "Last-Event-ID",
            "matching ordinary stream",
            "WebSocket syntax is not available",
            "presence {",
        ] {
            assert!(
                realtime.contains(contract),
                "realtime guide omitted `{contract}`"
            );
        }

        // Moved contracts must not linger in routing.
        for moved in [
            "server/queues/<name>.nox",
            "stream endpoint Name",
            "presence {",
            "DATA_SCOPE_VIOLATION",
            "server/plugins/*.{ts,js}",
            "server/tasks/<name>.nox",
            "noxid.trace.v1",
        ] {
            assert!(
                !routing.contains(moved),
                "routing guide should no longer contain moved contract `{moved}`"
            );
        }

        let ssr = agent_guide("ssr").expect("SSR guide");
        for contract in [
            "auto-detected server/host.ts",
            "[server] entry was removed",
            "server/utils/",
            "SSR documents and action requests",
        ] {
            assert!(ssr.contains(contract), "SSR guide omitted `{contract}`");
        }
        assert!(!routing.contains("src/middleware/server/"));
        assert!(!ssr.contains("src/server.js"));
    }

    #[test]
    fn agent_guide_topics_are_budgeted_and_context_first() {
        // WO-53: every agent-guide topic must fit a model's window (<= 6 KB)
        // and open with the context-first instruction, so a model routes through
        // query_project { operation: "context" } before loading reference prose.
        const MAX_TOPIC_BYTES: usize = 6 * 1024;
        for topic in [
            "core",
            "scaffolding",
            "interop",
            "types",
            "routing",
            "storage",
            "realtime",
            "observability",
            "reactivity",
            "motion",
            "remote-actions",
            "ssr",
            "testing",
            "semantic-tools",
        ] {
            let guide = agent_guide(topic).expect("known guide topic");
            assert!(
                guide.len() <= MAX_TOPIC_BYTES,
                "agent-guide topic `{topic}` is {} bytes, over the {MAX_TOPIC_BYTES}-byte budget",
                guide.len()
            );
            assert!(
                guide.starts_with(super::CONTEXT_PREAMBLE),
                "agent-guide topic `{topic}` did not open with the context-first instruction"
            );
        }
    }

    #[test]
    fn testing_agent_guide_exposes_direct_task_scenarios() {
        let testing = agent_guide("testing").expect("testing guide");
        for contract in [
            "when: run()",
            "given: TaskName = value",
            "scheduler is never mocked",
            "compiler-owned task handlers cannot be replaced",
        ] {
            assert!(
                testing.contains(contract),
                "testing guide omitted `{contract}`"
            );
        }
    }

    #[test]
    fn semantic_tools_agent_guide_exposes_phase_one_devtools_contract() {
        let guide = agent_guide("semantic-tools").expect("semantic tools guide");
        for contract in [
            "classification (automatic|review)",
            "proof: the recompile, the noxid drift result",
            "Everything else is review with a concrete proposed edit",
            "exact route matching",
            "bounded graph/impact traversal",
            "reverse DOM ownership",
            "{id,title,description?}",
            "never invents cross-wire relationships",
            "Production runtimes prune",
            "app.devtools.json remains inert compiler metadata",
        ] {
            assert!(
                guide.contains(contract),
                "semantic tools guide omitted `{contract}`"
            );
        }
    }

    #[test]
    fn agent_guides_expose_the_resource_cache_algebra() {
        let reactivity = agent_guide("reactivity").expect("reactivity guide");
        for contract in [
            "declaration plus ordered typed arguments",
            "refresh on focus",
            "refresh on reconnect",
            "refresh every 5m",
            "prefetch on hover",
            "unused trigger runtime is pruned",
        ] {
            assert!(
                reactivity.contains(contract),
                "reactivity guide omitted `{contract}`"
            );
        }

        let remote = agent_guide("remote-actions").expect("remote guide");
        for contract in [
            "AMBIGUOUS_RESOURCE_INVALIDATION",
            "invalidates [Products]",
            "invalidates none",
            "Failures do not invalidate",
        ] {
            assert!(
                remote.contains(contract),
                "remote guide omitted `{contract}`"
            );
        }

        let testing = agent_guide("testing").expect("testing guide");
        for contract in [
            "Ready([...]) aged 45s",
            "compiler-authorized and non-I/O",
            "unaged givens pass no age",
            "Pagination/infinite resources",
            "automatic optimistic rollback",
            "given presence = [Snapshot(...), Joined(...), Left",
            "exactly one same-principal delivery",
        ] {
            assert!(
                testing.contains(contract),
                "testing guide omitted `{contract}`"
            );
        }

        let ssr = agent_guide("ssr").expect("SSR guide");
        assert!(ssr.contains("renderedAt"));
        assert!(ssr.contains("Transit time counts"));
    }

    #[test]
    fn universal_scaffold_uses_the_auto_discovered_server_host() {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock after Unix epoch")
            .as_nanos();
        let root = std::env::temp_dir().join(format!(
            "noxid-universal-scaffold-{}-{nonce}",
            std::process::id()
        ));

        scaffold_project(&root, "counter", Some("universal")).expect("scaffold universal project");
        let manifest = fs::read_to_string(root.join("Noxid.toml")).expect("read manifest");
        assert!(manifest.contains("[server]\nruntime = \"node\""));
        assert!(!manifest.contains("entry ="));
        assert!(root.join("server/host.js").is_file());
        assert!(!root.join("src/server.js").exists());

        fs::remove_dir_all(&root).expect("remove scaffold fixture");
    }
}