blue-lang-cli 0.0.57

The blue command line: run, fmt, ast, erase, check.
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
//! The CLI's contract, exercised as a subprocess.
//!
//! These run the real binary against real files, because that is the only way
//! to test what a user actually touches: argument parsing, file reading, what
//! lands on stdout versus stderr, and **the exit code**. A library test cannot
//! observe any of those.
//!
//! Exit codes matter most. `blue fmt --check` in CI and `blue check` in a
//! pre-commit hook are both *only* their exit code as far as the caller is
//! concerned — a subcommand that prints an error and exits 0 is a gate that
//! silently passes everything.

use std::path::PathBuf;
use std::process::{Command, Output};

/// The binary under test. Cargo sets `CARGO_BIN_EXE_<name>` for integration
/// tests, which is how this finds the just-built `blue` rather than whatever
/// is on `PATH`.
///
/// Blue's three environment inputs are **cleared**, so a developer who has a
/// distribution on `BLUE_PATH` or a deployed `~/.config/blue/blue.yaml` does
/// not get different results from CI. A test that passes only on an unconfigured
/// machine is the "passes locally" class this repo already paid for once with
/// `lld`.
fn blue() -> Command {
    let mut c = Command::new(env!("CARGO_BIN_EXE_blue"));
    c.env_remove("BLUE_PATH")
        .env_remove("BLUE_CONFIG")
        .env_remove("BLUE_TIER");
    c
}

/// A scratch `.b` file, named per test so parallel tests cannot collide.
fn write(name: &str, src: &str) -> PathBuf {
    let mut p = std::env::temp_dir();
    p.push(format!("blue-cli-test-{name}.b"));
    std::fs::write(&p, src).expect("write fixture");
    p
}

fn run(args: &[&str]) -> Output {
    blue().args(args).output().expect("spawn blue")
}

/// `run`, with environment set for this invocation only.
///
/// Per-process rather than `std::env::set_var`, which would race every other
/// test in this binary — cargo runs them on threads of one process.
fn run_env(args: &[&str], env: &[(&str, &str)]) -> Output {
    let mut c = blue();
    for (k, v) in env {
        c.env(k, v);
    }
    c.args(args).output().expect("spawn blue")
}

/// A scratch file with an arbitrary name/extension, for fixtures that are not
/// `.b` sources (config YAML, `Bluefile`s inside a distribution).
fn write_at(rel: &str, contents: &str) -> PathBuf {
    let mut p = std::env::temp_dir();
    p.push(format!("blue-cli-test-{rel}"));
    if let Some(parent) = p.parent() {
        std::fs::create_dir_all(parent).expect("create fixture dir");
    }
    std::fs::write(&p, contents).expect("write fixture");
    p
}

fn stdout(o: &Output) -> String {
    String::from_utf8_lossy(&o.stdout).to_string()
}

fn stderr(o: &Output) -> String {
    String::from_utf8_lossy(&o.stderr).to_string()
}

const PROGRAM: &str =
    "def fact(n: Int) -> Int\n  if n < 2\n    1\n  else\n    n * fact(n - 1)\n  end\nend\nfact(6)";

// ---------------------------------------------------------------------------
// run
// ---------------------------------------------------------------------------

/// A program's own arguments reach `argv()`, flags included, and nothing of
/// the CLI's own (`run`, the path) comes with them. Before 2026-09-27 `run`
/// refused every trailing argument, so no blue program could take any.
#[test]
fn run_passes_the_programs_arguments_to_argv() {
    let f = write("argv", "join(argv(), \"|\")");
    let o = run(&[
        "run",
        f.to_str().unwrap(),
        "rust",
        "--dry-run",
        "--min-age-hours",
        "6",
        "/x",
    ]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "rust|--dry-run|--min-age-hours|6|/x");
    // No arguments: an empty list, not the CLI's own.
    let o = run(&["run", f.to_str().unwrap()]);
    assert_eq!(stdout(&o).trim(), "");
    // `--` lets a program take an argument the CLI would otherwise read.
    let o = run(&["run", f.to_str().unwrap(), "--", "--input"]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "--input");
}

/// `write_stdout` writes the text exactly: no quotes (println's), no newline
/// added. Before 2026-09-27 a blue command-line tool had no way to print
/// plain text.
#[test]
fn write_stdout_prints_plain_text() {
    let f = write(
        "wstdout",
        "write_stdout(\"a b\\n\")\nwrite_stdout(\"c\")\nwrite_stderr(\"e\")\n0",
    );
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    // The program's own output, then the CLI's printed final value.
    assert_eq!(stdout(&o), "a b\nc0\n");
    assert_eq!(stderr(&o), "e");
}

/// `--quiet` leaves only what the program wrote: no final value. The control
/// is the same program without it, which prints the value. A program that
/// takes `--quiet` itself receives it after `--`, which is why `mkBlueApp`
/// wraps as `run --quiet <file> --`: every argument a user types then belongs
/// to the program, never to the CLI.
#[test]
fn run_quiet_prints_only_what_the_program_writes() {
    let f = write("quiet", "write_stdout(\"out\\n\")\nnil");
    let o = run(&["run", "--quiet", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(stdout(&o), "out\n");
    let o = run(&["run", f.to_str().unwrap()]);
    assert_eq!(stdout(&o), "out\nnil\n");
    let g = write("quiet-argv", "write_stdout(join(argv(), \"|\"))\nnil");
    let o = run(&[
        "run",
        "--quiet",
        g.to_str().unwrap(),
        "--",
        "--quiet",
        "rust",
    ]);
    assert_eq!(stdout(&o), "--quiet|rust");
}

#[test]
fn run_executes_a_program_and_prints_its_value() {
    let f = write("run", PROGRAM);
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "720");
}

/// **A type error must exit non-zero.** A `blue run` that printed the error
/// and exited 0 would pass every CI gate built on it.
#[test]
fn run_rejects_a_type_error_with_a_failing_exit_code() {
    let f = write("run-bad-type", "def bad(a: Int) -> Str\n  a\nend\nbad(1)");
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(!o.status.success(), "a type error must fail the process");
    assert!(
        stderr(&o).contains("Str") && stderr(&o).contains("Int"),
        "the error must name both types: {}",
        stderr(&o)
    );
    assert!(
        stdout(&o).trim().is_empty(),
        "a rejected program must not print a value: {:?}",
        stdout(&o)
    );
}

/// Anti-vacuity for the test above: the same program without annotations
/// runs, so the rejection is the annotation's doing.
#[test]
fn run_accepts_the_same_program_without_annotations() {
    let f = write("run-untyped", "def ok(a)\n  a\nend\nok(1)");
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "1");
}

