axbuild 0.5.0

An OS build lib toolkit used by arceos
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
use std::{
    fs,
    os::unix::fs::PermissionsExt,
    path::{Path, PathBuf},
    process::Command,
};

use regex::Regex;
use tempfile::tempdir;
use walkdir::WalkDir;

use super::{
    app_qemu_test_case, load_qemu_app_case_fields, prepare_qemu_app_case,
    qemu_app_managed_rootfs_paths, read_qemu_app_config, resolve_qemu_config,
};
use crate::{
    rootfs::qemu::RootfsWritePolicy,
    starry::app::{
        StarryAppQemuCase, discover_apps,
        test_support::{write_case_file, write_test_image_config},
    },
    test::case::HostHttpServerConfig,
};

#[tokio::test]
async fn app_owned_rootfs_runs_declared_builder_without_default_rootfs() {
    let root = tempdir().unwrap();
    write_test_image_config(root.path());
    write_case_file(
        root.path(),
        "nixos",
        "qemu-x86_64.toml",
        r#"args = [
  "-drive",
  "id=disk0,if=none,format=raw,file=${workspace}/.tgos-images/rootfs-x86_64-nixos.img/rootfs-x86_64-nixos.img",
]
uefi = true
to_bin = true
success_regex = []
fail_regex = []

[rootfs_preparation]
mode = "app-owned"
builder = "build-rootfs.sh"
target_arch = "x86_64"
"#,
    );
    write_case_file(
        root.path(),
        "nixos",
        "build-rootfs.sh",
        "#!/bin/sh\nset -eu\nprintf 'nixos-image' >\"$STARRY_ROOTFS\"\n",
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "nixos")
        .unwrap();

    let case = prepare_qemu_app_case(root.path(), &app, Some("x86_64"), None)
        .await
        .unwrap();

    assert_eq!(fs::read(&case.rootfs_path).unwrap(), b"nixos-image");
    assert!(!root.path().join("tmp/axbuild/rootfs").exists());
}

#[tokio::test]
async fn app_owned_rootfs_rejects_builder_that_does_not_publish_artifact() {
    let root = tempdir().unwrap();
    write_test_image_config(root.path());
    write_case_file(
        root.path(),
        "nixos",
        "qemu-x86_64.toml",
        r#"args = [
  "-drive",
  "id=disk0,if=none,format=raw,file=${workspace}/.tgos-images/rootfs-x86_64-nixos.img/rootfs-x86_64-nixos.img",
]
uefi = true
to_bin = true
success_regex = []
fail_regex = []

[rootfs_preparation]
mode = "app-owned"
builder = "build-rootfs.sh"
target_arch = "x86_64"
"#,
    );
    write_case_file(
        root.path(),
        "nixos",
        "build-rootfs.sh",
        "#!/bin/sh\nexit 0\n",
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "nixos")
        .unwrap();

    let error = prepare_qemu_app_case(root.path(), &app, Some("x86_64"), None)
        .await
        .unwrap_err()
        .to_string();

    assert!(
        error.contains("did not publish"),
        "unexpected error: {error}"
    );
}

#[tokio::test]
async fn app_owned_rootfs_rejects_target_arch_mismatch_before_builder_runs() {
    let root = tempdir().unwrap();
    write_test_image_config(root.path());
    let builder_marker = root.path().join("builder-ran");
    write_case_file(
        root.path(),
        "nixos",
        "qemu-x86_64.toml",
        r#"args = [
  "-drive",
  "id=disk0,if=none,format=raw,file=${workspace}/.tgos-images/rootfs-x86_64-nixos.img/rootfs-x86_64-nixos.img",
]
uefi = true
to_bin = true
success_regex = []
fail_regex = []

[rootfs_preparation]
mode = "app-owned"
builder = "build-rootfs.sh"
target_arch = "aarch64"
"#,
    );
    write_case_file(
        root.path(),
        "nixos",
        "build-rootfs.sh",
        &format!("#!/bin/sh\ntouch '{}'\n", builder_marker.display()),
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "nixos")
        .unwrap();

    let error = prepare_qemu_app_case(root.path(), &app, Some("x86_64"), None)
        .await
        .unwrap_err()
        .to_string();

    assert!(
        error.contains("targets `aarch64`"),
        "unexpected error: {error}"
    );
    assert!(!builder_marker.exists());
}

#[test]
fn starrynixos_qemu_config_enforces_app_owned_boot_contract() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_path = repo.join("apps/starry/nixos/qemu-x86_64.toml");
    let config: toml::Value = toml::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();

    assert_eq!(
        config.get("uefi").and_then(toml::Value::as_bool),
        Some(true)
    );
    assert_eq!(
        config.get("to_bin").and_then(toml::Value::as_bool),
        Some(true)
    );
    assert_eq!(
        config.get("timeout").and_then(toml::Value::as_integer),
        Some(600)
    );
    let qemu_args = config
        .get("args")
        .and_then(toml::Value::as_array)
        .expect("StarryNixOS QEMU args must be an array");
    let qemu_args = qemu_args
        .iter()
        .map(|arg| arg.as_str().expect("QEMU arguments must be strings"))
        .collect::<Vec<_>>();
    assert!(qemu_args.iter().any(|arg| {
        arg.contains("rootfs-x86_64-nixos.img")
            && arg.contains("format=raw")
            && !arg.contains("alpine")
    }));
    assert!(
        qemu_args.windows(2).any(|args| args == ["-smp", "8"]),
        "StarryNixOS QEMU acceptance must use eight vCPUs"
    );

    let preparation = config
        .get("rootfs_preparation")
        .and_then(toml::Value::as_table)
        .expect("StarryNixOS must declare rootfs preparation");
    assert_eq!(
        preparation.get("mode").and_then(toml::Value::as_str),
        Some("app-owned")
    );
    assert_eq!(
        preparation.get("target_arch").and_then(toml::Value::as_str),
        Some("x86_64")
    );
    assert_eq!(
        preparation.get("builder").and_then(toml::Value::as_str),
        Some("build-rootfs.sh")
    );
}

