rproj 0.20.2

Guided bootstrap-to-game-dev CLI for Roblox: takes a fresh Windows PC to a working Roblox/Luau setup, then scaffolds projects on it
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
//! The steps that shell out and touch the network, exercised for real.
//!
//! **Not part of `cargo test`.** Every test here is `#[ignore]`d because it
//! scaffolds a genuine project: it installs rokit tools, resolves packages
//! from a registry, clones repos, and runs the quality gate. That takes
//! minutes and needs a working toolchain and network, which is the wrong
//! trade for a suite meant to run on every edit.
//!
//! ```text
//! cargo test --test live -- --ignored --test-threads=1
//! ```
//!
//! `--test-threads=1` is not optional: these share rokit's global manifest
//! and wally's package cache, and two scaffolds racing on those is a flake
//! nobody can reproduce.
//!
//! What this covers that nothing else can: every §7 landmine was found by
//! running the real thing, and the four biggest gaps in §9 are all here —
//! the shell-out steps, `rproj new`'s pickers, the generated check script,
//! and §8.2's claim about how submodule packages resolve.

mod common;

// Jest regression only (requires an already provisioned Studio/Jest machine).
// Normal `rproj new` syncs shared Rokit/Wally caches and refreshes the Studio
// runner plugin; only the temporary project itself is isolated and removed.
// $env:RPROJ_TEST_TIMEOUT = '180'
// cargo test --locked --test live jest_starter_specs_pass_and_report_failure -- --ignored --test-threads=1 --nocapture

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

use common::{DOWN, ENTER, ESC, LEFT, Session};

fn hub_creation(name: &str) -> Session {
    let mut session = Session::start(&projects_root(), &[]);
    session.wait_for("Tasks");
    session.send(DOWN);
    session.send(ENTER);
    session.wait_for("Project folder name");
    session.send(name);
    session.send(ENTER);
    session.wait_for("Review");
    session.send("Start point");
    session.send(ENTER);
    session.wait_for("Composition");
    session
}

fn hub_minimal_review(session: &mut Session) {
    session.send("Expert");
    session.send(ENTER);
    session.wait_for("Dependencies");
    session.send("None");
    session.send(ENTER);
    session.wait_for("Capabilities");
    session.send(ENTER);
    session.wait_for("Review");
}

#[test]
#[ignore = "requires recorded machine setup and optional real Rojo template validation; run serially"]
fn hub_creation_cancel_preserves_draft_boundary_and_restores_terminal() {
    let name = unique_name("hub-cancel");
    let path = projects_root().join(&name);
    let mut session = hub_creation(&name);
    hub_minimal_review(&mut session);
    assert!(!path.exists());
    session.send(ESC);
    session.wait_for("Discard this draft");
    session.send(ESC);
    session.wait_for("Review");
    session.send("\x03");
    session.wait_for("Cancelled. Nothing created.");
    session.send(ESC);
    let result = session.finish();
    assert_eq!(result.code, 0, "{}", result.text);
    assert!(!path.exists());
}

#[test]
#[ignore = "requires recorded machine setup and optional real Rojo template validation; run serially"]
fn hub_creation_refuses_a_concurrent_destination_without_overwriting() {
    let name = unique_name("hub-concurrent");
    let project = LiveProject {
        path: projects_root().join(&name),
    };
    let mut session = hub_creation(&name);
    hub_minimal_review(&mut session);
    std::fs::create_dir(project.path()).unwrap();
    std::fs::write(project.path().join("owner.txt"), "preserve").unwrap();
    session.send(ENTER);
    session.wait_for("reviewed files?");
    session.send(ENTER);
    session.wait_for("Destination already exists");
    session.send("\x03");
    session.wait_for("Cancelled. Nothing created.");
    session.send(ESC);
    assert_eq!(session.finish().code, 0);
    assert_eq!(project.read("owner.txt"), "preserve");
    assert!(!project.exists("default.project.json"));
}

#[test]
#[ignore = "requires provisioned Git/Rokit/Rojo; creates only a unique temporary project; run serially"]
fn hub_creation_confirm_hands_the_reviewed_graph_to_the_existing_executor() {
    let dirs = directories::ProjectDirs::from("", "", "rproj").unwrap();
    let setups = dirs.config_dir().join("setups");
    std::fs::create_dir_all(&setups).unwrap();
    let setup = tempfile::Builder::new()
        .prefix("rproj-hub-save-")
        .suffix(".toml")
        .tempfile_in(&setups)
        .unwrap()
        .into_temp_path();
    let setup_name = setup.file_stem().unwrap().to_str().unwrap().to_owned();
    std::fs::remove_file(&setup).unwrap();
    let name = unique_name("hub-create");
    let project = LiveProject {
        path: projects_root().join(&name),
    };
    let mut session = hub_creation(&name);
    hub_minimal_review(&mut session);
    session.send("Save named setup");
    session.send(ENTER);
    session.wait_for("New setup name");
    session.send(&setup_name);
    session.send(ENTER);
    session.wait_for("Save setup on Create");
    session.send(&"\x7f".repeat("Save named setup".len()));
    session.send("Create");
    assert!(!project.path().exists());
    assert!(!setup.exists());
    session.send(ENTER);
    session.wait_for("reviewed files?");
    assert!(!project.path().exists());
    session.send(ENTER);
    session.wait_for("is ready");
    session.wait_for("Press Enter to return the project.");
    session.send(ENTER);
    session.wait_for("Project actions");
    session.send("\x03");
    session.wait_for("Tasks");
    session.send(ESC);
    let result = session.finish();
    assert_eq!(result.code, 0, "{}", result.text);
    let graph: toml::Value = toml::from_str(&project.read("rproj.toml")).unwrap();
    assert_eq!(graph["package_workflow"].as_str(), Some("none"));
    assert!(graph["capabilities"].as_table().unwrap().is_empty());
    assert!(project.exists("src/shared"));
    assert!(project.exists("default.project.json"));
    assert!(!project.exists("wally.toml"));
    assert!(!project.exists("rokit.toml"));
    let saved = std::fs::read(&setup).unwrap();
    assert_eq!(
        saved,
        std::fs::read(project.path().join("rproj.toml")).unwrap()
    );
    let replay_name = unique_name("hub-replay");
    let mut replay = hub_creation(&replay_name);
    replay.send(&setup_name);
    replay.send(ENTER);
    replay.wait_for("Review");
    replay.send("\x03");
    replay.wait_for("Cancelled. Nothing created.");
    replay.send(ESC);
    assert_eq!(replay.finish().code, 0);
    assert_eq!(std::fs::read(&setup).unwrap(), saved);
    assert!(!projects_root().join(replay_name).exists());
}