#[test]
fn a_missing_file_fails_with_the_path_named() {
    let o = run(&["run", "/nonexistent/definitely-not-here.b"]);
    assert!(!o.status.success());
    assert!(
        stderr(&o).contains("definitely-not-here.b"),
        "the error must name the path: {}",
        stderr(&o)
    );
}

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

/// Formatting is idempotent through the CLI, and the second pass is what
/// `--check` relies on being a fixed point.
#[test]
fn fmt_output_is_already_formatted() {
    let f = write("fmt-idem", PROGRAM);
    let once = run(&["fmt", f.to_str().unwrap()]);
    assert!(once.status.success(), "stderr: {}", stderr(&once));

    let g = write("fmt-idem-2", &stdout(&once));
    let check = run(&["fmt", "--check", g.to_str().unwrap()]);
    assert!(
        check.status.success(),
        "formatted output must satisfy --check; got: {}",
        stderr(&check)
    );
}

/// **`--check` must fail on drift**, or it is not a gate.
#[test]
fn fmt_check_fails_on_unformatted_input() {
    let f = write("fmt-drift", "1   +    2");
    let o = run(&["fmt", "--check", f.to_str().unwrap()]);
    assert!(!o.status.success(), "unformatted input must fail --check");
    assert!(
        stderr(&o).contains("not formatted"),
        "and say why: {}",
        stderr(&o)
    );
}

/// `--check` must not modify the file. A gate with a side effect is not a
/// gate.
#[test]
fn fmt_check_does_not_rewrite_the_file() {
    let original = "1   +    2";
    let f = write("fmt-check-pure", original);
    let _ = run(&["fmt", "--check", f.to_str().unwrap()]);
    assert_eq!(
        std::fs::read_to_string(&f).expect("read back"),
        original,
        "--check must leave the file alone"
    );
}