#[test]
fn starrynixos_qemu_matcher_requires_ordered_evidence_and_rejects_failures() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_path = repo.join("apps/starry/nixos/qemu-x86_64.toml");
    let config: toml::Value = toml::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();
    let timeout = config
        .get("timeout")
        .and_then(toml::Value::as_integer)
        .unwrap_or_default();
    assert!(
        timeout > 0,
        "{} must classify a partial boot as a timeout instead of waiting indefinitely",
        config_path.display()
    );
    let success_regex = config
        .get("success_regex")
        .and_then(toml::Value::as_array)
        .and_then(|patterns| patterns.first())
        .and_then(toml::Value::as_str)
        .map(Regex::new)
        .expect("StarryNixOS must have one compound success regex")
        .unwrap();

    let complete = "STARRY_NIXOS_PHASE=pid1\nSTARRY_NIXOS_PHASE=activation\\
                    nSTARRY_NIXOS_PHASE=systemd\nSTARRY_NIXOS_PHASE=marker\\
                    nSTARRY_NIXOS_SYSTEM_PASSED\n";
    assert!(success_regex.is_match(complete));
    assert!(!success_regex.is_match(
        "STARRY_NIXOS_PHASE=pid1\nSTARRY_NIXOS_PHASE=activation\nSTARRY_NIXOS_SYSTEM_PASSED\n"
    ));
    assert!(!success_regex.is_match(
        "STARRY_NIXOS_PHASE=activation\nSTARRY_NIXOS_PHASE=pid1\nSTARRY_NIXOS_PHASE=systemd\\
         nSTARRY_NIXOS_PHASE=marker\nSTARRY_NIXOS_SYSTEM_PASSED\n"
    ));

    let fail_regexes = config
        .get("fail_regex")
        .and_then(toml::Value::as_array)
        .expect("StarryNixOS must declare terminal failure patterns")
        .iter()
        .map(|pattern| Regex::new(pattern.as_str().unwrap()).unwrap())
        .collect::<Vec<_>>();
    for failure in [
        "kernel panicked at boot",
        "FATAL: PID 1 exited",
        "STARRY_NIXOS_SYSTEM_FAILED: phase=activation",
        "marker.service: Failed with result 'exit-code'",
        "Failed to start Verify the StarryNixOS stage-2 baseline",
    ] {
        assert!(
            fail_regexes.iter().any(|regex| regex.is_match(failure)),
            "failure was not rejected: {failure}"
        );
    }
}

#[test]
fn qemu_config_selection_prefers_exact_arch_config() {
    let root = tempdir().unwrap();
    write_case_file(
        root.path(),
        "codex-cli",
        "qemu-x86_64-codex-help.toml",
        "args = []\n",
    );
    let exact = write_case_file(root.path(), "codex-cli", "qemu-x86_64.toml", "args = []\n");
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "codex-cli")
        .unwrap();

    let selected = resolve_qemu_config(&app, Some("x86_64"), None)
        .unwrap()
        .unwrap();

    assert_eq!(selected, exact);
}

#[tokio::test]
async fn qemu_case_uses_starry_default_arch_without_an_arch_argument() {
    let root = tempdir().unwrap();
    write_case_file(
        root.path(),
        "qemu/apt",
        "qemu-riscv64.toml",
        "args = []\nuefi = false\nto_bin = true\nsuccess_regex = []\nfail_regex = []\n",
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "qemu/apt")
        .unwrap();

    let case = prepare_qemu_app_case(root.path(), &app, None, None)
        .await
        .unwrap();

    assert_eq!(case.arch, crate::context::DEFAULT_STARRY_ARCH);
}

#[test]
fn qemu_config_selection_rejects_variant_only_default() {
    let root = tempdir().unwrap();
    write_case_file(
        root.path(),
        "codex-cli",
        "qemu-x86_64-codex-help.toml",
        "args = []\n",
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "codex-cli")
        .unwrap();

    let err = resolve_qemu_config(&app, Some("x86_64"), None)
        .unwrap_err()
        .to_string();

    assert!(err.contains("qemu-x86_64.toml"));
}