/// A scaffolded project, removed when the test ends however it ends.
struct LiveProject {
    path: PathBuf,
}

impl LiveProject {
    /// Scaffolds through the expert picker, selecting each key in
    /// `packages` by typing enough of its name to filter the list down.
    ///
    /// Filtering rather than counting arrow presses: the catalog's order is
    /// not this test's business, and a test that breaks when a package is
    /// added is a test nobody keeps.
    fn scaffold(name: &str, packages: &[&str], submodules: bool) -> Self {
        let root = projects_root();
        let name = unique_name(name);
        let path = root.join(&name);

        let mut session = Session::start(&root, &["new", &name]);

        // **Dependency strategy first.** It used to come after the packages,
        // which is what let a React selection silently overrule it.
        session.wait_for("How should this project get its dependencies?");
        if submodules {
            session.send("git-submodules");
            session.wait_for("git-submodules - ");
        }
        session.send(ENTER);

        session.wait_for("How do you want to pick packages?");
        session.send(&format!("{DOWN}{ENTER}")); // expert
        session.wait_for("Pick every package this project needs");
        for key in packages.iter().filter(|key| **key != "testez") {
            session.send(key);
            session.wait_for(&format!("{key} - "));
            session.send(" ");
            // Clear the filter so the next key searches the whole list.
            session.send(&"\x7f".repeat(key.len()));
        }
        session.send(ENTER);

        // Select the gate's capabilities explicitly; fresh pickers start empty.
        session.wait_for("What should this project do?");
        for key in ["lint", "format", "typecheck", "gate", "editor", "ci"]
            .into_iter()
            .chain(packages.contains(&"testez").then_some("test"))
        {
            session.send(key);
            session.wait_for(&format!("{key} - "));
            session.send(" ");
            session.send(&"\x7f".repeat(key.len()));
        }
        session.send(ENTER);
        if packages.contains(&"testez") && !submodules {
            session.wait_for("test:");
            session.send("testez");
            session.wait_for("testez - ");
            session.send(ENTER);
        }

        // The summary is not a picker - nothing here is a new decision, so
        // there is exactly one keystroke to confirm it.
        session.wait_for("Create it?");
        session.send(ENTER);

        session.wait_for("is ready");
        let outcome = session.finish();
        assert_eq!(outcome.code, 0, "scaffold failed:\n{}", outcome.text);

        Self { path }
    }

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

    fn read(&self, relative: &str) -> String {
        std::fs::read_to_string(self.path.join(relative))
            .unwrap_or_else(|e| panic!("reading {relative}: {e}"))
    }

    fn exists(&self, relative: &str) -> bool {
        self.path.join(relative).exists()
    }

    /// Contents of the generated link file for `key` in `dir`, matched on
    /// the file stem so the test doesn't hard-code a naming convention that
    /// belongs to wally. Lists the directory on failure, since "the file
    /// isn't there" is never the useful half of that message.
    fn link_file(&self, dir: &str, key: &str) -> String {
        let path = self.path.join(dir);
        let entries: Vec<PathBuf> = std::fs::read_dir(&path)
            .unwrap_or_else(|e| panic!("reading {}: {e}", path.display()))
            .filter_map(|entry| Some(entry.ok()?.path()))
            .collect();
        let found = entries.iter().find(|entry| {
            entry
                .file_stem()
                .is_some_and(|stem| stem.eq_ignore_ascii_case(key))
        });
        match found {
            Some(file) => std::fs::read_to_string(file).expect("read link file"),
            None => panic!(
                "no link file for `{key}` in {}. It holds: {}",
                path.display(),
                entries
                    .iter()
                    .filter_map(|e| e.file_name().map(|n| n.to_string_lossy().into_owned()))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        }
    }

    /// Runs the project's own quality gate and returns its exit code.
    fn gate(&self) -> i32 {
        let (code, output) = run(&self.path, "lute", &["run", "check"]);
        if code != 0 {
            eprintln!("Quality gate failed (exit {code}):\n{output}");
        }
        code
    }
}

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

fn projects_root() -> PathBuf {
    let dirs = directories::ProjectDirs::from("", "", "rproj").expect("config directory");
    let text = std::fs::read_to_string(dirs.config_dir().join("config.toml"))
        .expect("live tests require an already provisioned machine");
    let config: toml::Value = toml::from_str(&text).expect("valid machine configuration");
    assert!(
        config
            .get("last_checked")
            .and_then(toml::Value::as_str)
            .is_some(),
        "run machine setup explicitly before live tests"
    );
    let root = config
        .get("roblox_projects_root")
        .and_then(toml::Value::as_str)
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            PathBuf::from(std::env::var_os("USERPROFILE").expect("USERPROFILE"))
                .join("Documents/RobloxProjects")
        });
    assert!(
        root.is_dir(),
        "live test project root must already exist: {}",
        root.display()
    );
    root
}

fn unique_name(label: &str) -> String {
    use std::sync::atomic::{AtomicUsize, Ordering};
    static NEXT: AtomicUsize = AtomicUsize::new(0);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let name = format!(
        "rproj-audit-{label}-{}-{nanos}-{}",
        std::process::id(),
        NEXT.fetch_add(1, Ordering::Relaxed)
    );
    assert!(
        !projects_root().join(&name).exists(),
        "scratch project already exists"
    );
    name
}