#[test]
fn fmt_write_rewrites_in_place() {
    let f = write("fmt-write", "1   +    2");
    let o = run(&["fmt", "--write", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(
        std::fs::read_to_string(&f).expect("read back").trim(),
        "1 + 2"
    );
}

/// **An ordinary call must survive the CLI as a call.** This is the
/// regression that all three formatting laws missed: `fact(n - 1)` rendered
/// `(n - 1).fact`, which round-tripped perfectly and read backwards.
#[test]
fn fmt_does_not_turn_a_call_into_a_method_send() {
    let f = write("fmt-call", PROGRAM);
    let out = stdout(&run(&["fmt", f.to_str().unwrap()]));
    assert!(
        out.contains("fact(n - 1)"),
        "a recursive call must render as a call: {out}"
    );
    assert!(
        !out.contains(").fact"),
        "and must not render as a method send: {out}"
    );
}

// ---------------------------------------------------------------------------
// ast / erase — the sliding scale, made visible
// ---------------------------------------------------------------------------

/// **The difference between `ast` and `erase` IS the sliding scale.** `ast`
/// keeps the annotation; `erase` shows what actually runs. Two subcommands
/// exist so a reader can see that annotations are *consumed*, not carried.
#[test]
fn ast_keeps_annotations_and_erase_drops_them() {
    let f = write("ast-erase", PROGRAM);
    let ast = stdout(&run(&["ast", f.to_str().unwrap()]));
    let erased = stdout(&run(&["erase", f.to_str().unwrap()]));

    assert!(
        ast.contains("define-typed") && ast.contains("Int"),
        "ast must keep the annotation: {ast}"
    );
    assert!(
        !erased.contains("define-typed") && !erased.contains("Int"),
        "erase must drop every trace of it: {erased}"
    );
    assert!(
        erased.contains("(define (fact n)"),
        "and leave a plain define: {erased}"
    );
}

/// Erasing an untyped program is the identity, so `erase` is not rewriting
/// code that had no annotations to begin with.
#[test]
fn erase_is_the_identity_on_untyped_source() {
    let f = write("erase-untyped", "def f(x)\n  x + 1\nend");
    assert_eq!(
        stdout(&run(&["erase", f.to_str().unwrap()])).trim(),
        stdout(&run(&["ast", f.to_str().unwrap()])).trim()
    );
}

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

/// **"No annotations, no analysis" is reported, not claimed.** The whole
/// sliding-scale promise is that an untyped program pays nothing, and the CLI
/// prints the number so it can be checked rather than believed.
#[test]
fn check_reports_zero_analysis_for_an_untyped_program() {
    let f = write("check-untyped", "def f(x)\n  x + 1\nend\nf(1)");
    let o = run(&["check", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    let out = stdout(&o);
    assert!(
        out.contains("typed declarations: 0"),
        "expected no typed decls: {out}"
    );
    assert!(
        out.contains("nodes analysed:     0"),
        "an untyped program must cost zero analysis: {out}"
    );
}

/// And an annotated program reports non-zero, so the number above is a
/// measurement and not a constant.
#[test]
fn check_reports_analysis_for_an_annotated_program() {
    let f = write("check-typed", PROGRAM);
    let out = stdout(&run(&["check", f.to_str().unwrap()]));
    assert!(
        out.contains("typed declarations: 1"),
        "expected one typed decl: {out}"
    );
    assert!(
        !out.contains("nodes analysed:     0"),
        "an annotation must buy real analysis: {out}"
    );
}

#[test]
fn check_exits_non_zero_on_a_type_error() {
    let f = write("check-bad", "def bad(a: Int) -> Str\n  a\nend");
    let o = run(&["check", f.to_str().unwrap()]);
    assert!(!o.status.success(), "check must fail on a type error");
}

// ---------------------------------------------------------------------------
// the surface itself
// ---------------------------------------------------------------------------

/// Every subcommand is reachable and documented. A subcommand that exists in
/// code but not in `--help` is one nobody can find.
#[test]
fn help_lists_every_subcommand() {
    let o = run(&["--help"]);
    assert!(o.status.success());
    let help = stdout(&o);
    for cmd in [
        "run", "fmt", "ast", "erase", "check", "test", "deps", "posture", "lsp", "banner", "shift",
        "morph", "bluefile", "lock",
    ] {
        assert!(help.contains(cmd), "--help must list `{cmd}`: {help}");
    }
}

#[test]
fn no_arguments_is_an_error_not_a_silent_success() {
    let o = blue().output().expect("spawn");
    assert!(!o.status.success(), "bare `blue` must not exit 0");
}

// ---------------------------------------------------------------------------
// test
// ---------------------------------------------------------------------------

const SUITE: &str = "def add(a, b)\n  a + b\nend\n\ntest \"adds\"\n  assert add(1, 2) == 3\nend";

#[test]
fn test_runs_a_passing_suite_and_exits_zero() {
    let f = write("test-pass", SUITE);
    let o = run(&["test", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert!(
        stdout(&o).contains("1 passed, 0 failed"),
        "expected a tally: {}",
        stdout(&o)
    );
}

/// **A failing suite must exit non-zero.** `blue test` in CI is only its exit
/// code; a runner that prints failures and exits 0 is a gate that passes
/// everything.
#[test]
fn test_exits_non_zero_when_a_test_fails() {
    let f = write("test-fail", "test \"wrong\"\n  assert 1 + 1 == 3\nend");
    let o = run(&["test", f.to_str().unwrap()]);
    assert!(!o.status.success(), "a failing suite must fail the process");
    assert!(
        stdout(&o).contains("0 passed, 1 failed"),
        "tally: {}",
        stdout(&o)
    );
}

/// **The failure names the expression, in blue syntax.** The whole point of
/// `assert` being a surface form rather than a library call.
#[test]
fn test_failure_reports_the_expression_as_written() {
    let f = write(
        "test-msg",
        "def add(a, b)\n  a + b\nend\n\ntest \"wrong\"\n  assert add(1, 2) == 4\nend",
    );
    let o = run(&["test", f.to_str().unwrap()]);
    assert!(
        stderr(&o).contains("assert add(1, 2) == 4"),
        "the message must be the expression in canonical blue source: {}",
        stderr(&o)
    );
}

/// A file with no tests is not a pass — the tally says zero AND the exit status
/// fails, so a mis-typed filename or an un-run suite cannot read as success in
/// a gate that only reads the status (every `lib.project` check does).
#[test]
fn test_on_a_file_with_no_tests_reports_zero_and_fails() {
    let f = write("test-none", "def f(x)\n  x\nend");
    let o = run(&["test", f.to_str().unwrap()]);
    assert!(
        stdout(&o).contains("0 test(s)"),
        "an empty run must be visibly empty: {}",
        stdout(&o)
    );
    assert!(
        !o.status.success(),
        "a file with no tests must fail, or a gate over it is vacuous: {}",
        stderr(&o)
    );
}

// ---------------------------------------------------------------------------
// deps / posture — the Bluefile
// ---------------------------------------------------------------------------

/// A Bluefile whose version is COMPUTED. A data-format manifest could not
/// express this, and it is the reason the Bluefile is a blue program.
const BLUEFILE: &str = "def app_version()\n  \"0.2.0\"\nend\n\npackage(\"myapp\", app_version())\nneeds(\"gaming\", \"^1.2\")\nposture(:preceding)";

#[test]
fn deps_reports_the_manifest_including_a_computed_version() {
    let f = write("deps", BLUEFILE);
    let o = run(&["deps", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    let out = stdout(&o);
    assert!(
        out.contains("myapp 0.2.0"),
        "the version came from a function call: {out}"
    );
    assert!(out.contains("needs gaming ^1.2.0"), "{out}");
}

/// **`deps` must not claim to have resolved anything** when there is nothing
/// to resolve against. Printing an empty resolution would read as success.
///
/// The message changed 2026-08-01 (from "requires a registry") because the
/// claim behind it stopped being true: `GitRegistry` reads a distribution
/// already on disk, so a `BLUE_PATH` that names one IS something to resolve
/// against. What is honest now is the narrower statement — no distribution on
/// the load path.
#[test]
fn deps_says_it_cannot_resolve_rather_than_printing_a_hollow_resolution() {
    let f = write("deps-honest", BLUEFILE);
    let out = stdout(&run(&["deps", f.to_str().unwrap()]));
    assert!(
        out.contains("nothing to resolve against"),
        "it must say resolution has no distribution: {out}"
    );
    assert!(
        !out.contains("resolved against"),
        "it must not claim a resolution it did not perform: {out}"
    );
}

// ---------------------------------------------------------------------------
// config — the two bounds, and proof that they are READ
// ---------------------------------------------------------------------------

/// A one-package distribution `blue deps` can actually resolve against.
fn distribution(name: &str) -> PathBuf {
    let manifest = write_at(
        &format!("dist-{name}/gaming/Bluefile"),
        "package(\"gaming\", \"1.2.0\")",
    );
    manifest
        .parent()
        .and_then(std::path::Path::parent)
        .expect("<root>/gaming/Bluefile")
        .to_path_buf()
}

#[test]
fn config_show_prints_the_prescribed_bounds() {
    let out = stdout(&run(&["config", "default"]));
    assert!(out.contains("solver_max_steps: 100000"), "{out}");
    assert!(out.contains("max_expr_depth: 256"), "{out}");
}

#[test]
fn config_show_bare_is_the_zero_opinion_floor() {
    let out = stdout(&run(&["config", "bare"]));
    assert!(out.contains("solver_max_steps: 0"), "{out}");
    assert!(out.contains("max_expr_depth: 0"), "{out}");
}

/// `deps` resolves against a distribution on `BLUE_PATH`.
///
/// The precondition for the next test: without a real resolution happening,
/// `solver_max_steps` could not be observed being read.
#[test]
fn deps_resolves_against_a_distribution_on_the_load_path() {
    let f = write("deps-resolve", BLUEFILE);
    let root = distribution("resolve");
    let out = stdout(&run_env(
        &["deps", f.to_str().unwrap()],
        &[("BLUE_PATH", root.to_str().unwrap())],
    ));
    assert!(out.contains("resolved against 1 package(s)"), "{out}");
    assert!(out.contains("gaming 1.2.0"), "{out}");
}

/// **`solver_max_steps` is read from the deployed YAML, end to end.**
///
/// This is the test that makes the config non-decorative. It exercises the
/// entire chain a fleet operator gets — a YAML file, `BLUE_CONFIG` pointing at
/// it (the env var substrate's module trio sets), shikumi's tier resolution,
/// then `Solver::with_max_steps` — by setting a bound so small that a
/// resolution which SUCCEEDS at the default must now fail.
///
/// The budget is 0, not 1: this graph resolves in exactly one step, and a
/// budget of 1 admits it (`steps > max_steps` fires after the increment).
/// Measured, not reasoned about — the first version of this test used 1 and
/// went green against a working wire, which is the vacuous-gate trap this
/// repo's testing discipline names.
///
/// Red run: with the `.with_max_steps(cfg.solver_max_steps)` call removed from
/// `main.rs`, the solver used its own 100_000 default and the run succeeded —
/// `resolved against 1 package(s)` — failing the assertion below. Restored.
#[test]
fn solver_max_steps_is_read_from_the_deployed_yaml() {
    let f = write("deps-bounded", BLUEFILE);
    let root = distribution("bounded");
    // `max_expr_depth` stays at the shipped default so a failure here can only
    // be the solver bound — if the tier had resolved to `bare()` instead of the
    // file, a depth of 0 would have failed the Bluefile PARSE, with a different
    // message, and this test would not be measuring what it claims.
    let cfg = write_at(
        "cfg-solver.yaml",
        "solver_max_steps: 0\nmax_expr_depth: 256\n",
    );

    let o = run_env(
        &["deps", f.to_str().unwrap()],
        &[
            ("BLUE_PATH", root.to_str().unwrap()),
            ("BLUE_CONFIG", cfg.to_str().unwrap()),
        ],
    );
    assert!(
        !o.status.success(),
        "a 0-step budget must not resolve anything; stdout: {} stderr: {}",
        stdout(&o),
        stderr(&o)
    );
    assert!(
        stderr(&o).contains("gave up after"),
        "the failure must name the exhausted budget: {}",
        stderr(&o)
    );
}

/// **`max_expr_depth` is read from the deployed YAML, end to end.**
///
/// Same chain, the other knob: a depth blue accepts by default must be refused
/// once the deployed config lowers the bound, and the error must name the bound
/// that was actually applied rather than the compiled-in constant.
///
/// Red run: reverting `Cmd::Ast` to `blue_lang_runtime::parse` turned this red
/// with `left: true, right: false` on the exit status — the file parsed fine
/// under the 256 default, exactly as a decoration knob would.
#[test]
fn max_expr_depth_is_read_from_the_deployed_yaml() {
    // Depth 12 — far below the 256 default, far above the configured 4.
    let src = format!("{}1{}", "(".repeat(12), ")".repeat(12));
    let f = write("ast-bounded", &src);
    let cfg = write_at(
        "cfg-depth.yaml",
        "solver_max_steps: 100000\nmax_expr_depth: 4\n",
    );

    assert!(
        run(&["ast", f.to_str().unwrap()]).status.success(),
        "precondition: the DEFAULT bound accepts this file"
    );

    let o = run_env(
        &["ast", f.to_str().unwrap()],
        &[("BLUE_CONFIG", cfg.to_str().unwrap())],
    );
    assert!(
        !o.status.success(),
        "a configured bound of 4 must refuse depth 12: {}",
        stdout(&o)
    );
    assert!(
        stderr(&o).contains("nests deeper than 4"),
        "the error must name the CONFIGURED bound, not the constant: {}",
        stderr(&o)
    );
}

/// `BLUE_TIER` is the explicit override, so it beats a `BLUE_CONFIG` file.
///
/// Without this ordering an operator could not get back to a known state
/// without deleting their config, which is the thing a tier selector exists to
/// avoid.
#[test]
fn an_explicit_tier_beats_the_config_file() {
    let src = format!("{}1{}", "(".repeat(12), ")".repeat(12));
    let f = write("ast-tier", &src);
    let cfg = write_at(
        "cfg-tier.yaml",
        "solver_max_steps: 100000\nmax_expr_depth: 4\n",
    );

    let o = run_env(
        &["ast", f.to_str().unwrap()],
        &[
            ("BLUE_CONFIG", cfg.to_str().unwrap()),
            ("BLUE_TIER", "default"),
        ],
    );
    assert!(
        o.status.success(),
        "BLUE_TIER=default must ignore the file's lower bound: {}",
        stderr(&o)
    );
}

#[test]
fn posture_reports_the_declared_floor() {
    let f = write("posture", BLUEFILE);
    let o = run(&["posture", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    let out = stdout(&o);
    assert!(out.contains("Preceding"), "the declared `when`: {out}");
    assert!(
        out.contains("unrestricted"),
        "undeclared reach is the top: {out}"
    );
}

/// A Bluefile with no `package` call fails, rather than defaulting to an
/// anonymous package at 0.0.0.
#[test]
fn a_bluefile_without_a_package_call_fails() {
    let f = write("bluefile-nopkg", "needs(\"a\", \"*\")");
    let o = run(&["deps", f.to_str().unwrap()]);
    assert!(!o.status.success(), "must fail");
    assert!(
        stderr(&o).contains("package"),
        "and say what is missing: {}",
        stderr(&o)
    );
}

/// **`fmt --write` must not delete comments.**
///
/// It used to delete every one: comments are lexed as trivia and were never
/// attached to a node, so formatting dropped them silently. A comment is the one
/// part of a program a machine cannot reconstruct, so that was data loss on a
/// routine operation. The formatter now re-interleaves them by position.
#[test]
fn fmt_write_preserves_comments() {
    let f = write("fmt-comments", "# keep me\n1   +   2\n");
    let o = run(&["fmt", "--write", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    let after = std::fs::read_to_string(&f).expect("read back");
    assert!(
        after.contains("# keep me"),
        "the comment must survive: {after:?}"
    );
    assert!(
        after.contains("1 + 2"),
        "and the code must be formatted: {after:?}"
    );
}

/// And `--check` settles on a commented file. Comparing against the
/// comment-stripped rendering made every commented file report "not formatted"
/// forever — a gate that can never be satisfied.
#[test]
fn fmt_check_settles_on_a_commented_file() {
    let f = write("fmt-check-comments", "# note\n1 + 2\n");
    let o = run(&["fmt", "--check", f.to_str().unwrap()]);
    assert!(
        o.status.success(),
        "an already-canonical commented file must pass --check: {}",
        stderr(&o)
    );
}

/// A comment with no line of its own once the code is re-laid out — here,
/// between a binding's `=` and its value — is still refused, and the file is
/// left as it was. (A comment inside a body used to be refused too; since
/// 2026-09-27 it is placed, and `fmt_write_places_a_comment_inside_a_body`
/// holds that.)
#[test]
fn fmt_write_refuses_a_comment_it_cannot_place() {
    let original = "x = # no line for this\n  5\n";
    let f = write("fmt-inner-comment", original);
    let o = run(&["fmt", "--write", f.to_str().unwrap()]);
    assert!(!o.status.success(), "it must refuse");
    assert!(
        stderr(&o).contains("comment"),
        "and say why: {}",
        stderr(&o)
    );
    assert_eq!(
        std::fs::read_to_string(&f).expect("read back"),
        original,
        "the file must be untouched"
    );
}

/// A comment inside a `def` body is written back where it sat.
#[test]
fn fmt_write_places_a_comment_inside_a_body() {
    let messy = "def f(x)\n    # inside\n    x   +   1\nend\n";
    let f = write("fmt-body-comment", messy);
    let o = run(&["fmt", "--write", f.to_str().unwrap()]);
    assert!(o.status.success(), "{}", stderr(&o));
    assert_eq!(
        std::fs::read_to_string(&f).expect("read back"),
        "def f(x)\n  # inside\n  x + 1\nend\n"
    );
}

/// And `--write` still works on a file with no comments, so the refusal is
/// narrow rather than a blanket failure.
#[test]
fn fmt_write_still_works_without_comments() {
    let f = write("fmt-nocomments", "1   +   2");
    let o = run(&["fmt", "--write", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(
        std::fs::read_to_string(&f).expect("read back").trim(),
        "1 + 2"
    );
}

// ---------------------------------------------------------------------------
// build inputs — capability-restricted, content-addressed macro I/O
// ---------------------------------------------------------------------------

fn write_bytes(name: &str, bytes: &[u8]) -> PathBuf {
    let mut p = std::env::temp_dir();
    p.push(format!("blue-cli-input-{name}"));
    std::fs::write(&p, bytes).expect("write input");
    p
}

const SCHEMA: &[u8] = b"id,name,email\n";
/// BLAKE3 of SCHEMA. Written out rather than computed so the test pins the
/// *value*: if hashing ever changed, a computed expectation would follow it
/// silently.
const SCHEMA_HASH: &str = "b3:1e8c349d3151d7c4c19836c6ba0e0d82270a2c174d98af445e102055040ac92c";

fn schema_program() -> String {
    let mut s = String::from("definput(\"schema\", \"");
    s.push_str(SCHEMA_HASH);
    s.push_str("\")\n");
    s.push_str(
        "defmacro column_count()\n  quote\n    length(split(trim(input(\"schema\")), \",\"))\n  end\nend\n\
         column_count()",
    );
    s
}

/// **A macro generates code from a schema, read at expansion time.** The
/// Tier-2 conversion `theory/BLUE.md` §VI OPEN #6 named as gating blue's
/// "stronger than Ruby's metaprogramming" claim.
#[test]
fn a_macro_reads_a_content_addressed_input() {
    let f = write("input-ok", &schema_program());
    let schema = write_bytes("schema-ok", SCHEMA);
    let o = run(&[
        "run",
        f.to_str().unwrap(),
        "--input",
        &format!("schema={}", schema.display()),
    ]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "3", "three columns in the schema");
}

/// **Bytes that do not match the declared hash are refused**, and the error
/// names both so the author can tell "I edited the file" from "I pasted the
/// wrong hash".
#[test]
fn input_bytes_must_match_the_declared_hash() {
    let f = write("input-tampered", &schema_program());
    let schema = write_bytes("schema-tampered", b"id,name,email,extra\n");
    let o = run(&[
        "run",
        f.to_str().unwrap(),
        "--input",
        &format!("schema={}", schema.display()),
    ]);
    assert!(!o.status.success(), "a hash mismatch must fail the run");
    let err = stderr(&o);
    assert!(err.contains(SCHEMA_HASH), "must name the expected: {err}");
    assert!(err.contains("hash to"), "and the actual: {err}");
}

/// **A declared input with no `--input` names the FLAG**, not the macro. The
/// first version short-circuited when the flag list was empty, so this reported
/// the macro-level "no input named …" from deep inside expansion — pointing at
/// the wrong thing entirely.
#[test]
fn a_declared_input_with_no_flag_names_the_missing_flag() {
    let f = write("input-missing", &schema_program());
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(!o.status.success());
    let err = stderr(&o);
    assert!(err.contains("--input schema="), "must name the flag: {err}");
}

/// Supplying a name the program never declared is a DIFFERENT mistake, and
/// reads differently.
#[test]
fn an_undeclared_input_name_is_its_own_error() {
    let f = write("input-undeclared", &schema_program());
    let schema = write_bytes("schema-undeclared", SCHEMA);
    let o = run(&[
        "run",
        f.to_str().unwrap(),
        "--input",
        &format!("nosuch={}", schema.display()),
    ]);
    assert!(!o.status.success());
    assert!(
        stderr(&o).contains("never declares it"),
        "got: {}",
        stderr(&o)
    );
}

/// A program with no declarations is unaffected — the check is narrow.
#[test]
fn a_program_without_declarations_still_runs() {
    let f = write("input-none", PROGRAM);
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(o.status.success(), "stderr: {}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "720");
}

// ---------------------------------------------------------------------------
// bluefile / lock — `theory/BLUE-STRUCTURE.md` P1 + P1b
//
// Every word reads back through `blue bluefile --json`, the surface nix is
// fed from. P1b's gate: remove a word from the frame and its test here goes
// red — recorded on `a_misspelled_word_is_an_escape_naming_it` in
// `blue_lang_pkg::bluefile`.
// ---------------------------------------------------------------------------

/// `blue bluefile --json` over a Bluefile whose body follows a fixed
/// `package(...)` line, parsed.
fn manifest_json(name: &str, body: &str) -> serde_json::Value {
    let f = write_at(
        &format!("json-{name}/Bluefile"),
        &(String::from("package(\"proj\", \"0.3.0\")\n") + body),
    );
    let o = run(&["bluefile", "--json", f.to_str().unwrap()]);
    assert!(o.status.success(), "{body}: {}", stderr(&o));
    serde_json::from_slice(&o.stdout).expect("--json prints JSON")
}

#[test]
fn bluefile_json_reads_back_identity_needs_and_posture() {
    let v = manifest_json("identity", "needs(\"kazu\", \"^0.1\")\nposture(:preceding)");
    assert_eq!(v["schema"], 1);
    assert_eq!(v["name"], "proj");
    assert_eq!(v["version"], "0.3.0");
    assert_eq!(v["needs"], serde_json::json!({ "kazu": "^0.1.0" }));
    assert_eq!(v["when"], "preceding");
}

#[test]
fn bluefile_json_reads_back_source() {
    let v = manifest_json(
        "source",
        "source(\"blue\", \"github:pleme-io/blue\", \"bidamas\")",
    );
    assert_eq!(
        v["sources"],
        serde_json::json!({ "blue": { "url": "github:pleme-io/blue", "dir": "bidamas" } })
    );
}

#[test]
fn bluefile_json_reads_back_packages() {
    let v = manifest_json("packages", "packages(\"bidamas\")");
    assert_eq!(v["packages"], serde_json::json!(["bidamas"]));
}

#[test]
fn bluefile_json_reads_back_run() {
    let v = manifest_json(
        "run",
        "run(\"games\", \"src/games.b\")\nrun(\"report\", \"src/report.b\", [\"games\"])",
    );
    assert_eq!(
        v["runs"],
        serde_json::json!({
            "games": { "file": "src/games.b", "reads": [] },
            "report": { "file": "src/report.b", "reads": ["games"] }
        })
    );
}

#[test]
fn bluefile_json_reads_back_tool() {
    let v = manifest_json("tool", "tool(\"duckdb\")");
    assert_eq!(v["tools"], serde_json::json!(["duckdb"]));
}

#[test]
fn bluefile_json_reads_back_check() {
    let v = manifest_json("check", "check(\"unit\", \"tests/unit.b\")");
    assert_eq!(
        v["checks"],
        serde_json::json!({ "unit": { "file": "tests/unit.b" } })
    );
}

#[test]
fn bluefile_json_reads_back_app() {
    let v = manifest_json("app", "app(\"report\", \"bin/report.b\")");
    assert_eq!(
        v["apps"],
        serde_json::json!({ "report": { "file": "bin/report.b" } })
    );
}

#[test]
fn bluefile_json_reads_back_catalog() {
    let v = manifest_json(
        "catalog",
        "packages(\"bidamas\")\ncatalog(\"bidamas/CATALOG.md\")",
    );
    assert_eq!(v["catalog"], "bidamas/CATALOG.md");
}

#[test]
fn bluefile_json_reads_back_generate() {
    let v = manifest_json(
        "generate",
        "generate(\"tables\", \"src/tables.rs\", \"gen/tables.b\")",
    );
    assert_eq!(
        v["generated"],
        serde_json::json!({ "tables": { "output": "src/tables.rs", "program": "gen/tables.b" } })
    );
}

/// A misspelled word never reaches JSON: the manifest is refused and the
/// refusal names it.
#[test]
fn bluefile_json_refuses_a_misspelled_word_naming_it() {
    let f = write_at(
        "json-typo/Bluefile",
        "package(\"p\", \"0.1.0\")\ntoool(\"jq\")",
    );
    let o = run(&["bluefile", "--json", f.to_str().unwrap()]);
    assert!(!o.status.success(), "a misspelled word must not exit 0");
    assert!(stderr(&o).contains("toool"), "{}", stderr(&o));
    assert!(
        o.stdout.is_empty(),
        "nothing may be printed for a refused manifest"
    );
}

/// A malformed call is refused with the word named — the silent drop that
/// `package` and `needs` used to perform on a non-string.
#[test]
fn bluefile_json_refuses_a_malformed_call() {
    let f = write_at(
        "json-malformed/Bluefile",
        "package(\"p\", \"0.1.0\")\nneeds(\"a\", 1)",
    );
    let o = run(&["bluefile", "--json", f.to_str().unwrap()]);
    assert!(!o.status.success());
    assert!(
        stderr(&o).contains("`needs`: `range` must be a string"),
        "{}",
        stderr(&o)
    );
}

#[test]
fn bluefile_needs_exactly_one_mode_and_json_one_file() {
    let f = write_at("json-mode/Bluefile", "package(\"p\", \"0.1.0\")");
    let path = f.to_str().unwrap();
    assert!(!run(&["bluefile", path]).status.success(), "no mode");
    assert!(
        !run(&["bluefile", "--json", "--confirm", path])
            .status
            .success(),
        "both modes"
    );
    let o = run(&["bluefile", "--json", path, path]);
    assert!(!o.status.success(), "two files for --json");
    assert!(stderr(&o).contains("one manifest"), "{}", stderr(&o));
}

/// A package directory for the lock tests, holding only a Bluefile.
fn lockable(name: &str, src: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("blue-cli-test-lock-{name}"));
    let _ = std::fs::remove_file(dir.join("Bluefile.lock"));
    std::fs::create_dir_all(&dir).expect("create package dir");
    std::fs::write(dir.join("Bluefile"), src).expect("write Bluefile");
    dir
}

fn confirm(dir: &std::path::Path) -> Output {
    run(&[
        "bluefile",
        "--confirm",
        dir.join("Bluefile").to_str().unwrap(),
    ])
}

const LOCKABLE: &str = "package(\"lockme\", \"1.0.0\")\nneeds(\"kazu\", \"^0.1\")\n";

/// `blue lock` writes what `--confirm` accepts, and what it writes is the
/// `--json` manifest plus the hash. No `source`, so nix is never started.
#[test]
fn lock_writes_a_lock_that_confirm_accepts() {
    let dir = lockable("fresh", LOCKABLE);
    let o = run(&["lock", dir.to_str().unwrap()]);
    assert!(o.status.success(), "{}", stderr(&o));

    let lock: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(dir.join("Bluefile.lock")).expect("the lock was written"),
    )
    .expect("the lock is JSON");
    assert_eq!(lock["schema"], 1);
    assert_eq!(lock["sources"], serde_json::json!({}));
    assert!(lock["bluefile_b3"].as_str().unwrap().starts_with("b3:"));
    let json = run(&["bluefile", "--json", dir.join("Bluefile").to_str().unwrap()]);
    let manifest: serde_json::Value = serde_json::from_slice(&json.stdout).expect("json");
    assert_eq!(
        lock["manifest"], manifest,
        "the lock's manifest IS --json's"
    );

    let c = confirm(&dir);
    assert!(c.status.success(), "{}", stderr(&c));
    assert!(
        stdout(&c).contains("\"status\":\"fresh\""),
        "{}",
        stdout(&c)
    );
}

/// **P1's second red run, at the CLI.** Zero the recorded hash by hand and
/// `--confirm` exits non-zero, naming why.
#[test]
fn confirm_fails_on_a_zeroed_hash() {
    let dir = lockable("zeroed", LOCKABLE);
    assert!(run(&["lock", dir.to_str().unwrap()]).status.success());
    let path = dir.join("Bluefile.lock");
    let mut lock: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    lock["bluefile_b3"] = serde_json::Value::from(String::from("b3:") + &"0".repeat(64));
    std::fs::write(&path, lock.to_string()).unwrap();

    let c = confirm(&dir);
    assert!(!c.status.success(), "a zeroed hash must not confirm");
    let line: serde_json::Value = serde_json::from_slice(&c.stdout).expect("json line");
    assert_eq!(line["status"], "stale");
    assert_eq!(line["reason"]["kind"], "hash");
    assert!(stderr(&c).contains("blue lock"), "{}", stderr(&c));
}

/// Edit the Bluefile without relocking: stale. Relock: fresh.
#[test]
fn confirm_fails_until_an_edited_bluefile_is_relocked() {
    let dir = lockable("edited", LOCKABLE);
    assert!(run(&["lock", dir.to_str().unwrap()]).status.success());
    std::fs::write(
        dir.join("Bluefile"),
        String::from(LOCKABLE) + "tool(\"jq\")\n",
    )
    .unwrap();
    assert!(
        !confirm(&dir).status.success(),
        "an edited Bluefile is stale"
    );
    assert!(run(&["lock", dir.to_str().unwrap()]).status.success());
    assert!(confirm(&dir).status.success(), "relocked is fresh");
}

#[test]
fn confirm_fails_when_there_is_no_lock() {
    let dir = lockable("missing", LOCKABLE);
    let c = confirm(&dir);
    assert!(!c.status.success());
    assert!(
        stdout(&c).contains("\"kind\":\"missing\""),
        "{}",
        stdout(&c)
    );
}

/// **Every committed bidama lock is fresh** — the same check the
/// `bidama-locks-fresh` flake check runs, from `cargo test`, over the real
/// distribution. Anti-vacuity: one `fresh` line per package, at least 21.
#[test]
fn every_bidama_lock_is_confirmed_fresh() {
    let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../bidamas");
    let mut manifests: Vec<String> = std::fs::read_dir(&root)
        .expect("bidamas/")
        .filter_map(Result::ok)
        .map(|e| e.path().join("Bluefile"))
        .filter(|p| p.is_file())
        .map(|p| p.to_string_lossy().into_owned())
        .collect();
    manifests.sort();
    let mut args = vec!["bluefile", "--confirm"];
    args.extend(manifests.iter().map(String::as_str));
    let o = run(&args);
    assert!(o.status.success(), "stale bidama locks:\n{}", stderr(&o));
    let fresh = stdout(&o).matches("\"status\":\"fresh\"").count();
    assert_eq!(fresh, manifests.len());
    assert!(fresh >= 21, "only {fresh} bidama locks were confirmed");
}

// ---------------------------------------------------------------------------
// blue compiles only canonical source (2026-09-27)
//
// "I want bluelang to not compile anything not formatted correctly", kept
// transparent: a file blue can write is formatted in place and compiled; one it
// cannot is refused. `blue_lang_pkg::canonical` holds the rule.
// ---------------------------------------------------------------------------

fn fresh(name: &str, src: &str) -> PathBuf {
    let mut p = std::env::temp_dir();
    p.push(format!("blue-cli-test-{name}.b"));
    // A previous run may have left it read-only; a directory entry can still
    // be removed.
    let _ = std::fs::remove_file(&p);
    std::fs::write(&p, src).expect("write fixture");
    p
}

#[test]
fn run_formats_a_messy_writable_file_in_place_and_runs_it() {
    let f = fresh("canon-run-messy", "x   =   1+2\nx   *   2\n");
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(o.status.success(), "{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "6");
    assert!(
        stderr(&o).contains(&format!("blue: formatted {}", f.display())),
        "one line saying so: {}",
        stderr(&o)
    );
    assert_eq!(
        std::fs::read_to_string(&f).expect("read back"),
        "x = 1 + 2\nx * 2\n"
    );
    // And a canonical file is compiled without a word.
    let again = run(&["run", f.to_str().unwrap()]);
    assert!(!stderr(&again).contains("formatted"), "{}", stderr(&again));
}

#[test]
fn test_formats_the_file_under_test() {
    let f = fresh(
        "canon-test-messy",
        "test   \"adds\"\n  assert 1+1 == 2\nend\n",
    );
    let o = run(&["test", f.to_str().unwrap()]);
    assert!(o.status.success(), "{}", stderr(&o));
    assert_eq!(
        std::fs::read_to_string(&f).expect("read back"),
        "test \"adds\"\n  assert 1 + 1 == 2\nend\n"
    );
}

#[test]
fn run_refuses_a_read_only_messy_file_and_leaves_it_alone() {
    let messy = "x   =   1+2\nx\n";
    let f = fresh("canon-run-readonly", messy);
    let mut perm = std::fs::metadata(&f).expect("meta").permissions();
    perm.set_readonly(true);
    std::fs::set_permissions(&f, perm).expect("chmod");
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(
        !o.status.success(),
        "a read-only messy file must not compile"
    );
    assert!(
        stderr(&o).contains(&format!(
            "{} is not formatted; run blue fmt --write {}",
            f.display(),
            f.display()
        )),
        "{}",
        stderr(&o)
    );
    assert!(stdout(&o).is_empty(), "nothing ran: {}", stdout(&o));
    assert_eq!(std::fs::read_to_string(&f).expect("read back"), messy);
}

#[test]
fn a_messy_writable_package_loaded_by_use_is_formatted() {
    let root = std::env::temp_dir().join("blue-cli-test-canon-dist");
    let pkg = root.join("canonpkg");
    std::fs::create_dir_all(&pkg).expect("mkdir");
    let file = pkg.join("canonpkg.b");
    std::fs::write(&file, "def twice(x)\n        x*2\nend\n").expect("write pkg");
    let entry = fresh(
        "canon-pkg-entry",
        "use(\"canonpkg\", [:twice])\ntwice(21)\n",
    );
    let o = run_env(
        &["run", entry.to_str().unwrap()],
        &[("BLUE_PATH", root.to_str().unwrap())],
    );
    assert!(o.status.success(), "{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "42");
    assert!(
        stderr(&o).contains(&format!("blue: formatted {}", file.display())),
        "{}",
        stderr(&o)
    );
    assert_eq!(
        std::fs::read_to_string(&file).expect("read back"),
        "def twice(x)\n  x * 2\nend\n"
    );
}

#[test]
fn a_file_the_formatter_refuses_is_a_compile_error_naming_the_line() {
    let src = "y = 1\nx = # a comment with no line of its own\n  5\nx\n";
    let f = fresh("canon-unplaceable", src);
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(!o.status.success(), "it must not compile");
    assert!(stderr(&o).contains("cannot be formatted"), "{}", stderr(&o));
    assert!(stderr(&o).contains("line(s) 2"), "{}", stderr(&o));
    assert!(stdout(&o).is_empty(), "nothing ran: {}", stdout(&o));
    assert_eq!(std::fs::read_to_string(&f).expect("read back"), src);
}

// ---------------------------------------------------------------------------
// Execution bounds: `max_call_depth` and `max_steps`.
//
// Measured at blue 0.0.49 (theory/BLUE-GAPS.md G6): a non-tail recursion 6,000
// deep aborted the process — `fatal runtime error: stack overflow`, rc 134 —
// and `try` could not catch it; a loop with no exit ran until killed.

const DEEP: &str = "def f(n)\n  if n == 0\n    0\n  else\n    1 + f(n - 1)\n  end\nend\n";

/// Ten times the depth that used to abort, on the shipped bounds.
#[test]
fn a_deep_recursion_completes_on_the_default_bounds() {
    let f = write("deep-default", &format!("{DEEP}f(60000)"));
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(o.status.success(), "{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), "60000");
}

/// **`max_call_depth` is read from the deployed YAML, end to end**, and the
/// refusal names the configured bound and the function.
///
/// Red run: with the `set_execution_bounds` call removed from `dispatch`, the
/// run used the 100k default and printed `500` with exit 0, failing the status
/// assertion. Restored.
#[test]
fn max_call_depth_is_read_from_the_deployed_yaml() {
    let f = write("deep-bounded", &format!("{DEEP}f(500)"));
    assert!(
        run(&["run", f.to_str().unwrap()]).status.success(),
        "precondition: the DEFAULT bound runs this program"
    );
    // Only the key under test: the other bounds come from the prescribed tier
    // the file is overlaid on, so a YAML deployed before a key existed keeps
    // working.
    let cfg = write_at("cfg-call-depth.yaml", "max_call_depth: 100\n");
    let o = run_env(
        &["run", f.to_str().unwrap()],
        &[("BLUE_CONFIG", cfg.to_str().unwrap())],
    );
    assert!(
        !o.status.success(),
        "depth 500 under a bound of 100: {}",
        stdout(&o)
    );
    assert!(
        stderr(&o).contains("call depth budget of 100 exceeded in `f`"),
        "the error must name the configured bound and the function: {}",
        stderr(&o)
    );
}

/// **`max_steps` is read from the deployed YAML**: a loop with no exit ends in
/// a typed error naming the function, at the configured bound rather than the
/// shipped one.
#[test]
fn max_steps_is_read_from_the_deployed_yaml() {
    let f = write("spin-bounded", "def spin(n)\n  spin(n + 1)\nend\nspin(0)");
    let cfg = write_at("cfg-steps.yaml", "max_steps: 100000\n");
    let o = run_env(
        &["run", f.to_str().unwrap()],
        &[("BLUE_CONFIG", cfg.to_str().unwrap())],
    );
    assert!(!o.status.success());
    assert!(
        stderr(&o).contains("fuel budget of 100000 exceeded in `spin`"),
        "{}",
        stderr(&o)
    );
}

#[test]
fn config_show_prints_the_execution_bounds() {
    let out = stdout(&run(&["config", "default"]));
    assert!(out.contains("max_call_depth: 100000"), "{out}");
    assert!(out.contains("max_steps: null"), "{out}");
}

/// **A run longer than 50M steps completes under the default config.**
///
/// Long runs are behaviour blue has always had (simulations, tools on nodes),
/// so the step bound must not be on by default. The same program is first
/// shown to exceed 50M steps — refused under `max_steps: 50000000` — so the
/// default passing is evidence about the default, not about a short program.
///
/// Red run, recorded 2026-09-30: against the 50M default shipped in `345f922`
/// the default run failed with ``fuel budget of 50000000 exceeded in `count` ``.
#[test]
fn a_run_past_fifty_million_steps_completes_under_the_default_config() {
    let f = write(
        "long-run",
        "def count(n)\n  if n == 0\n    :done\n  else\n    count(n - 1)\n  end\nend\ncount(8000000)",
    );
    let cfg = write_at("cfg-50m.yaml", "max_steps: 50000000\n");
    let bounded = run_env(
        &["run", f.to_str().unwrap()],
        &[("BLUE_CONFIG", cfg.to_str().unwrap())],
    );
    assert!(
        stderr(&bounded).contains("fuel budget of 50000000 exceeded in `count`"),
        "precondition: the program runs past 50M steps: {}",
        stderr(&bounded)
    );
    let o = run(&["run", f.to_str().unwrap()]);
    assert!(o.status.success(), "{}", stderr(&o));
    assert_eq!(stdout(&o).trim(), ":done");
}