#[test]
fn qemu_config_selection_uses_explicit_variant_config() {
    let root = tempdir().unwrap();
    let explicit = write_case_file(
        root.path(),
        "codex-cli",
        "qemu-x86_64-codex-syscall-hunt.toml",
        "args = []\n",
    );
    write_case_file(
        root.path(),
        "codex-cli",
        "qemu-x86_64-codex-help.toml",
        "args = []\n",
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "codex-cli")
        .unwrap();

    let selected = resolve_qemu_config(
        &app,
        Some("x86_64"),
        Some(Path::new("qemu-x86_64-codex-syscall-hunt.toml")),
    )
    .unwrap()
    .unwrap();

    assert_eq!(selected, explicit);
}

#[test]
fn qemu_case_fields_load_grouped_commands_and_subcases() {
    let root = tempdir().unwrap();
    write_case_file(
        root.path(),
        "qemu/sqlite",
        "qemu-x86_64.toml",
        "args = []\nuefi = false\nto_bin = true\nsuccess_regex = []\nfail_regex = \
         []\ntest_commands = [\"/usr/bin/app-sqlite\", \"/usr/bin/app-sqlite-deep\"]\n",
    );
    write_case_file(
        root.path(),
        "qemu/sqlite/app-sqlite/c",
        "CMakeLists.txt",
        "cmake_minimum_required(VERSION 3.20)\n",
    );
    write_case_file(
        root.path(),
        "qemu/sqlite/app-sqlite-deep/c",
        "CMakeLists.txt",
        "cmake_minimum_required(VERSION 3.20)\n",
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "qemu/sqlite")
        .unwrap();
    let qemu_config = resolve_qemu_config(&app, Some("x86_64"), None).unwrap();

    let fields =
        load_qemu_app_case_fields(root.path(), &app, qemu_config.as_deref().unwrap()).unwrap();

    assert_eq!(
        fields.test_case.test_commands,
        vec!["/usr/bin/app-sqlite", "/usr/bin/app-sqlite-deep"]
    );
    assert_eq!(fields.test_case.subcases.len(), 2);
}

#[test]
fn qemu_case_fields_load_configured_managed_rootfs() {
    let root = tempdir().unwrap();
    write_test_image_config(root.path());
    let rootfs_path = root.path().join(".tgos-images/rootfs-aarch64-debian.img");
    write_case_file(
        root.path(),
        "qemu/apt",
        "qemu-aarch64.toml",
        r#"args = [
  "-drive",
  "id=disk0,if=none,format=raw,file=${workspace}/.tgos-images/rootfs-aarch64-debian.img",
]
uefi = false
to_bin = true
success_regex = []
fail_regex = []
"#,
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "qemu/apt")
        .unwrap();
    let qemu_config = resolve_qemu_config(&app, Some("aarch64"), None).unwrap();

    let fields =
        load_qemu_app_case_fields(root.path(), &app, qemu_config.as_deref().unwrap()).unwrap();

    assert_eq!(fields.rootfs_path, Some(rootfs_path));
    assert_eq!(fields.write_policy, RootfsWritePolicy::Discard);
}

#[test]
fn apk_equivalence_qemu_configs_resolve_with_default_image_config() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let workspace = tempdir().unwrap();

    for (case, arch) in [
        ("apk-add-fs-equivalence", "riscv64"),
        ("apk-add-fs-equivalence", "x86_64"),
        ("apk-net-equivalence", "riscv64"),
        ("apk-net-equivalence", "x86_64"),
    ] {
        let config_path = repo
            .join("apps/starry/qemu")
            .join(case)
            .join(format!("qemu-{arch}.toml"));
        let qemu = read_qemu_app_config(&config_path).unwrap();

        let rootfs_paths = qemu_app_managed_rootfs_paths(workspace.path(), &qemu).unwrap();

        assert_eq!(
            rootfs_paths,
            vec![
                workspace
                    .path()
                    .join(format!("tmp/axbuild/rootfs/rootfs-{arch}-alpine.img"))
            ],
            "{} must use the default managed rootfs directory",
            config_path.display()
        );
    }
}

#[test]
fn qemu_case_fields_load_persistent_rootfs_policy() {
    let root = tempdir().unwrap();
    write_case_file(
        root.path(),
        "macos-selfbuild",
        "qemu-aarch64.toml",
        r#"args = []
uefi = false
to_bin = true
rootfs_write_policy = "persist"
success_regex = []
fail_regex = []
"#,
    );
    let app = discover_apps(root.path())
        .unwrap()
        .into_iter()
        .find(|app| app.name == "macos-selfbuild")
        .unwrap();
    let qemu_config = resolve_qemu_config(&app, Some("aarch64"), None).unwrap();

    let fields =
        load_qemu_app_case_fields(root.path(), &app, qemu_config.as_deref().unwrap()).unwrap();

    assert_eq!(fields.write_policy, RootfsWritePolicy::Persist);
}