/// Runs a toolchain command in `dir`, returning its exit code and output.
/// Tools are invoked through rokit's shims, the same way a developer's
/// shell would find them.
fn run(dir: &Path, tool: &str, args: &[&str]) -> (i32, String) {
    let shim = PathBuf::from(std::env::var_os("USERPROFILE").expect("USERPROFILE"))
        .join(".rokit")
        .join("bin")
        .join(format!("{tool}.exe"));
    let program = if shim.is_file() {
        shim
    } else {
        PathBuf::from(tool)
    };

    let output = Command::new(&program)
        .args(args)
        .current_dir(dir)
        .output()
        .unwrap_or_else(|e| panic!("spawning {}: {e}", program.display()));
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    (output.status.code().unwrap_or(-1), text)
}

/// Invalid saved setups must fail before even explicit machine reconfiguration.
/// Send no input: a regression reaching an installer prompt times out instead
/// of approving it. Every setup fixture has an exclusively reserved filename.
#[test]
#[ignore = "uses real machine config/setup paths and optional Rojo template validation; run serially"]
fn invalid_saved_setups_refuse_before_reconfiguration_or_creation() {
    let root = projects_root();
    let dirs = directories::ProjectDirs::from("", "", "rproj").expect("config directory");
    let config_path = dirs.config_dir().join("config.toml");
    let machine_before = std::fs::read(&config_path).expect("read machine config");
    let setups = dirs.config_dir().join("setups");
    std::fs::create_dir_all(&setups).expect("create setup directory");
    let scratch = tempfile::Builder::new()
        .prefix("rproj-refusal-")
        .tempdir_in(&root)
        .expect("create unique project scratch directory");
    let project_prefix = scratch.path().file_name().unwrap().to_str().unwrap();
    let output_path = tempfile::Builder::new()
        .prefix("rproj-refusal-output-")
        .suffix(".toml")
        .tempfile_in(&setups)
        .expect("reserve output setup sentinel")
        .into_temp_path();
    let output_name = output_path.file_stem().unwrap().to_str().unwrap();
    let sentinel = b"preserve this existing setup byte-for-byte\n";
    std::fs::write(&output_path, sentinel).unwrap();

    for (label, contents, error) in [
        ("missing", None, "no saved setup called"),
        ("malformed", Some("mode = [".to_string()), "failed to parse"),
        (
            "jest-with-none",
            Some("package_workflow = 'none'\n[capabilities]\ntest = 'jest-roblox'\n".to_string()),
            "selects Jest Roblox without Wally",
        ),
        (
            "jest-with-submodules",
            Some(
                "package_workflow = 'git-submodules'\n[capabilities]\ntest = 'jest-roblox'\n"
                    .to_string(),
            ),
            "selects Jest Roblox without Wally",
        ),
    ] {
        let setup_path = tempfile::Builder::new()
            .prefix(&format!("rproj-refusal-{label}-"))
            .suffix(".toml")
            .tempfile_in(&setups)
            .expect("reserve input setup fixture")
            .into_temp_path();
        let setup_name = setup_path.file_stem().unwrap().to_str().unwrap();
        if let Some(text) = &contents {
            std::fs::write(&setup_path, text).expect("write owned setup fixture");
        } else {
            std::fs::remove_file(&setup_path).expect("remove reserved missing setup");
        }
        let project_name = format!("{project_prefix}/{label}/project");
        let outcome = Session::start(
            &root,
            &[
                "new",
                &project_name,
                "--like",
                setup_name,
                "--reconfigure",
                "--save-setup",
                output_name,
            ],
        )
        .finish();
        assert_eq!(outcome.code, 1, "{label}: {}", outcome.text);
        outcome.assert_contains(error);
        // The setup-specific identifier prevents an unrelated template/config
        // error (or a generic nonzero exit) from satisfying the refusal check.
        outcome.assert_contains(label);
        for forbidden in [
            "System apps",
            "Rokit-managed CLI tools",
            "Machine setup",
            "Scaffolding",
            "Create it?",
            "is ready",
        ] {
            outcome.assert_lacks(forbidden);
        }
        outcome.assert_lacks(&format!("saved setup `{output_name}`"));
        assert!(
            !scratch.path().join(label).exists(),
            "{label}: refusal created the destination or its parent"
        );
        assert_eq!(std::fs::read(&config_path).unwrap(), machine_before);
        assert_eq!(std::fs::read(&output_path).unwrap(), sentinel);
        let fixture_path = setup_path.to_path_buf();
        match contents {
            Some(text) => {
                assert_eq!(std::fs::read_to_string(&setup_path).unwrap(), text);
                setup_path
                    .close()
                    .expect("remove owned input setup fixture");
            }
            None => assert!(!setup_path.exists(), "missing setup was created"),
        }
        assert!(!fixture_path.exists());
    }
    let output_path_check = output_path.to_path_buf();
    let scratch_path = scratch.path().to_path_buf();
    output_path
        .close()
        .expect("remove owned output setup sentinel");
    scratch
        .close()
        .expect("remove empty project scratch directory");
    assert!(!output_path_check.exists());
    assert!(!scratch_path.exists());
}

