turnout 0.7.1

A developer's switchyard: point local apps at any backend stand, keep servers and secrets at hand, build and deploy from any directory
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
use assert_cmd::Command;
use predicates::prelude::*;

fn turnout(data_dir: &std::path::Path) -> Command {
    let mut cmd = Command::cargo_bin("turnout").unwrap();
    cmd.env("TURNOUT_DATA_DIR", data_dir);
    // No test should reach github.com as a side effect of running a command.
    // The update check is already off under `CI`, but a local run would spawn
    // a background lookup from every single `setup`. The few tests that do
    // exercise the check turn it back on via `with_update_check`.
    cmd.env("TURNOUT_UPDATE_CHECK", "0");
    cmd
}

#[test]
fn status_before_setup_reports_uninitialized() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("Not set up yet"));
}

#[test]
fn setup_creates_data_directory_and_meta() {
    let dir = tempfile::tempdir().unwrap();
    let data = dir.path().join("data");
    turnout(&data)
        .args(["setup", "--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("ready to store"));
    assert!(data.join("meta.json").exists());
}

#[test]
fn setup_is_idempotent() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    turnout(dir.path())
        .args(["setup", "--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("already set up"));
}

#[test]
fn status_after_setup_shows_overview() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    turnout(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("Gateway: not running"));
}

/// Initialized data dir + a project directory to register as an app.
fn workspace() -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    let project = dir.path().join("project");
    std::fs::create_dir(&project).unwrap();
    (dir, project)
}

#[test]
fn app_crud_roundtrip() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--port", "7100"])
        .assert()
        .success()
        .stdout(predicate::str::contains("'myapp' added"));
    turnout(dir.path())
        .args(["app", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("myapp").and(predicate::str::contains(":7100")));
    turnout(dir.path())
        .args(["app", "show", "myapp"])
        .assert()
        .success()
        .stdout(predicate::str::contains("localhost:7100"));
    turnout(dir.path()).args(["app", "remove", "myapp", "--yes"]).assert().success();
    turnout(dir.path())
        .args(["app", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No apps yet"));
}

#[test]
fn app_add_rejects_duplicates_and_bad_names() {
    let (dir, project) = workspace();
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .assert()
        .failure()
        .stderr(predicate::str::contains("already exists"));
    turnout(dir.path())
        .args(["app", "add", "My App", "--path"])
        .arg(&project)
        .assert()
        .failure()
        .stderr(predicate::str::contains("invalid name"));
}

#[test]
fn app_add_detects_npm_commands() {
    let (dir, project) = workspace();
    std::fs::write(project.join("package.json"), "{}").unwrap();
    turnout(dir.path()).args(["app", "add", "webapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["app", "show", "webapp"])
        .assert()
        .success()
        .stdout(predicate::str::contains("npm run dev"));
}

/// Real scripts beat conventions: a Vue-style project calls its dev script
/// `serve`, and scripts that fill no role stay reachable through `run`.
#[test]
fn app_add_maps_package_json_scripts_to_roles() {
    let (dir, project) = workspace();
    std::fs::write(
        project.join("package.json"),
        r#"{"scripts":{"serve":"vue-cli-service serve","build":"vue-cli-service build","storybook":"start-storybook"}}"#,
    )
    .unwrap();
    std::fs::write(project.join("pnpm-lock.yaml"), "").unwrap();
    turnout(dir.path()).args(["app", "add", "webapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path()).args(["app", "show", "webapp"]).assert().success().stdout(
        predicate::str::contains("dev")
            .and(predicate::str::contains("pnpm serve"))
            .and(predicate::str::contains("pnpm storybook")),
    );
}

#[test]
fn app_edit_updates_commands_and_port() {
    let (dir, project) = workspace();
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["app", "edit", "myapp", "--port", "7200", "--command", "deploy=echo deploy"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["app", "show", "myapp"])
        .assert()
        .success()
        .stdout(predicate::str::contains("localhost:7200").and(predicate::str::contains("echo deploy")));
}

#[cfg(windows)]
#[test]
fn app_add_canonicalizes_the_drive_letter() {
    let (dir, project) = workspace();
    let display = project.display().to_string();
    // A lowercase drive letter would reach dev servers as a lowercase cwd
    // and break them (Vite resolves imports against it).
    let lowercase = format!("{}{}", display[..1].to_lowercase(), &display[1..]);
    turnout(dir.path()).args(["app", "add", "myapp", "--path", &lowercase]).assert().success();
    let canonical = std::fs::canonicalize(&project).unwrap().display().to_string();
    let canonical = canonical.strip_prefix(r"\\?\").unwrap_or(&canonical).to_string();
    turnout(dir.path())
        .args(["app", "show", "myapp"])
        .assert()
        .success()
        .stdout(predicate::str::contains(&canonical));
}

#[test]
fn gateway_run_on_a_busy_port_suggests_stopping() {
    let (dir, project) = workspace();
    // Hold the listener that chose the port rather than rebinding its number:
    // releasing it first leaves a window where another process takes the port
    // and the rebind fails (it did, on a macOS runner).
    let busy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = busy.local_addr().unwrap().port();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--port", &port.to_string()])
        .assert()
        .success();
    turnout(dir.path())
        .args(["gateway", "run"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("turnout gateway stop"));
}

#[test]
fn server_crud_roundtrip() {
    let (dir, _) = workspace();
    turnout(dir.path())
        .args([
            "server",
            "add",
            "staging",
            "--url",
            "https://staging.example.com",
            "--label",
            "Staging",
            "--ssh",
            "deploy@staging.example.com:2200",
            "--insecure",
        ])
        .assert()
        .success();
    turnout(dir.path()).args(["server", "show", "staging"]).assert().success().stdout(
        predicate::str::contains("https://staging.example.com")
            .and(predicate::str::contains("deploy@staging.example.com:2200"))
            .and(predicate::str::contains("accept invalid certificates")),
    );
    turnout(dir.path()).args(["server", "edit", "staging", "--secure"]).assert().success();
    turnout(dir.path())
        .args(["server", "show", "staging"])
        .assert()
        .success()
        .stdout(predicate::str::contains("verify certificates"));
}

#[test]
fn server_add_requires_valid_url() {
    let (dir, _) = workspace();
    turnout(dir.path())
        .args(["server", "add", "bad", "--url", "staging.example.com"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("must start with http"));
}

#[test]
fn app_cannot_allow_unknown_server() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--server", "nosuch"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no server named 'nosuch'"));
}

#[test]
fn removing_server_updates_apps() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--server", "staging"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["server", "remove", "staging", "--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Removed 'staging' from apps: myapp"));
    turnout(dir.path())
        .args(["app", "show", "myapp"])
        .assert()
        .success()
        .stdout(predicate::str::contains("none allowed yet"));
}

/// Pass commands run with the insecure file backend: the OS keyring is
/// per-process-safe but not shareable across the separate CLI invocations
/// a test makes, and CI runners have no unlocked keyring at all.
fn turnout_secrets(data_dir: &std::path::Path) -> Command {
    let mut cmd = turnout(data_dir);
    cmd.env("TURNOUT_KEYRING", "insecure-file");
    cmd
}

fn add_staging(dir: &std::path::Path) {
    turnout(dir)
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
}

fn save_access(dir: &std::path::Path) {
    turnout_secrets(dir)
        .args(["pass", "set", "staging", "--login", "deploy"])
        .write_stdin("s3cret\n")
        .assert()
        .success()
        .stdout(predicate::str::contains("saved"));
}

#[test]
fn pass_set_copy_roundtrip() {
    let (dir, _) = workspace();
    add_staging(dir.path());
    save_access(dir.path());
    turnout_secrets(dir.path())
        .args(["pass", "copy", "staging", "--show"])
        .assert()
        .success()
        .stdout(predicate::str::contains("s3cret"));
    turnout_secrets(dir.path())
        .args(["pass", "copy", "staging", "--login", "--show"])
        .assert()
        .success()
        .stdout(predicate::str::contains("deploy"));
    turnout_secrets(dir.path())
        .args(["pass", "show", "staging"])
        .assert()
        .success()
        .stdout(predicate::str::contains("deploy").and(predicate::str::contains("s3cret").not()));
    turnout_secrets(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("Access:  saved for staging"));
}

#[test]
fn pass_set_requires_known_server() {
    let (dir, _) = workspace();
    add_staging(dir.path());
    turnout_secrets(dir.path())
        .args(["pass", "set", "nosuch", "--login", "x"])
        .write_stdin("value\n")
        .assert()
        .failure()
        .stderr(predicate::str::contains("no server named 'nosuch'"));
}

#[test]
fn pass_remove_deletes_secret() {
    let (dir, _) = workspace();
    add_staging(dir.path());
    save_access(dir.path());
    turnout_secrets(dir.path()).args(["pass", "remove", "staging", "--yes"]).assert().success();
    turnout_secrets(dir.path())
        .args(["pass", "copy", "staging", "--show"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no access saved"));
}

#[test]
fn server_remove_purges_access() {
    let (dir, _) = workspace();
    add_staging(dir.path());
    save_access(dir.path());
    turnout_secrets(dir.path())
        .args(["server", "remove", "staging", "--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Removed stored access: password"));
    turnout_secrets(dir.path())
        .args(["pass", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No access saved yet"));
}

#[cfg(not(target_os = "linux"))]
#[test]
fn pass_copy_never_prints_the_secret() {
    let (dir, _) = workspace();
    add_staging(dir.path());
    save_access(dir.path());
    turnout_secrets(dir.path())
        .args(["pass", "copy", "staging"])
        .assert()
        .success()
        .stdout(predicate::str::contains("copied to the clipboard").and(predicate::str::contains("s3cret").not()));
}

#[test]
fn use_binds_app_and_shows_in_status() {
    let (dir, project) = workspace();
    add_staging(dir.path());
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["use", "myapp", "staging", "--no-check"])
        .assert()
        .success()
        .stdout(predicate::str::contains("'myapp' now uses 'staging'"));
    turnout(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("myapp -> staging"));
}

#[test]
fn use_respects_the_allow_list() {
    let (dir, project) = workspace();
    add_staging(dir.path());
    turnout(dir.path())
        .args(["server", "add", "other", "--url", "https://other.example.com"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--server", "staging"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["use", "myapp", "other", "--no-check"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("not allowed"));
}

fn free_port() -> u16 {
    std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}

fn wait_for_port(port: u16) {
    let address = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    for _ in 0..100 {
        if std::net::TcpStream::connect_timeout(&address, std::time::Duration::from_millis(100)).is_ok() {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    panic!("port {port} never came up");
}

/// Kills the gateway child even when an assertion panics.
struct ChildGuard(std::process::Child);
impl Drop for ChildGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
    }
}

/// A tiny "stand": sets a session cookie, echoes cookies back, redirects to itself.
fn spawn_stand(port: u16) {
    std::thread::spawn(move || {
        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
        runtime.block_on(async move {
            use axum::http::HeaderMap;
            use axum::routing::get;
            let base = format!("http://127.0.0.1:{port}");
            let app = axum::Router::new()
                .route(
                    "/hello",
                    get(|| async { ([("set-cookie", "sid=abc123; Path=/; HttpOnly")], "hello from the stand") }),
                )
                .route(
                    "/echo-cookie",
                    get(|headers: HeaderMap| async move { headers.get("cookie").and_then(|v| v.to_str().ok()).unwrap_or("none").to_string() }),
                )
                .route(
                    "/login",
                    get(move || async move { (axum::http::StatusCode::FOUND, [("location", format!("{base}/after"))]) }),
                )
                .route(
                    "/ws",
                    get(|ws: axum::extract::ws::WebSocketUpgrade| async move {
                        ws.on_upgrade(|mut socket| async move {
                            while let Some(Ok(message)) = socket.recv().await {
                                if let axum::extract::ws::Message::Text(text) = message {
                                    let reply = axum::extract::ws::Message::Text(format!("echo: {text}").into());
                                    if socket.send(reply).await.is_err() {
                                        break;
                                    }
                                }
                            }
                        })
                    }),
                );
            let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
            axum::serve(listener, app).await.unwrap();
        });
    });
    wait_for_port(port);
}

#[test]
fn gateway_proxies_with_cookie_jar_and_location_rewrite() {
    let (dir, project) = workspace();
    let stand_port = free_port();
    let gateway_port = free_port();
    spawn_stand(stand_port);

    turnout(dir.path())
        .args(["server", "add", "stand", "--url", &format!("http://127.0.0.1:{stand_port}")])
        .assert()
        .success();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--port", &gateway_port.to_string()])
        .assert()
        .success();
    turnout(dir.path()).args(["use", "myapp", "stand", "--no-check"]).assert().success();

    let child = std::process::Command::new(assert_cmd::cargo::cargo_bin("turnout"))
        .env("TURNOUT_DATA_DIR", dir.path())
        .args(["gateway", "run"])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .unwrap();
    let _guard = ChildGuard(child);
    wait_for_port(gateway_port);

    let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
    runtime.block_on(async move {
        let client = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()).build().unwrap();
        let base = format!("http://127.0.0.1:{gateway_port}");

        // Pass-through works and the stand's cookie never reaches the browser.
        let response = client.get(format!("{base}/hello")).send().await.unwrap();
        assert_eq!(response.status(), 200);
        assert!(response.headers().get("set-cookie").is_none(), "set-cookie must be stripped");
        assert_eq!(response.text().await.unwrap(), "hello from the stand");

        // The jar sends the captured cookie back to the stand.
        let response = client.get(format!("{base}/echo-cookie")).send().await.unwrap();
        assert_eq!(response.text().await.unwrap(), "sid=abc123");

        // Absolute redirects to the stand come back rewritten to localhost.
        let response = client.get(format!("{base}/login")).send().await.unwrap();
        assert_eq!(response.status(), 302);
        let location = response.headers().get("location").unwrap().to_str().unwrap();
        assert_eq!(location, &format!("http://localhost:{gateway_port}/after"));

        // WebSocket frames travel through the gateway both ways.
        use futures_util::{SinkExt, StreamExt};
        let (mut socket, _) = tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{gateway_port}/ws")).await.unwrap();
        socket.send(tokio_tungstenite::tungstenite::Message::text("ping")).await.unwrap();
        let reply = socket.next().await.unwrap().unwrap();
        assert_eq!(reply.to_text().unwrap(), "echo: ping");
    });
}

#[test]
fn run_executes_app_commands_with_exit_codes() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--command", "hello=echo hi from turnout", "--command", "fail=exit 3"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["run", "hello", "myapp"])
        .assert()
        .success()
        .stdout(predicate::str::contains("hi from turnout"));
    turnout(dir.path()).args(["run", "fail", "myapp"]).assert().code(3);
    turnout(dir.path())
        .args(["run", "nosuch", "myapp"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("has no 'nosuch' command"));
}

#[test]
fn run_resolves_app_from_current_directory() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["app", "add", "myapp", "--path"])
        .arg(&project)
        .args(["--command", "hello=echo resolved by cwd"])
        .assert()
        .success();
    let nested = project.join("src");
    std::fs::create_dir(&nested).unwrap();
    turnout(dir.path())
        .current_dir(&nested)
        .args(["run", "hello"])
        .assert()
        .success()
        .stdout(predicate::str::contains("resolved by cwd"));
    turnout(dir.path())
        .current_dir(dir.path())
        .args(["run", "hello"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("not inside a known app directory"));
}

#[test]
fn server_edit_sets_deploy_targets() {
    let (dir, project) = workspace();
    add_staging(dir.path());
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args([
            "server",
            "edit",
            "staging",
            "--deploy-path",
            "myapp=/var/www/myapp",
            "--restart-cmd",
            "myapp=systemctl restart myapp",
        ])
        .assert()
        .success();
    turnout(dir.path())
        .args(["server", "show", "staging"])
        .assert()
        .success()
        .stdout(predicate::str::contains("/var/www/myapp").and(predicate::str::contains("systemctl restart myapp")));
    turnout(dir.path())
        .args(["server", "edit", "staging", "--restart-cmd", "ghost=oops"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("has no deploy path"));
}

#[test]
fn server_edit_manages_the_ssh_key() {
    let (dir, _) = workspace();
    add_staging(dir.path());
    turnout(dir.path())
        .args(["server", "edit", "staging", "--ssh-key", "/home/me/.ssh/id_ed25519"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("set SSH access first"));
    turnout(dir.path())
        .args([
            "server",
            "edit",
            "staging",
            "--ssh",
            "deploy@staging.example.com",
            "--ssh-key",
            "/home/me/.ssh/id_ed25519",
        ])
        .assert()
        .success();
    turnout(dir.path())
        .args(["server", "show", "staging"])
        .assert()
        .success()
        .stdout(predicate::str::contains("key: /home/me/.ssh/id_ed25519"));
    turnout(dir.path()).args(["server", "edit", "staging", "--ssh-key", ""]).assert().success();
    turnout(dir.path())
        .args(["server", "show", "staging"])
        .assert()
        .success()
        .stdout(predicate::str::contains("key:").not());
}

#[test]
fn backup_and_restore_validate_preconditions() {
    let (dir, project) = workspace();
    add_staging(dir.path());
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["backup", "myapp", "--server", "staging"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no SSH access"));
    turnout(dir.path())
        .args(["server", "edit", "staging", "--ssh", "deploy@staging.example.com"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["restore", "myapp", "--server", "staging", "--list"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no deploy path"));
}

#[test]
fn deploy_validates_its_preconditions() {
    let (dir, project) = workspace();
    add_staging(dir.path());
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["deploy", "myapp", "--no-build"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("pass --server or bind"));
    turnout(dir.path())
        .args(["deploy", "myapp", "--server", "staging", "--no-build"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no SSH access"));
    turnout(dir.path())
        .args(["server", "edit", "staging", "--ssh", "deploy@staging.example.com"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["deploy", "myapp", "--server", "staging", "--no-build"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no deploy path"));
    turnout(dir.path())
        .args(["server", "edit", "staging", "--deploy-path", "myapp=/var/www/myapp"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["deploy", "myapp", "--server", "staging", "--no-build"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("no artifact directory"));
}

#[test]
fn group_use_binds_all_members() {
    let (dir, project) = workspace();
    add_staging(dir.path());
    let second = dir.path().join("second");
    std::fs::create_dir(&second).unwrap();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(dir.path()).args(["app", "add", "api", "--path"]).arg(&second).assert().success();
    turnout(dir.path())
        .args(["group", "add", "contour", "--app", "web", "--app", "api"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["use", "contour", "staging", "--no-check"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Group 'contour' now uses 'staging'"));
    turnout(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("web -> staging").and(predicate::str::contains("api -> staging")));
    turnout(dir.path())
        .args(["group", "show", "contour"])
        .assert()
        .success()
        .stdout(predicate::str::contains("web -> staging"));
}

#[test]
fn group_names_cannot_clash_with_apps() {
    let (dir, project) = workspace();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["group", "add", "web", "--app", "web"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("must not clash"));
}

#[test]
fn removing_an_app_updates_groups() {
    let (dir, project) = workspace();
    let second = dir.path().join("second");
    std::fs::create_dir(&second).unwrap();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(dir.path()).args(["app", "add", "api", "--path"]).arg(&second).assert().success();
    turnout(dir.path())
        .args(["group", "add", "contour", "--app", "web", "--app", "api"])
        .assert()
        .success();
    turnout(dir.path())
        .args(["app", "remove", "web", "--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Removed 'web' from groups: contour"));
    turnout(dir.path())
        .args(["group", "show", "contour"])
        .assert()
        .success()
        .stdout(predicate::str::contains("web").not());
}

/// The completion helper feeds live names to the shell; `use` accepts apps and
/// groups together, so `targets` must carry both.
#[test]
fn complete_lists_live_entity_names() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(dir.path()).args(["group", "add", "contour", "--app", "web"]).assert().success();

    turnout(dir.path()).args(["complete", "apps"]).assert().success().stdout("web\n");
    turnout(dir.path()).args(["complete", "servers"]).assert().success().stdout("staging\n");
    turnout(dir.path())
        .args(["complete", "targets"])
        .assert()
        .success()
        .stdout(predicate::str::contains("web").and(predicate::str::contains("contour")));
}

/// bash gets the dynamic wrapper appended; other shells stay untouched.
#[test]
fn bash_completions_carry_the_dynamic_wrapper() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["completions", "bash"]).assert().success().stdout(
        predicate::str::contains("_turnout_dynamic").and(predicate::str::contains("-F _turnout_dynamic -o nosort -o bashdefault -o default turnout tn")),
    );
    turnout(dir.path())
        .args(["completions", "zsh"])
        .assert()
        .success()
        .stdout(predicate::str::contains("_turnout_dynamic").not());
}

#[test]
fn completions_cover_the_command_surface() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path())
        .args(["completions", "powershell"])
        .assert()
        .success()
        .stdout(predicate::str::contains("turnout").and(predicate::str::contains("deploy")));
}

/// Pickers only stand in on a terminal; piped runs must keep failing loudly
/// rather than blocking on a prompt nobody can answer.
#[test]
fn missing_names_still_fail_without_a_terminal() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();

    for args in [
        vec!["app", "show"],
        vec!["server", "show"],
        vec!["use"],
        vec!["use", "myapp"],
        vec!["pass", "copy"],
    ] {
        turnout(dir.path())
            .args(&args)
            .assert()
            .failure()
            .stderr(predicate::str::contains("no terminal to prompt on").or(predicate::str::contains("no access saved")));
    }
}

/// Confirmations are prompts too: unattended they must name `--yes` rather than
/// failing with dialoguer's bare "not a terminal", and must remove nothing.
#[test]
fn destructive_commands_explain_how_to_skip_the_prompt() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path()).args(["group", "add", "contour", "--app", "myapp"]).assert().success();

    for args in [
        vec!["app", "remove", "myapp"],
        vec!["server", "remove", "staging"],
        vec!["group", "remove", "contour"],
    ] {
        turnout(dir.path())
            .args(&args)
            .assert()
            .failure()
            .stderr(predicate::str::contains("--yes").and(predicate::str::contains("no terminal to prompt on")));
    }

    // Nothing was confirmed, so nothing may have been removed.
    turnout(dir.path())
        .args(["app", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("myapp"));
    turnout(dir.path())
        .args(["server", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("staging"));
    turnout(dir.path())
        .args(["group", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("contour"));
}

/// A scripted `pass set` reads the secret from stdin; an empty pipe is a
/// forgotten value, not an intentionally empty secret.
#[test]
fn pass_set_says_when_no_secret_arrived_on_stdin() {
    let (dir, _project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();

    turnout(dir.path())
        .args(["pass", "set", "staging", "--kind", "ssh", "--login", "deploy"])
        .write_stdin("")
        .assert()
        .failure()
        .stderr(predicate::str::contains("no secret on stdin"));
}

/// The deploy wizard is interactive by nature; scripts must be told what to
/// use instead rather than hanging on a prompt.
#[test]
fn deploy_setup_refuses_to_run_unattended() {
    let (dir, project) = workspace();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .args(["deploy-setup", "web"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("is a wizard").and(predicate::str::contains("turnout server edit")));
}

/// Every state change lands in the journal, and `status` shows the tail.
/// Secrets never do - `pass` is not journaled at all.
#[test]
fn actions_are_journaled_without_secrets() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(dir.path()).args(["use", "web", "staging", "--no-check"]).assert().success();
    turnout(dir.path())
        .args(["pass", "set", "staging", "--login", "deploy"])
        .env("TURNOUT_KEYRING", "insecure-file")
        .write_stdin("hunter2-topsecret")
        .assert()
        .success();

    let journal = std::fs::read_to_string(dir.path().join("journal.jsonl")).unwrap();
    assert!(journal.contains(r#""action":"use""#), "{journal}");
    assert!(journal.contains(r#""action":"app.add""#), "{journal}");
    assert!(!journal.contains("hunter2"), "the secret leaked: {journal}");
    assert!(!journal.contains("deploy"), "the login leaked: {journal}");

    turnout(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("Recent:").and(predicate::str::contains("web -> staging")));
}

#[test]
fn status_counts_catalogs() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(dir.path()).args(["app", "add", "myapp", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("Apps:    1 (myapp)").and(predicate::str::contains("Servers: 1 (staging)")));
}

/// The update check is off under `CI`, which is exactly where these tests run,
/// so they switch it back on explicitly - otherwise they would pass by
/// checking nothing.
fn with_update_check(data_dir: &std::path::Path) -> Command {
    let mut cmd = turnout(data_dir);
    cmd.env("TURNOUT_UPDATE_CHECK", "1").env_remove("CI");
    cmd
}

/// The hidden helper the background process runs. Pointing it at an
/// unreachable host proves the failure path: the attempt is recorded so the
/// next command does not retry immediately, and no version is invented.
///
/// `setup` runs with the check disabled on purpose. Enabled, it would spawn a
/// background lookup against the real GitHub, and that answer - not the failure
/// under test - is what would land in the cache.
#[test]
fn a_failed_update_lookup_is_recorded_without_a_version() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    with_update_check(dir.path())
        .env("TURNOUT_UPDATE_URL", "http://update-check.invalid/releases/latest")
        .arg("check-update")
        .assert()
        .success();

    let cache = std::fs::read_to_string(dir.path().join("update-check.json")).unwrap();
    assert!(cache.contains("checked_at"), "{cache}");
    assert!(!cache.contains("latest"), "an unreachable host must not yield a version: {cache}");
}

/// A newer version in the cache must never reach piped output: scripts read
/// stdout, and a version notice in the middle of it is noise.
#[test]
fn the_update_notice_stays_out_of_piped_output() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    let cache = format!(r#"{{"checked_at":{},"latest":"99.0.0"}}"#, u64::MAX / 2);
    std::fs::write(dir.path().join("update-check.json"), cache).unwrap();

    with_update_check(dir.path())
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("99.0.0").not())
        .stderr(predicate::str::contains("99.0.0").not());
}

/// Turning the check off means nothing is looked up at all - no cache file
/// appears, so no background process went out to the network.
#[test]
fn the_update_check_can_be_switched_off() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    turnout(dir.path())
        .env("TURNOUT_UPDATE_CHECK", "off")
        .env_remove("CI")
        .arg("status")
        .assert()
        .success();
    // The spawn is fire-and-forget; give a stray one time to land.
    std::thread::sleep(std::time::Duration::from_millis(500));
    assert!(
        !dir.path().join("update-check.json").exists(),
        "a disabled check must not reach the network or write a cache"
    );
}

/// A command must not fail because the update check did.
#[test]
fn a_broken_update_check_never_fails_the_command() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    with_update_check(dir.path())
        .env("TURNOUT_UPDATE_URL", "http://update-check.invalid/releases/latest")
        .arg("status")
        .assert()
        .success()
        .stdout(predicate::str::contains("Gateway: not running"));
}

/// A binary left over from a previous `self-update` is swept by any later
/// command - not only by `self-update` itself, which nobody runs twice in a
/// row. Until it is swept it costs a full binary worth of disk.
#[test]
fn a_leftover_binary_from_self_update_is_swept() {
    let dir = tempfile::tempdir().unwrap();
    let exe = dir.path().join(if cfg!(windows) { "turnout.exe" } else { "turnout" });
    std::fs::copy(assert_cmd::cargo::cargo_bin("turnout"), &exe).unwrap();

    let mut leftover = exe.clone().into_os_string();
    leftover.push(".old");
    let leftover = std::path::PathBuf::from(leftover);
    std::fs::write(&leftover, b"the previous binary").unwrap();

    // A plain command, unrelated to updating. Not `--version`: clap answers
    // that one itself and exits before any of our code runs.
    let mut cmd = Command::new(&exe);
    cmd.env("TURNOUT_DATA_DIR", dir.path()).env("TURNOUT_UPDATE_CHECK", "0");
    cmd.arg("status").assert().success();

    assert!(!leftover.exists(), "the leftover binary should have been removed");
    assert!(exe.exists(), "the running binary must survive the sweep");
}

/// A round trip through a file is the whole point of export/import: what comes
/// out on the other machine has to be what went in.
#[test]
fn a_setup_survives_export_and_import() {
    let (source, project) = workspace();
    turnout(source.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(source.path())
        .args(["app", "add", "web", "--path"])
        .arg(&project)
        .args(["--port", "7100"])
        .assert()
        .success();

    let file = source.path().join("export.json");
    turnout(source.path()).args(["export", "--output"]).arg(&file).assert().success();

    let target = tempfile::tempdir().unwrap();
    turnout(target.path()).args(["setup", "--yes"]).assert().success();
    turnout(target.path()).arg("import").arg(&file).assert().success();
    turnout(target.path())
        .args(["app", "show", "web"])
        .assert()
        .success()
        .stdout(predicate::str::contains("localhost:7100"));
    turnout(target.path())
        .args(["server", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("staging"));
}

/// Without `--with-secrets` the file must be safe to hand around: it carries
/// the access record but not the value behind it.
#[test]
fn a_plain_export_carries_no_secret_values() {
    let (dir, project) = workspace();
    turnout(dir.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(dir.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .args(["pass", "set", "staging", "--kind", "password", "--login", "deploy"])
        .write_stdin("hunter2")
        .assert()
        .success();

    let file = dir.path().join("export.json");
    turnout(dir.path()).args(["export", "--output"]).arg(&file).assert().success();

    let text = std::fs::read_to_string(&file).unwrap();
    assert!(!text.contains("hunter2"), "the secret leaked into a plain export: {text}");
    assert!(text.contains("\"login\": \"deploy\""), "the access record should still travel: {text}");
}

/// Secrets travel only under a passphrase, and arrive usable on the far side.
#[test]
fn secrets_travel_encrypted_and_arrive_usable() {
    let (source, project) = workspace();
    turnout(source.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(source.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(source.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .args(["pass", "set", "staging", "--kind", "password", "--login", "deploy"])
        .write_stdin("hunter2")
        .assert()
        .success();

    let file = source.path().join("export.json");
    turnout(source.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .args(["export", "--with-secrets", "--output"])
        .arg(&file)
        .write_stdin("lab passphrase")
        .assert()
        .success();
    let text = std::fs::read_to_string(&file).unwrap();
    assert!(!text.contains("hunter2"), "the secret must be encrypted: {text}");

    let target = tempfile::tempdir().unwrap();
    turnout(target.path()).args(["setup", "--yes"]).assert().success();
    turnout(target.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .arg("import")
        .arg(&file)
        .write_stdin("lab passphrase")
        .assert()
        .success();
    turnout(target.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .args(["pass", "copy", "staging", "--kind", "password", "--show"])
        .assert()
        .success()
        .stdout(predicate::str::contains("hunter2"));
}

/// A wrong passphrase must leave the machine untouched. Writing the catalogs
/// first and failing on the secrets would hand back half a setup - and the
/// retry would then hit "already exists" on everything.
#[test]
fn a_wrong_passphrase_imports_nothing_at_all() {
    let (source, project) = workspace();
    turnout(source.path())
        .args(["server", "add", "staging", "--url", "https://staging.example.com"])
        .assert()
        .success();
    turnout(source.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();
    turnout(source.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .args(["pass", "set", "staging", "--kind", "password", "--login", "deploy"])
        .write_stdin("hunter2")
        .assert()
        .success();
    let file = source.path().join("export.json");
    turnout(source.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .args(["export", "--with-secrets", "--output"])
        .arg(&file)
        .write_stdin("right passphrase")
        .assert()
        .success();

    let target = tempfile::tempdir().unwrap();
    turnout(target.path()).args(["setup", "--yes"]).assert().success();
    turnout(target.path())
        .env("TURNOUT_KEYRING", "insecure-file")
        .arg("import")
        .arg(&file)
        .write_stdin("wrong passphrase")
        .assert()
        .failure()
        .stderr(predicate::str::contains("wrong passphrase"));

    turnout(target.path())
        .args(["app", "list"])
        .assert()
        .success()
        .stdout(predicate::str::contains("No apps yet"));
}

/// The local setup wins unless `--force` says otherwise.
#[test]
fn import_keeps_local_entries_unless_forced() {
    let (source, project) = workspace();
    turnout(source.path())
        .args(["app", "add", "web", "--path"])
        .arg(&project)
        .args(["--port", "7100"])
        .assert()
        .success();
    let file = source.path().join("export.json");
    turnout(source.path()).args(["export", "--output"]).arg(&file).assert().success();

    let (target, other) = workspace();
    turnout(target.path())
        .args(["app", "add", "web", "--path"])
        .arg(&other)
        .args(["--port", "9999"])
        .assert()
        .success();

    turnout(target.path())
        .arg("import")
        .arg(&file)
        .assert()
        .success()
        .stdout(predicate::str::contains("Skipped").and(predicate::str::contains("--force")));
    turnout(target.path())
        .args(["app", "show", "web"])
        .assert()
        .success()
        .stdout(predicate::str::contains("localhost:9999"));

    turnout(target.path()).arg("import").arg(&file).arg("--force").assert().success();
    turnout(target.path())
        .args(["app", "show", "web"])
        .assert()
        .success()
        .stdout(predicate::str::contains("localhost:7100"));
}

/// Data written by a newer turnout must stop the command with an explanation,
/// not with a parse error from somewhere deep in a catalog. The files may well
/// still parse and mean something different, which is the dangerous case.
#[test]
fn a_newer_data_directory_is_refused_with_a_way_out() {
    let dir = tempfile::tempdir().unwrap();
    turnout(dir.path()).args(["setup", "--yes"]).assert().success();
    std::fs::write(dir.path().join("meta.json"), r#"{"schema_version": 99}"#).unwrap();

    turnout(dir.path())
        .args(["app", "list"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("newer turnout").and(predicate::str::contains("self-update")));

    // Nothing may be rewritten on the way out.
    let meta = std::fs::read_to_string(dir.path().join("meta.json")).unwrap();
    assert!(meta.contains("99"), "the marker must be left alone: {meta}");
}

/// The version marker is read on every command, so a current directory has to
/// stay silent and untouched - a migration notice on every run would be noise.
#[test]
fn a_current_data_directory_migrates_nothing() {
    let (dir, project) = workspace();
    turnout(dir.path()).args(["app", "add", "web", "--path"]).arg(&project).assert().success();

    turnout(dir.path())
        .args(["app", "list"])
        .assert()
        .success()
        .stderr(predicate::str::contains("Migrating").not());

    let backups: Vec<_> = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_name().to_string_lossy().starts_with("settings-backup"))
        .collect();
    assert!(backups.is_empty(), "no backup folder should appear for a no-op");
}