#[test]
fn selfhost_x86_app_preserves_the_persistent_build_contract() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let app_dir = repo.join("apps/starry/selfhost/selfhost-full-kernel");
    let config_path = app_dir.join("qemu-x86_64.toml");
    let config: toml::Value = toml::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();

    assert_eq!(
        config
            .get("rootfs_write_policy")
            .and_then(toml::Value::as_str),
        Some("persist"),
        "{} must persist the guest-built kernel",
        config_path.display()
    );
    assert_eq!(
        config.get("shell_init_cmd").and_then(toml::Value::as_str),
        Some("/bin/sh /opt/starry-selfhost-run.sh"),
        "{} must use the staged non-interactive guest runner",
        config_path.display()
    );
    let qemu_args = config
        .get("args")
        .and_then(toml::Value::as_array)
        .expect("selfhost qemu args must be an array");
    let qemu_args = qemu_args
        .iter()
        .map(|arg| arg.as_str().expect("QEMU arguments must be strings"))
        .collect::<Vec<_>>();
    assert!(
        qemu_args.contains(&"-no-shutdown")
            && qemu_args.windows(2).any(|args| args == ["-smp", "4"])
            && qemu_args.windows(2).any(|args| args == ["-m", "16G"])
            && qemu_args
                .windows(2)
                .any(|args| args == ["-netdev", "user,id=net0"])
            && qemu_args
                .windows(2)
                .any(|args| args == ["-device", "virtio-net-pci,netdev=net0"]),
        "{} must wait for an explicit success or failure marker before QEMU exits",
        config_path.display()
    );
    assert!(
        fs::read_to_string(&config_path)
            .unwrap()
            .contains("rootfs-x86_64-selfhost.img"),
        "{} must select a managed per-app rootfs",
        config_path.display()
    );

    let prebuild_path = app_dir.join("prebuild.sh");
    let prebuild = fs::read_to_string(&prebuild_path).unwrap();
    assert!(
        prebuild.contains("tgoskits-src.tar")
            && prebuild.contains("starry-selfhost-run.sh")
            && prebuild.contains("starry-selfhost-reboot-guard.sh")
            && prebuild.contains("cargo xtask image resize")
            && prebuild.contains("SELFHOST_ROOTFS_SIZE_MIB:-32768")
            && prebuild.contains("stage_guest_resolver")
            && prebuild.contains("/run/systemd/resolve/resolv.conf")
            && prebuild.contains("sha256sum --check --status")
            && prebuild.contains("--prefix=\"$toolchain_dir\"")
            && prebuild.contains(".starry-selfhost-toolchain-version"),
        "{} must stage source, the guest runner, the reboot guard, and a usable resolver into a \
         32 GiB rootfs, and must install verified Rust components into a versioned toolchain \
         archive",
        prebuild_path.display()
    );

    let guest_runner_path = app_dir.join("guest-selfbuild.sh");
    let guest_runner = fs::read_to_string(&guest_runner_path).unwrap();
    assert!(
        guest_runner.contains("x86_64-unknown-linux-musl")
            && guest_runner.contains("TOOLCHAIN=\"nightly-2026-07-15\"")
            && guest_runner.contains("RUSTUP_TOOLCHAIN=\"starry-selfhost-")
            && guest_runner.contains("--default-toolchain none")
            && guest_runner.contains("export RUSTUP_TOOLCHAIN")
            && guest_runner.contains("rustc -vV")
            && guest_runner.contains("cargo-binutils --version 0.4.0 --locked")
            && guest_runner.contains("ksym --version 0.6.0 --locked")
            && guest_runner.contains("tg-xtask")
            && guest_runner.contains("SELF_COMPILE_SUCCESS")
            && !guest_runner.contains("SELFHOST_RUST_TOOLCHAIN")
            && !guest_runner.contains("x86_64-unknown-linux-gnu")
            && !guest_runner.contains("export CARGO_TARGET_DIR")
            && guest_runner.contains("SELFHOST_TARGET_DIR:-/opt/starry-selfhost-target")
            && guest_runner.contains("ln -s \"$TARGET_DIR\" \"$SOURCE_DIR/target\"")
            && guest_runner.contains("SELFHOST_CARGO_BUILD_JOBS:-2")
            && guest_runner
                .contains("$SOURCE_DIR/target/x86_64-unknown-linux-musl/release/starryos"),
        "{} must build the canonical x86_64 path with a native musl host toolchain",
        guest_runner_path.display()
    );
}

#[test]
fn selfhost_reboot_guard_reports_the_interrupted_phase() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let guard =
        repo.join("apps/starry/selfhost/selfhost-full-kernel/guest-selfbuild-reboot-guard.sh");
    let root = tempdir().unwrap();
    let state = root.path().join("state");
    let bin_dir = root.path().join("bin");
    let poweroff = bin_dir.join("poweroff");
    let poweroff_marker = root.path().join("poweroff-called");
    fs::create_dir(&bin_dir).unwrap();
    fs::write(
        &poweroff,
        "#!/bin/sh\nprintf 'called\\n' >\"$POWER_OFF_MARKER\"\n",
    )
    .unwrap();
    fs::set_permissions(&poweroff, fs::Permissions::from_mode(0o755)).unwrap();
    fs::write(&state, "running test-run kernel\n").unwrap();

    let output = Command::new("/bin/sh")
        .arg(&guard)
        .env("SELFHOST_STATE_FILE", &state)
        .env("POWER_OFF_MARKER", &poweroff_marker)
        .env("PATH", &bin_dir)
        .output()
        .unwrap();

    assert!(!output.status.success());
    assert!(
        String::from_utf8_lossy(&output.stdout)
            .contains("SELF_COMPILE_FAILED: unexpected guest reboot during kernel")
    );
    assert_eq!(fs::read_to_string(&poweroff_marker).unwrap(), "called\n");

    fs::write(&state, "ready test-run prebuild\n").unwrap();
    fs::remove_file(&poweroff_marker).unwrap();
    let output = Command::new("/bin/sh")
        .arg(&guard)
        .env("SELFHOST_STATE_FILE", &state)
        .env("POWER_OFF_MARKER", &poweroff_marker)
        .env("PATH", &bin_dir)
        .output()
        .unwrap();

    assert!(output.status.success());
    assert!(!String::from_utf8_lossy(&output.stdout).contains("SELF_COMPILE_FAILED"));
    assert!(!poweroff_marker.exists());
}