/// Saving and replaying must preserve the complete composition, not just its
/// packages. Exercise both dependency strategies so resetting to Wally cannot
/// pass accidentally. This uses shared tool caches and a uniquely reserved
/// setup file, but never replaces an existing user setup or machine config.
#[test]
#[ignore = "requires provisioned Rokit/Wally/Git, network and shared setup directory; run serially"]
fn saved_setup_replays_workflow_packages_capabilities_and_dropped_files() {
    let root = projects_root();
    let dirs = directories::ProjectDirs::from("", "", "rproj").expect("config directory");
    let setups = dirs.config_dir().join("setups");
    std::fs::create_dir_all(&setups).expect("create setup directory");

    for workflow in ["wally", "git-submodules"] {
        let scratch = tempfile::Builder::new()
            .prefix("rproj-replay-")
            .tempdir_in(&root)
            .expect("create unique replay scratch directory");
        // Reserve the exact setup filename before the CLI writes it. TempPath
        // releases the open handle and cleans up even if a later assertion fails.
        let setup = tempfile::Builder::new()
            .prefix("rproj-replay-")
            .suffix(".toml")
            .tempfile_in(&setups)
            .expect("reserve unique saved setup")
            .into_temp_path();
        let setup_name = setup.file_stem().unwrap().to_str().unwrap();
        let parent_name = scratch.path().file_name().unwrap().to_str().unwrap();
        let original_name = format!("{parent_name}/original");
        let replay_name = format!("{parent_name}/replayed");
        let original = scratch.path().join("original");
        let replayed = scratch.path().join("replayed");
        let mut session =
            Session::start(&root, &["new", &original_name, "--save-setup", setup_name]);
        session.wait_for("How should this project get its dependencies?");
        session.send(workflow);
        session.wait_for(&format!("{workflow} - "));
        session.send(ENTER);
        session.wait_for("How do you want to pick packages?");
        session.send(&format!("{DOWN}{ENTER}")); // expert
        session.wait_for("Pick every package this project needs");
        session.send(LEFT);
        for key in ["charm", "promise"] {
            session.send(key);
            session.wait_for(&format!("{key} - "));
            session.send(" ");
            session.send(&"\x7f".repeat(key.len()));
        }
        session.send(ENTER);
        session.wait_for("What should this project do?");
        session.send(LEFT);
        for key in ["format", "lint"] {
            session.send(key);
            session.wait_for(&format!("{key} - "));
            session.send(" ");
            session.send(&"\x7f".repeat(key.len()));
        }
        session.send(ENTER);
        session.wait_for("Create it?");
        session.send("customize");
        session.wait_for("customize - ");
        session.send(ENTER);
        session.wait_for("Files to keep");
        session.send(".gitignore");
        session.wait_for(".gitignore - ");
        session.send(&format!(" {ENTER}")); // drop only this housekeeping file
        session.wait_for("Create it?");
        session.send(ENTER);
        session.wait_for("is ready");
        let created = session.finish();
        assert_eq!(created.code, 0, "{workflow}: {}", created.text);
        created.assert_contains(&format!("saved setup `{setup_name}`"));

        let read_toml = |path: &Path| -> toml::Value {
            let text = std::fs::read_to_string(path)
                .unwrap_or_else(|error| panic!("reading {}: {error}", path.display()));
            toml::from_str(&text).expect("valid generated TOML")
        };
        // Pin the intended answers before comparing two outputs: otherwise
        // two equally incorrect scaffolds could satisfy the round trip.
        let expected: toml::Value = toml::from_str(&format!(
            "mode = 'expert'\npackage_workflow = '{workflow}'\n\
             packages = ['charm', 'promise']\ndropped = ['.gitignore']\n\
             [capabilities]\nformat = 'stylua'\nlint = 'selene'\n"
        ))
        .unwrap();
        assert_eq!(read_toml(&original.join("rproj.toml")), expected);
        assert_eq!(read_toml(&setup), expected);
        let saved_bytes = std::fs::read(&setup).unwrap();

        let mut session = Session::start(&root, &["new", &replay_name, "--like", setup_name]);
        // No choice prompts are answered on this run. Re-asking any of them
        // must fail, rather than silently repairing an incomplete replay.
        session.wait_for("Create it?");
        session.send(ENTER);
        session.wait_for("is ready");
        let replay = session.finish();
        assert_eq!(replay.code, 0, "{workflow}: {}", replay.text);
        replay.assert_contains(&format!("using saved setup `{setup_name}`"));
        for prompt in [
            "How should this project get its dependencies?",
            "How do you want to pick packages?",
            "Pick every package this project needs",
            "What should this project do?",
            "Files to keep",
        ] {
            replay.assert_lacks(prompt);
        }
        let mut expected_replay = expected;
        expected_replay["mode"] = format!("like:{setup_name}").into();
        assert_eq!(read_toml(&replayed.join("rproj.toml")), expected_replay);
        assert_eq!(
            std::fs::read(&setup).unwrap(),
            saved_bytes,
            "replay rewrote setup"
        );

        // The graph is not enough: the filesystem must honor those choices.
        for project in [&original, &replayed] {
            for kept in [
                "default.project.json",
                "stylua.toml",
                ".gitattributes",
                "selene.toml",
            ] {
                assert!(
                    project.join(kept).is_file(),
                    "missing {kept} in {project:?}"
                );
            }
            for absent in [".gitignore", ".vscode/settings.json", ".lute/check.luau"] {
                assert!(
                    !project.join(absent).exists(),
                    "unexpected {absent} in {project:?}"
                );
            }
            if workflow == "wally" {
                let manifest = read_toml(&project.join("wally.toml"));
                let dependencies = manifest["dependencies"].as_table().unwrap();
                assert_eq!(
                    dependencies.keys().map(String::as_str).collect::<Vec<_>>(),
                    ["charm", "promise"]
                );
                for key in ["charm", "promise"] {
                    // Wally owns the generated link extension and casing.
                    assert!(
                        std::fs::read_dir(project.join("Packages"))
                            .unwrap()
                            .any(|entry| {
                                let path = entry.unwrap().path();
                                path.is_file()
                                    && path
                                        .file_stem()
                                        .is_some_and(|stem| stem.eq_ignore_ascii_case(key))
                            }),
                        "missing installed Wally package {key} in {project:?}"
                    );
                }
                assert!(!project.join("modules").exists());
            } else {
                for module in ["Charm", "Promise"] {
                    assert!(project.join(format!("modules/{module}.luau")).is_file());
                }
                assert!(project.join(".gitmodules").is_file());
                assert!(!project.join("wally.toml").exists());
            }
            let pins = read_toml(&project.join("rokit.toml"));
            let tools = pins["tools"].as_table().expect("project-local tool pins");
            for source in ["JohnnyMorganz/StyLua@", "Kampfkarren/selene@"] {
                assert!(
                    tools
                        .values()
                        .any(|pin| pin.as_str().is_some_and(|pin| pin.starts_with(source))),
                    "missing selected {source} pin in {project:?}: {pins}"
                );
            }
        }
        assert_eq!(
            read_toml(&original.join("rokit.toml"))["tools"],
            read_toml(&replayed.join("rokit.toml"))["tools"],
            "replay changed project-local tool pins"
        );
        let setup_path = setup.to_path_buf();
        let scratch_path = scratch.path().to_path_buf();
        setup.close().expect("remove temporary saved setup");
        scratch
            .close()
            .expect("remove original and replayed scratch projects");
        assert!(!setup_path.exists());
        assert!(!scratch_path.exists());
    }
}

/// Exercises the released CLI boundary, including scaffolded pins/config,
/// runner discovery, and failure propagation. A no-tests success or a tool
/// startup failure must never satisfy either half of this regression.
#[test]
#[ignore = "requires provisioned Rokit/Wally, Studio with JestRobloxRunner, network; run serially"]
fn jest_starter_specs_pass_and_report_failure() {
    fn package_snapshot(project: &Path) -> std::collections::BTreeMap<PathBuf, Vec<u8>> {
        fn collect(
            root: &Path,
            path: &Path,
            files: &mut std::collections::BTreeMap<PathBuf, Vec<u8>>,
        ) {
            for entry in std::fs::read_dir(path).unwrap() {
                let entry = entry.unwrap();
                if entry.file_type().unwrap().is_dir() {
                    collect(root, &entry.path(), files);
                } else {
                    files.insert(
                        entry.path().strip_prefix(root).unwrap().to_path_buf(),
                        std::fs::read(entry.path()).unwrap(),
                    );
                }
            }
        }
        let mut files = std::collections::BTreeMap::new();
        for folder in ["Packages", "DevPackages"] {
            collect(project, &project.join(folder), &mut files);
        }
        files
    }

    let root = projects_root();
    let plugin = PathBuf::from(std::env::var_os("LOCALAPPDATA").expect("LOCALAPPDATA"))
        .join("Roblox/Plugins/JestRobloxRunner.rbxm");
    assert!(
        plugin.is_file(),
        "install the Jest Studio runner before running this live test"
    );

    // Own the parent before starting the scaffold, so even a partial scaffold
    // is cleaned up, without deleting or reusing any pre-existing directory.
    // A relative name keeps rproj's generated Wally package name short.
    let scratch = tempfile::Builder::new()
        .prefix("rproj-jest-")
        .tempdir_in(&root)
        .expect("create unique Jest scratch directory");
    let name = format!(
        "{}/project",
        scratch.path().file_name().unwrap().to_str().unwrap()
    );
    let project = scratch.path().join("project");
    let mut session = Session::start(&root, &["new", &name]);
    session.wait_for("How should this project get its dependencies?");
    session.send(ENTER); // Wally
    session.wait_for("How do you want to pick packages?");
    session.send(&format!("{DOWN}{ENTER}")); // expert
    session.wait_for("Pick every package this project needs");
    session.send(&format!("{LEFT}{ENTER}")); // Jest adds its own dev dependencies
    session.wait_for("What should this project do?");
    session.send(LEFT);
    session.send("test");
    session.wait_for("test - ");
    session.send(&format!(" {ENTER}"));
    session.wait_for("test:");
    session.send("jest-roblox");
    session.wait_for("jest-roblox - ");
    session.send(ENTER);
    session.wait_for("Jest execution:");
    session.send(ENTER); // Local Studio
    session.wait_for("Create it?");
    session.send(ENTER);
    session.wait_for("is ready");
    let scaffold = session.finish();
    assert_eq!(scaffold.code, 0, "{}", scaffold.text);

    // Global shims must not hide a scaffold that forgot its project pins.
    let manifest: toml::Value = toml::from_str(
        &std::fs::read_to_string(project.join("rokit.toml")).expect("generated Rokit manifest"),
    )
    .expect("valid Rokit manifest");
    let tools = manifest["tools"].as_table().expect("project tool pins");
    for source in ["christopher-buss/jest-roblox-cli@", "UpliftGames/wally@"] {
        assert!(
            tools
                .values()
                .any(|pin| pin.as_str().is_some_and(|pin| pin.starts_with(source))),
            "missing {source} pin: {manifest}\n{}",
            scaffold.text
        );
    }

    let packages_before = package_snapshot(&project);
    let passing = Session::start(
        &project,
        &[
            "test",
            "--backend",
            "studio-cli",
            "--no-color",
            "--outputFile",
            "passing.json",
        ],
    )
    .finish();
    assert_eq!(passing.code, 0, "{}", passing.text);
    assert_eq!(package_snapshot(&project), packages_before);
    let report = |name: &str| -> serde_json::Value {
        let text = std::fs::read_to_string(project.join(name)).expect("Jest result report");
        serde_json::from_str(&text).expect("valid Jest result JSON")
    };
    let passed = report("passing.json");
    assert_eq!(passed["success"], true, "{passed}");
    assert_eq!(passed["numPassedTests"], 3, "{passed}\n{}", passing.text);
    assert_eq!(passed["numFailedTests"], 0, "{passed}");
    let suites = passed["testResults"].as_array().expect("per-file results");
    assert_eq!(suites.len(), 3, "{passed}");
    for area in ["shared", "server", "client"] {
        let path = format!("tests/{area}/hello.spec.luau");
        let suite = suites
            .iter()
            .find(|suite| suite["testFilePath"] == path)
            .unwrap_or_else(|| panic!("missing {path}: {passed}"));
        assert_eq!(suite["numPassingTests"], 1, "{suite}");
        assert_eq!(suite["testResults"][0]["status"], "passed", "{suite}");
    }

    let spec_path = project.join("tests/shared/hello.spec.luau");
    let spec = std::fs::read_to_string(&spec_path).expect("generated starter spec");
    assert_eq!(spec.matches("expect(1 + 1).toBe(2)").count(), 1, "{spec}");
    let broken = spec
        .replace("expect(1 + 1).toBe(2)", "expect(1 + 1).toBe(987654)")
        .replace("it(\"runs\"", "it(\"rproj deliberate failure\"");
    std::fs::write(&spec_path, &broken).expect("break owned starter spec");
    let failing = Session::start(
        &project,
        &[
            "test",
            "--backend",
            "studio-cli",
            "--no-color",
            "--outputFile",
            "failing.json",
        ],
    )
    .finish();
    assert_eq!(failing.code, 1, "{}", failing.text);
    assert_eq!(package_snapshot(&project), packages_before);
    failing.assert_contains("rproj deliberate failure");
    failing.assert_contains("987654");
    failing.assert_contains("reported test failures (exit code 1)");
    let failed = report("failing.json");
    assert_eq!(failed["numPassedTests"], 2, "{failed}");
    assert_eq!(failed["numFailedTests"], 1, "{failed}");
    assert_eq!(failed["success"], false, "{failed}");
    let failed_suites = failed["testResults"].as_array().expect("per-file results");
    assert_eq!(failed_suites.len(), 3, "{failed}");
    let shared = failed_suites
        .iter()
        .find(|suite| suite["testFilePath"] == "tests/shared/hello.spec.luau")
        .expect("shared starter spec result");
    assert_eq!(shared["numFailingTests"], 1, "{shared}");
    assert_eq!(shared["testResults"][0]["status"], "failed", "{shared}");
    assert_eq!(
        shared["testResults"][0]["title"], "rproj deliberate failure",
        "{shared}"
    );
    assert_eq!(
        std::fs::read_to_string(spec_path).unwrap(),
        broken,
        "rproj test must preserve the user's failing spec"
    );
    println!(
        "Jest regression: 3 starter specs passed; deliberate failure returned 1 with 2 passed / 1 failed."
    );
}