#[test]
fn app_qemu_test_case_preserves_host_symbolize_success_regex() {
    let case_dir = PathBuf::from("/tmp/apps/starry/memtrack-backtrace");
    let qemu_config_path = case_dir.join("qemu-x86_64.toml");
    let case = StarryAppQemuCase {
        name: "memtrack-backtrace".to_string(),
        arch: "x86_64".to_string(),
        target: "x86_64-unknown-none".to_string(),
        build_config_path: None,
        qemu_config_path: Some(qemu_config_path.clone()),
        rootfs_path: PathBuf::from("/tmp/rootfs.img"),
        rootfs_write_policy: RootfsWritePolicy::Discard,
        test_commands: Vec::new(),
        host_symbolize_success_regex: vec!["symbolized".to_string()],
        host_http_server: Some(HostHttpServerConfig {
            bind: "127.0.0.1".to_string(),
            port: 18382,
            body: "fixture".to_string(),
            body_size: None,
            body_byte: b'X',
            dir: None,
        }),
        subcases: Vec::new(),
    };

    let test_case = app_qemu_test_case(&case, case_dir.clone()).unwrap();

    assert_eq!(test_case.case_dir, case_dir);
    assert_eq!(test_case.qemu_config_path, qemu_config_path);
    assert_eq!(test_case.host_symbolize_success_regex, vec!["symbolized"]);
    assert_eq!(
        test_case
            .host_http_server
            .as_ref()
            .map(|config| (config.bind.as_str(), config.port)),
        Some(("127.0.0.1", 18382))
    );
}

#[test]
fn ebpf_prebuilds_install_selected_rust_musl_target() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let ebpf_dir = repo.join("apps/starry/ebpf");
    let mut checked = 0;

    for entry in fs::read_dir(&ebpf_dir).unwrap() {
        let prebuild_path = entry.unwrap().path().join("prebuild.sh");
        if !prebuild_path.is_file() {
            continue;
        }

        let content = fs::read_to_string(&prebuild_path).unwrap();
        if !content.contains(r#"cargo build --release --target "$musl_target""#) {
            continue;
        }

        checked += 1;
        assert!(
            content.contains("rustup show active-toolchain")
                && content
                    .contains(r#"rustup target add --toolchain "$rust_toolchain" "$musl_target""#)
                && content.contains(r#"export RUSTUP_TOOLCHAIN="$rust_toolchain""#)
                && content.contains(r#"host_tools_dir="${STARRY_WORKSPACE:-$app_dir}/tmp/axbuild/starry-host-tools""#)
                && content.contains("apk add --no-cache bpf-linker")
                && content.contains("cargo install bpf-linker --version 0.10.3 --locked --root"),
            "{} must install the selected Rust musl target before nested cargo build",
            prebuild_path.display()
        );
    }

    assert!(checked > 0, "expected to check at least one eBPF prebuild");
}

#[test]
fn ebpf_build_scripts_use_selected_rustup_toolchain() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let ebpf_dir = repo.join("apps/starry/ebpf");
    let mut checked = 0;

    for entry in fs::read_dir(&ebpf_dir).unwrap() {
        let app_dir = entry.unwrap().path();
        let app_name = app_dir.file_name().unwrap().to_string_lossy();
        let build_rs = app_dir.join(app_name.as_ref()).join("build.rs");
        if !build_rs.is_file() {
            continue;
        }

        checked += 1;
        let content = fs::read_to_string(&build_rs).unwrap();
        assert!(
            content.contains(r#"std::env::var("RUSTUP_TOOLCHAIN")"#)
                && content.contains("Toolchain::Custom")
                && !content.contains("build_ebpf([ebpf_package], Toolchain::default())"),
            "{} must build eBPF with the selected rustup toolchain, not implicit nightly",
            build_rs.display()
        );
    }

    assert!(checked > 0, "expected to check at least one eBPF build.rs");
}

#[test]
fn claw_code_prebuild_replaces_stale_rootfs_directory() {
    let root = tempdir().unwrap();
    let workspace = root.path();
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let script = repo.join("apps/starry/claw-code/prebuild.sh");

    let cache = workspace.join("cache");
    let bin = cache.join("claw");
    fs::create_dir_all(&cache).unwrap();
    fs::write(&bin, b"fake claw").unwrap();

    let tools = workspace.join("tools");
    fs::create_dir_all(&tools).unwrap();
    let debugfs = tools.join("debugfs");
    fs::write(
        &debugfs,
        "#!/usr/bin/env bash\nif [ \"$1\" = \"-w\" ]; then test -f \"$2\"; fi\nexit 0\n",
    )
    .unwrap();
    fs::set_permissions(&debugfs, fs::Permissions::from_mode(0o755)).unwrap();

    let rootfs_dir = workspace.join("tmp/axbuild/rootfs");
    let default_rootfs = rootfs_dir.join("rootfs-x86_64-alpine.img");
    let app_rootfs = rootfs_dir.join("rootfs-x86_64-claw-code.img");
    fs::create_dir_all(&rootfs_dir).unwrap();
    fs::write(&default_rootfs, b"base rootfs").unwrap();

    let path = format!("{}:{}", tools.display(), std::env::var("PATH").unwrap());
    let status = Command::new("bash")
        .arg(&script)
        .current_dir(repo.join("apps/starry/claw-code"))
        .env("CLAW_CACHE_DIR", &cache)
        .env("STARRY_WORKSPACE", workspace)
        .env("STARRY_ROOTFS", &app_rootfs)
        .env("STARRY_OVERLAY_DIR", workspace.join("overlay"))
        .env("PATH", path)
        .status()
        .unwrap();

    assert!(status.success());
    assert!(app_rootfs.is_file());
    assert_eq!(fs::read(&app_rootfs).unwrap(), b"base rootfs");
    assert_eq!(fs::read(default_rootfs).unwrap(), b"base rootfs");
}

#[test]
fn syscall_count_qemu_configs_stop_after_pass_marker() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_dir = repo.join("apps/starry/ebpf/syscall_count");

    for arch in ["x86_64", "aarch64", "riscv64", "loongarch64"] {
        let config_path = config_dir.join(format!("qemu-{arch}.toml"));
        let content = fs::read_to_string(&config_path).unwrap();
        let config: toml::Value = toml::from_str(&content).unwrap();
        let success_regex = config
            .get("success_regex")
            .and_then(toml::Value::as_array)
            .unwrap();
        assert!(
            success_regex
                .iter()
                .filter_map(toml::Value::as_str)
                .any(|regex| regex.contains("SYSCALL_COUNT_PASS")),
            "{} must stop QEMU after syscall_count reports a captured syscall",
            config_path.display()
        );
    }
}

#[test]
fn loongarch64_nvme_rootfs_build_keeps_serial_console() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_path =
        repo.join("apps/starry/qemu/nvme/build-loongarch64-unknown-none-softfloat.toml");
    let content = fs::read_to_string(&config_path).unwrap();
    let config: toml::Value = toml::from_str(&content).unwrap();
    let features = config
        .get("features")
        .and_then(toml::Value::as_array)
        .expect("NVMe build config must declare features");

    assert!(
        features
            .iter()
            .filter_map(toml::Value::as_str)
            .any(|feature| feature == "ax-driver/serial"),
        "{} must keep the LoongArch serial console enabled so NVMe test markers are observable",
        config_path.display()
    );
}