/// **"rproj needs to be such that if I want, I can create a project with only
/// the rojo init basic stuff."** Driven end to end, saying no to everything.
///
/// Lives in the live suite because it drives `rproj new`'s real prompts, but
/// unlike its neighbours it needs **no network and no toolchain**: with no
/// packages, no pinned tools and no files ticked, every step that would shell
/// out is gated off. So it is the cheapest test here and the one that proves
/// the property the artifact model exists for.
///
/// Two things make it bare, and both are deliberate. `none` is a real answer
/// to the dependency question, so no manifest is offered for dependencies
/// that don't exist. And the housekeeping files (`rproj.toml`, `.gitignore`)
/// are written for every project rather than asked about, so reaching the
/// absolute minimum goes through the summary's escape hatch — one extra
/// screen for the person who wants it, none for everyone else. This test is
/// what pins that hatch open.
#[test]
#[ignore]
fn saying_no_to_everything_yields_only_the_rojo_basics() {
    let root = projects_root();
    let name = unique_name("rproj-bare-basics");
    let path = root.join(&name);

    let mut session = Session::start(&root, &["new", &name]);
    // `none` is now a real answer to the dependency question, and choosing
    // it skips the package prompts entirely rather than defaulting to Wally
    // and then offering a manifest for dependencies that don't exist.
    session.wait_for("How should this project get its dependencies?");
    session.send("none");
    session.wait_for("none - ");
    session.send(ENTER);
    session.wait_for("What should this project do?");
    session.send(&format!("{LEFT}{ENTER}")); // no capabilities

    // The housekeeping entries (`rproj.toml`, `.gitignore`) are written for
    // every project rather than asked about, so reaching the *truly* bare
    // project goes through the summary's escape hatch. One extra screen for
    // the person who wants it, none for everyone else - and this test is
    // what proves the hatch is real rather than decorative.
    session.wait_for("Create it?");
    session.send("customize");
    session.wait_for("customize - ");
    session.send(ENTER);
    session.wait_for("Files to keep");
    session.send(&format!("{LEFT}{ENTER}")); // keep nothing optional
    session.wait_for("Create it?");
    session.send(ENTER);
    session.wait_for("is ready");

    let outcome = session.finish();
    assert_eq!(outcome.code, 0, "scaffold failed:\n{}", outcome.text);

    let mut entries: Vec<String> = std::fs::read_dir(&path)
        .expect("read the project dir")
        .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
        .collect();
    entries.sort();
    assert_eq!(
        entries,
        [".git", "default.project.json", "src"],
        "a minimal answer must produce nothing else:\n{}",
        outcome.text
    );

    // And the mandatory two are real, not empty placeholders.
    assert!(path.join("default.project.json").is_file());
    assert!(path.join("src").join("shared").is_dir());

    let _ = std::fs::remove_dir_all(&path);
}

#[test]
#[ignore = "requires an already provisioned machine"]
fn confirmation_and_cancellation_preserve_a_concurrently_created_directory() {
    for cancel in [true, false] {
        let root = projects_root();
        let name = unique_name("concurrent");
        let path = root.join(&name);
        let mut session = Session::start(&root, &["new", &name]);
        session.wait_for("How should this project get its dependencies?");
        session.send("none");
        session.wait_for("none - ");
        session.send(ENTER);
        session.wait_for("What should this project do?");
        session.send(&format!("{LEFT}{ENTER}"));
        session.wait_for("Create it?");
        assert!(!path.exists());
        std::fs::create_dir(&path).unwrap();
        std::fs::write(path.join("user.txt"), "preserve me").unwrap();
        let project = LiveProject { path };
        if cancel {
            session.send("cancel");
            session.wait_for("cancel - ");
        }
        session.send(ENTER);
        let outcome = session.finish();
        assert_eq!(outcome.code, if cancel { 0 } else { 1 }, "{}", outcome.text);
        assert_eq!(project.read("user.txt"), "preserve me");
        assert!(!project.exists("default.project.json"));
    }
}

/// **The redesign, end to end.** Pick a package and capabilities,
/// and the summary must *explain* every file rather than offering
/// it as a checkbox.
///
/// Stops at the summary with `ESC` instead of completing, so this needs no
/// install: what is being checked is the text on screen before any work
/// happens. The assertions are on the reasons, not just the keys — a line
/// naming `wally.toml` with no explanation would be a tool announcing
/// decisions, and the whole point is that the user can see which earlier
/// answer to change.
#[test]
#[ignore]
fn the_summary_explains_every_file_instead_of_offering_it_as_a_choice() {
    let root = projects_root();
    let name = unique_name("rproj-summary-report");
    let path = root.join(&name);

    let mut session = Session::start(&root, &["new", &name]);
    session.wait_for("How should this project get its dependencies?");
    session.send(ENTER); // Wally, the recommended default
    session.wait_for("How do you want to pick packages?");
    session.send(&format!("{DOWN}{ENTER}")); // expert
    session.wait_for("Pick every package this project needs");
    session.send("promise");
    session.wait_for("promise - ");
    session.send(" ");
    session.send(ENTER);

    session.wait_for("What should this project do?");
    for key in ["lint", "format", "typecheck", "gate", "editor"] {
        session.send(key);
        session.wait_for(&format!("{key} - "));
        session.send(" ");
        session.send(&"\x7f".repeat(key.len()));
    }
    session.send(ENTER);

    session.wait_for("Create it?");
    let screen = session.text();

    // Every file names the answer that caused it. A list without reasons
    // would be a receipt, and the summary's whole job is showing the work.
    for expected in [
        "wally.toml",
        "this project uses Wally",
        "selene.toml",
        "you chose lint",
        "rokit.toml",
    ] {
        assert!(
            screen.contains(expected),
            "expected {expected:?} in:\n{screen}"
        );
    }
    // The capability names its tool, so a user who enabled "lint" has seen
    // the word Selene by the time the project exists.
    assert!(screen.contains("lint (Selene)"), "{screen}");
    assert!(screen.contains("format (StyLua)"), "{screen}");

    // And none of this is a checkbox: the summary is a summary. The old
    // flow rendered these as `key - description (badge)` option lines.
    for offered in ["wally.toml - ", "rokit.toml - ", "selene.toml - "] {
        assert!(
            !screen.contains(offered),
            "{offered:?} must not be a checkbox:\n{screen}"
        );
    }

    assert!(
        !path.exists(),
        "answering prompts must not create the project"
    );
    session.send(ESC);
    let _ = session.finish();
    assert!(!path.exists(), "escape must leave no project behind");
}

/// **Revision, not navigation.** Change an early answer from the summary and
/// the later ones that it makes stale are re-asked - the ones it does not
/// touch are left alone.
///
/// Needs no network: it changes the strategy to `none`, which is the branch
/// where nothing installs. What is being checked is that the graph
/// re-derives rather than that anything is written, so it cancels at the end.
#[test]
#[ignore]
fn changing_an_early_answer_reasks_only_what_it_invalidates() {
    let root = projects_root();
    let name = unique_name("rproj-revise");
    let path = root.join(&name);

    let mut session = Session::start(&root, &["new", &name]);
    session.wait_for("How should this project get its dependencies?");
    session.send(ENTER); // Wally
    session.wait_for("How do you want to pick packages?");
    session.send(&format!("{DOWN}{ENTER}")); // expert
    session.wait_for("Pick every package this project needs");
    session.send("promise");
    session.wait_for("promise - ");
    session.send(" ");
    session.send(ENTER);
    session.wait_for("What should this project do?");
    session.send(&format!("{LEFT}{ENTER}")); // nothing, so nothing installs

    // The first summary: a Wally project with a package and a manifest.
    session.wait_for("Create it?");
    let before = session.text();
    assert!(before.contains("Dependencies  Wally"), "{before}");
    assert!(before.contains("wally.toml"), "{before}");

    session.send("change");
    session.wait_for("change - ");
    session.send(ENTER);

    // The menu shows what each answer currently is, so it is answerable
    // without remembering what was said four prompts ago.
    session.wait_for("Change which answer?");
    let menu = session.text();
    assert!(menu.contains("dependencies - Wally"), "{menu}");
    assert!(menu.contains("packages - promise"), "{menu}");

    session.send("dependencies");
    session.wait_for("dependencies - ");
    session.send(ENTER);

    // Says what it is about to discard *before* discarding it.
    session.wait_for("changing this re-asks: packages");
    session.wait_for("How should this project get its dependencies?");
    session.send("none");
    session.wait_for("none - ");
    session.send(ENTER);

    // With no dependency manager the package question is skipped entirely,
    // and the manifest that only existed for Wally is gone with it.
    session.wait_for("Dependencies  none");
    let after = session.text();
    assert!(
        after.contains("Packages      none"),
        "packages were invalidated:
{after}"
    );
    assert!(
        after
            .rfind("wally.toml")
            .is_none_or(|at| at < after.rfind("Dependencies  none").unwrap()),
        "the manifest must not survive the strategy that wanted it:
{after}"
    );

    session.send("cancel");
    session.wait_for("cancel - ");
    session.send(ENTER);

    let outcome = session.finish();
    assert_eq!(
        outcome.code, 0,
        "cancelling is a clean exit:
{}",
        outcome.text
    );
    assert!(!path.exists(), "cancel must leave nothing behind");
}

/// The whole Wally chain, from picker to a green gate.
///
/// Every link here is a step that shells out or hits the network, which is
/// exactly the set no other test touches.
#[test]
#[ignore]
fn a_wally_project_scaffolds_and_passes_its_own_gate() {
    let project = LiveProject::scaffold("live-wally", &["charm", "testez"], false);

    for file in [
        "rokit.toml",
        "wally.toml",
        "selene.toml",
        "stylua.toml",
        "default.project.json",
        "sourcemap.json",
        "testez.yml",
        ".luaurc",
        ".lute/check.luau",
        ".github/workflows/ci.yml",
        ".gitattributes",
    ] {
        assert!(project.exists(file), "{file} was not scaffolded");
    }
    let dirs = directories::ProjectDirs::from("", "", "rproj").unwrap();
    let config: toml::Value =
        toml::from_str(&std::fs::read_to_string(dirs.config_dir().join("config.toml")).unwrap())
            .unwrap();
    let vscode = config["selected_system_apps"]
        .as_array()
        .unwrap()
        .iter()
        .any(|app| app.as_str() == Some("vscode"));
    assert_eq!(project.exists(".vscode/settings.json"), vscode);

    // Wally actually resolved and vendored, rather than leaving an empty
    // folder that everything downstream would fail on. Found by scanning
    // rather than named outright: the link file takes its name from the
    // alias in `wally.toml`, which is wally's business, not this test's.
    let link = project.link_file("Packages", "charm");
    // `wally install` rewrites link files without their `export type`
    // lines; `wally::sync` puts them back. Losing this is silent - the
    // types just stop existing.
    assert!(
        link.contains("export type"),
        "package types were stripped:\n{link}"
    );

    // Case-insensitive on purpose. A Wally package is mounted under the
    // alias from `wally.toml`, so the instance is `charm`, not `Charm` -
    // the casing is wally's business here. It is *not* in the submodule
    // test below, where the mount name is load-bearing (§8.2).
    let sourcemap = project.read("sourcemap.json").to_lowercase();
    assert!(
        sourcemap.contains("\"charm\""),
        "charm missing from the sourcemap"
    );

    assert_eq!(
        project.gate(),
        0,
        "a freshly scaffolded project failed its own gate"
    );
}