#[test]
fn loongarch64_nvme_rootfs_uses_dynamic_uefi_handoff() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_path = repo.join("apps/starry/qemu/nvme/nvme-rootfs-rw-20m/qemu-loongarch64.toml");
    let content = fs::read_to_string(&config_path).unwrap();
    let config: toml::Value = toml::from_str(&content).unwrap();

    assert_eq!(
        config.get("uefi").and_then(toml::Value::as_bool),
        Some(true),
        "{} must boot the PIC kernel through the supported LoongArch dynamic UEFI handoff",
        config_path.display()
    );
    assert_eq!(
        config.get("to_bin").and_then(toml::Value::as_bool),
        Some(true),
        "{} must retain the UEFI runner's explicit BIN artifact contract",
        config_path.display()
    );
}

#[test]
fn x86_64_nvme_rootfs_uses_dynamic_uefi_handoff() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_path = repo.join("apps/starry/qemu/nvme/nvme-rootfs-rw-20m/qemu-x86_64.toml");
    let content = fs::read_to_string(&config_path).unwrap();
    let config: toml::Value = toml::from_str(&content).unwrap();

    assert_eq!(
        config.get("uefi").and_then(toml::Value::as_bool),
        Some(true),
        "{} must boot the PIC kernel through the supported x86_64 dynamic UEFI handoff",
        config_path.display()
    );
    assert_eq!(
        config.get("to_bin").and_then(toml::Value::as_bool),
        Some(true),
        "{} must retain the UEFI runner's explicit BIN artifact contract",
        config_path.display()
    );
}

#[test]
fn codex_cli_qemu_config_uses_injected_smoke_script() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_path = repo.join("apps/starry/codex-cli/qemu-x86_64.toml");
    let content = fs::read_to_string(&config_path).unwrap();
    let config: toml::Value = toml::from_str(&content).unwrap();

    let shell_init_cmd = config
        .get("shell_init_cmd")
        .and_then(toml::Value::as_str)
        .unwrap_or_default();
    assert_eq!(shell_init_cmd, "/usr/bin/codex-offline-smoke.sh");
    assert!(
        !shell_init_cmd.contains("STARRY_CODEX_STAGE_G_CODEX_HELP_PASSED")
            && !shell_init_cmd.contains("STARRY_CODEX_STAGE_G_LOGIN_STATUS_OK"),
        "{} must not inject the long smoke script through the interactive shell",
        config_path.display()
    );

    let prebuild_path = repo.join("apps/starry/codex-cli/prebuild.sh");
    let prebuild = fs::read_to_string(&prebuild_path).unwrap();
    assert!(
        prebuild.contains("/usr/bin/codex-offline-smoke.sh")
            && prebuild.contains("STARRY_CODEX_STAGE_G_CODEX_HELP_PASSED"),
        "{} must inject the offline smoke script into the rootfs overlay",
        prebuild_path.display()
    );
}

#[test]
fn llvm22_build_configs_use_current_starryos_features() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_dir = repo.join("apps/starry/llvm22");

    for name in [
        "build-aarch64-unknown-none-softfloat.toml",
        "build-loongarch64-unknown-none-softfloat.toml",
        "build-riscv64gc-unknown-none-elf.toml",
    ] {
        let config_path = config_dir.join(name);
        let content = fs::read_to_string(&config_path).unwrap();
        assert!(
            !content.contains("ax-feat/"),
            "{} must not request removed ax-feat package features",
            config_path.display()
        );
        assert!(
            content.contains("\"ax-runtime/display\""),
            "{} must enable display support through ax-runtime",
            config_path.display()
        );
        assert!(
            content.contains("\"ax-runtime/rtc\""),
            "{} must enable RTC support through ax-runtime",
            config_path.display()
        );
    }
}

#[test]
fn glibc_dynamic_smoke_prebuild_installs_selected_gnu_cross_compiler() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let prebuild_path = repo.join("apps/starry/glibc-dynamic-smoke/prebuild.sh");
    let content = fs::read_to_string(&prebuild_path).unwrap();

    assert!(
        content.contains("gcc-aarch64-linux-gnu")
            && content.contains("gcc-riscv64-linux-gnu")
            && content.contains("gcc-x86-64-linux-gnu")
            && content.contains("libc6-dev-arm64-cross")
            && content.contains("libc6-dev-riscv64-cross")
            && content.contains("#include <stdio.h>")
            && content.contains("apt-get install -y --no-install-recommends"),
        "{} must install the selected host GNU cross compiler when it is missing",
        prebuild_path.display()
    );
}

#[test]
fn apk_package_prebuilds_use_guest_apk_from_staging_root() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();

    for app in ["ffmpeg", "mosquitto"] {
        let prebuild_path = repo.join(format!("apps/starry/{app}/prebuild.sh"));
        let content = fs::read_to_string(&prebuild_path).unwrap();

        assert!(
            !content.contains("apk-tools") && !content.contains("command -v apk"),
            "{} must not require host apk-tools; Ubuntu CI does not provide it",
            prebuild_path.display()
        );
        assert!(
            content.contains("/sbin/apk")
                && content.contains("--force-no-chroot")
                && content.contains("--scripts=no"),
            "{} must install Alpine packages with the target rootfs apk",
            prebuild_path.display()
        );
    }
}

#[test]
fn nix_qemu_configs_use_dedicated_nvme_rootfs() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let app_dir = repo.join("apps/starry/nix");

    for (config_name, arch) in [
        ("qemu-x86_64.toml", "x86_64"),
        ("qemu-x86_64-shell.toml", "x86_64"),
        ("qemu-aarch64.toml", "aarch64"),
    ] {
        let config_path = app_dir.join(config_name);
        let config = fs::read_to_string(&config_path).unwrap();

        assert!(
            config.contains(&format!("rootfs-{arch}-nix.img")),
            "{} must use a Nix-specific managed rootfs so its 8 GiB resize cannot mutate the \
             shared Alpine base image",
            config_path.display()
        );
        assert!(
            !config.contains(&format!("rootfs-{arch}-alpine.img")),
            "{} must not pass the shared Alpine base image to the Nix prebuild",
            config_path.display()
        );
        assert!(
            config.contains("\"nvme,") && !config.contains("virtio-blk"),
            "{} must attach its Starry root disk through the IRQ-driven NVMe path",
            config_path.display()
        );
    }
}

#[test]
fn nix_app_installs_nix_before_guest_boot() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();

    let prebuild_path = repo.join("apps/starry/nix/prebuild.sh");
    let prebuild = fs::read_to_string(&prebuild_path).unwrap();
    assert!(
        prebuild.contains("/sbin/apk")
            && prebuild.contains("--force-no-chroot")
            && prebuild.contains("--scripts=no")
            && prebuild.contains("add nix"),
        "{} must install Alpine-packaged Nix into the app rootfs before boot",
        prebuild_path.display()
    );
    assert!(
        prebuild.contains("info --recursive --format json nix"),
        "{} must copy the full Alpine Nix dependency closure, not only newly installed packages",
        prebuild_path.display()
    );
    assert!(
        prebuild.contains("relativize_staging_absolute_symlinks")
            && prebuild.contains("realpath --relative-to="),
        "{} must make staging-root absolute symlinks qemu-user safe before running guest apk",
        prebuild_path.display()
    );

    let guest_script_path = repo.join("apps/starry/nix/test_nix.sh");
    let guest_script = fs::read_to_string(&guest_script_path).unwrap();
    assert!(
        !guest_script.contains("apk add") && !guest_script.contains("apk update"),
        "{} must not install Nix from the guest at QEMU runtime",
        guest_script_path.display()
    );
    assert!(
        guest_script.contains("command -v nix"),
        "{} must still verify that the prebuilt Nix binary is present",
        guest_script_path.display()
    );

    for script_name in ["nix-nosandbox.sh", "nix.sh", "nix-nixpkgs.sh"] {
        let script_path = repo.join("apps/starry/nix").join(script_name);
        let script = fs::read_to_string(&script_path).unwrap();
        assert!(
            script.contains("NIX_REMOTE=local"),
            "{} must use the injected single-user store instead of the daemon socket",
            script_path.display()
        );
    }
}