/// The §8.2 claim, which until now was only ever checked by hand: a
/// submodule package resolves under *both* the name project code requires
/// and the name the vendored source requires internally.
#[test]
#[ignore]
fn submodule_packages_resolve_under_both_names_and_build() {
    // charmSync pulls in charm, and both live in one upstream monorepo -
    // the case where the mount name is load-bearing.
    let project = LiveProject::scaffold("live-submodules", &["charmSync"], true);

    assert!(project.exists("modules/Charm.luau"), "link file missing");
    assert!(
        project.exists("modules/CharmSync.luau"),
        "link file missing"
    );
    assert!(project.exists("modules/submodules/default.project.json"));

    let sourcemap = project.read("sourcemap.json");
    for name in ["Charm", "CharmSync"] {
        assert!(
            sourcemap.contains(&format!("\"{name}\"")),
            "{name} missing from the sourcemap"
        );
    }

    // The real test of the mount: rojo refuses a `$path` it can't turn into
    // an instance, so a build succeeding means every declared path resolved.
    let (code, output) = run(project.path(), "rojo", &["build", "-o", "live-check.rbxlx"]);
    assert_eq!(code, 0, "rojo build failed:\n{output}");
    assert!(project.exists("live-check.rbxlx"));

    assert_eq!(project.gate(), 0, "submodule project failed its own gate");
}

/// A gate that only ever passes proves nothing. Each of the three steps is
/// broken in turn, and each has to take the gate from 0 to non-zero.
#[test]
#[ignore]
fn the_generated_gate_rejects_bad_code_one_step_at_a_time() {
    let project = LiveProject::scaffold("live-gate", &["testez"], false);
    assert_eq!(project.gate(), 0, "should start green");

    let spec = project
        .path()
        .join("tests")
        .join("shared")
        .join("hello.spec.luau");
    let original = std::fs::read_to_string(&spec).expect("starter spec");
    let (header, body) = original
        .split_once("return function()")
        .expect("starter spec returns its test function");

    // Check the intended diagnostic as well as the exit code: a syntax error
    // would fail every step at once and prove only that something ran.
    let breakages: &[(&str, &str, &str)] = &[
        (
            "luau-lsp: a string where a number is declared",
            "local wrong: number = \"not a number\"\nprint(wrong)\n\n",
            "TypeError:",
        ),
        (
            "selene: an undefined global",
            "print(someUndefinedGlobalName)\n\n",
            "error[undefined_variable]",
        ),
        (
            "stylua: space indentation where the config says tabs",
            "local function f()\n    return 1\nend\nprint(f())\n\n",
            "Diff in",
        ),
    ];

    for (what, addition, diagnostic) in breakages {
        // Luau requires return to be the block's final statement. Keep the
        // strict-mode header first and insert each defect before the return.
        std::fs::write(&spec, format!("{header}{addition}return function(){body}"))
            .expect("break the spec");
        let (code, output) = run(project.path(), "lute", &["run", "check"]);
        assert_ne!(code, 0, "the gate accepted bad code ({what}):\n{output}");
        assert!(
            output.contains(diagnostic),
            "missing intended diagnostic ({what}):\n{output}"
        );
        for syntax_error in ["SyntaxError:", "error[parse_error]", "error parsing:"] {
            assert!(
                !output.contains(syntax_error),
                "invalid syntax masked the intended failure ({what}):\n{output}"
            );
        }
        std::fs::write(&spec, &original).expect("restore the spec");
        assert_eq!(
            project.gate(),
            0,
            "restoring should go green again ({what})"
        );
    }
}

/// A `git clone` records a submodule's commit and leaves its directory
/// empty, and `rproj watch` is what repairs that. Verified by cloning
/// without `--recurse-submodules`, which is what `git clone <url>` does.
#[test]
#[ignore]
fn watch_restores_submodules_in_a_fresh_clone() {
    let project = LiveProject::scaffold("live-clone", &["charm"], true);

    let (code, output) = run(project.path(), "git", &["add", "-A"]);
    assert_eq!(code, 0, "{output}");
    let (code, output) = run(
        project.path(),
        "git",
        &[
            "-c",
            "user.email=t@t",
            "-c",
            "user.name=t",
            "commit",
            "-qm",
            "scaffold",
        ],
    );
    assert_eq!(code, 0, "{output}");

    let clone = projects_root().join(unique_name("clone-copy"));
    let (code, output) = run(
        projects_root().as_path(),
        "git",
        &[
            "clone",
            "-q",
            &project.path().display().to_string(),
            &clone.display().to_string(),
        ],
    );
    assert_eq!(code, 0, "clone failed:\n{output}");
    struct Cleanup(PathBuf);
    impl Drop for Cleanup {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }
    let _cleanup = Cleanup(clone.clone());

    // The state a teammate actually gets: the directory exists and is empty.
    let vendored = clone.join("modules").join("submodules").join("charm");
    assert!(
        std::fs::read_dir(&vendored)
            .map(|mut d| d.next().is_none())
            .unwrap_or(true),
        "the clone already has submodule contents, so this proves nothing"
    );

    // `watch` never returns on its own; it repairs, then blocks on the
    // sourcemap watcher. Getting as far as watching is the pass condition.
    let session = Session::start(&clone, &["watch"]);
    session.wait_for("submodules synced");
    // "Watching for changes" prints *before* the watcher starts, so it
    // proves nothing on its own; rojo's own line is the real signal.
    session.wait_for("Created sourcemap");
    drop(session);

    assert!(
        std::fs::read_dir(&vendored)
            .map(|mut d| d.next().is_some())
            .unwrap_or(false),
        "watch did not fetch the submodule"
    );
    assert!(
        clone.join("sourcemap.json").exists(),
        "no sourcemap after watch"
    );
}