#[test]
fn app_qemu_applies_shared_timeout_scale() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let source_path = repo.join("scripts/axbuild/src/starry/mod.rs");
    let source = fs::read_to_string(&source_path).unwrap();

    assert!(
        source
            .matches("qemu::apply_timeout_scale(&mut qemu);")
            .count()
            >= 2,
        "{} must apply shared QEMU timeout scaling on both app qemu paths",
        source_path.display()
    );
}

#[test]
fn apk_prebuilds_do_not_poison_qemu_with_guest_library_path() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();

    for app in ["ffmpeg", "ffplay", "mosquitto"] {
        let prebuild_path = repo.join(format!("apps/starry/{app}/prebuild.sh"));
        let content = fs::read_to_string(&prebuild_path).unwrap();

        assert!(
            content.contains("env -u LD_LIBRARY_PATH")
                && !content.contains("LD_LIBRARY_PATH=\"$staging_root"),
            "{} must not expose target-rootfs libraries through host LD_LIBRARY_PATH when running \
             qemu-user",
            prebuild_path.display()
        );
    }
}

#[test]
fn go_lang_grpc_cancel_stream_uses_blocking_cancel_handler() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let source_path = repo.join("apps/starry/go-lang/go/framework_grpc.go");
    let content = fs::read_to_string(&source_path).unwrap();

    assert!(
        content.contains("serverStreamHook func")
            && content.contains("<-stream.Context().Done()")
            && content.contains("status.FromContextError(stream.Context().Err()).Err()"),
        "{} must make the cancel stream case block until client cancellation",
        source_path.display()
    );
}

#[test]
fn ffplay_prebuild_exposes_weston_private_libraries() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let prebuild_path = repo.join("apps/starry/ffplay/prebuild.sh");
    let content = fs::read_to_string(&prebuild_path).unwrap();

    assert!(
        content.contains("for dir in lib usr/lib usr/local/lib usr/libexec")
            && content.contains("ld-musl-${arch}.path")
            && content.contains("append_musl_search_path /usr/libexec")
            && content.contains("append_musl_search_path /usr/lib/weston"),
        "{} must copy and expose Weston private library directories so Alpine libexec_weston.so.0 \
         is loadable",
        prebuild_path.display()
    );
}

#[test]
fn claw_code_qemu_config_exits_after_smoke_check() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let config_path = repo.join("apps/starry/claw-code/qemu-x86_64.toml");
    let content = fs::read_to_string(&config_path).unwrap();
    let config: toml::Value = toml::from_str(&content).unwrap();

    let timeout = config
        .get("timeout")
        .and_then(toml::Value::as_integer)
        .unwrap_or_default();
    assert!(
        timeout > 0,
        "{} must not disable QEMU timeout in CI smoke runs",
        config_path.display()
    );

    let success_regex = config
        .get("success_regex")
        .and_then(toml::Value::as_array)
        .unwrap();
    assert!(
        success_regex
            .iter()
            .filter_map(toml::Value::as_str)
            .any(|regex| regex.contains("STARRY_CLAW_READY")),
        "{} must stop QEMU after the claw smoke marker",
        config_path.display()
    );

    let shell_init_cmd = config
        .get("shell_init_cmd")
        .and_then(toml::Value::as_str)
        .unwrap_or_default();
    assert!(
        shell_init_cmd.contains("test -x /usr/bin/claw"),
        "{} must verify that /usr/bin/claw was injected as an executable",
        config_path.display()
    );
    assert!(
        !shell_init_cmd.contains("STARRY_CLAW_READY")
            && !shell_init_cmd.contains("STARRY_CLAW_MISSING"),
        "{} must not echo full claw smoke markers as shell input",
        config_path.display()
    );
}

#[test]
fn debugfs_copy_commands_in_prebuild_scripts_suppress_stdout() {
    let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("axbuild manifest should live under scripts/axbuild")
        .to_path_buf();
    let mut copy_commands = 0;

    for entry in WalkDir::new(repo.join("apps/starry")) {
        let entry = entry.unwrap();
        if entry.file_name() != "prebuild.sh" {
            continue;
        }

        let content = fs::read_to_string(entry.path()).unwrap();
        for (line_index, line) in content.lines().enumerate() {
            let line = line.trim();
            if line.starts_with('#')
                || !line.contains("debugfs")
                || !(line.contains("rdump ") || line.contains("-R \"write "))
            {
                continue;
            }

            copy_commands += 1;
            assert!(
                line.contains(">/dev/null") || line.contains("1>/dev/null"),
                "{}:{} must suppress normal debugfs copy output",
                entry.path().display(),
                line_index + 1
            );
        }
    }

    assert!(
        copy_commands > 0,
        "expected to inspect debugfs copy commands"
    );
}