ignition-cli 1.5.0

ign — operate Ignition 8.3+ gateways from the terminal
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
//! Golden-file contract tests for the `ign rig` family's docker-less
//! error paths (04-01, RIG-01): the no-rig discovery failure (exit 7
//! with the full search trail), the unknown-name refusal (knowns
//! listed — the ProfileNotFound shape precedent), the discovery
//! precedence pin, and the help surface. Harness inherited from
//! `contract_restart_wait.rs`: isolated `IGNITION_CLI_CONFIG` per
//! spawn, stderr-envelope parse from the first `{`, `[..]` elides only
//! genuinely dynamic values (temp paths).
//!
//! ## Machine isolation (the plan-checker's lesson, made structural)
//!
//! Discovery's WHK-convention levels probe the REAL home roots — on a
//! developer machine those repos exist, so every test exports
//! `IGNITION_RIG_ROOTS` pointing at an empty temp dir (the documented
//! override) to make "nothing found" deterministic everywhere.
//!
//! ## The docker-present guard
//!
//! The precedence test pins the error the RESOLVE run produces when
//! the docker CLI is absent (CI); a machine WITH docker would run the
//! resolve for real and change the outcome — so the test skips when
//! `docker compose version` answers OR when
//! `IGNITION_SKIP_RIG_DOCKER_TESTS` forces the skip (documented).

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

use assert_cmd::Command;
use serde_json::Value;

/// Isolated config dir + the config path inside it (file need not exist).
fn isolated_config() -> (tempfile::TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    (dir, path)
}

/// An EMPTY temp dir for `IGNITION_RIG_ROOTS` — convention-level
/// probing then finds nothing, everywhere.
fn isolated_roots() -> (tempfile::TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().to_path_buf();
    (dir, path)
}

/// Spawn `ign rig …` with an isolated config, isolated convention
/// roots, no rig env, and an isolated cwd — every test needs all four
/// (the crate root itself has no compose file, but the convention
/// levels make no-`--rig` paths machine-dependent without the roots
/// override).
fn ign_rig(config: &Path, roots: &Path, cwd: &Path, args: &[&str]) -> std::process::Output {
    let mut command = Command::cargo_bin("ign").expect("binary 'ign' not found");
    command
        .env("IGNITION_CLI_CONFIG", config)
        .env("IGNITION_RIG_ROOTS", roots)
        .env_remove("IGNITION_RIG")
        .env_remove("IGNITION_TOKEN")
        .current_dir(cwd);
    command.args(args).output().expect("spawn ign")
}

/// stderr's JSON envelope starting at the first `{` (log-tolerant parse).
fn stderr_envelope(out: &std::process::Output) -> String {
    let stderr = String::from_utf8_lossy(&out.stderr);
    let start = stderr.find('{').unwrap_or(0);
    stderr[start..].to_string()
}

/// True when the docker CLI answers `compose version` — the
/// docker-present machines that must skip the resolve-failure golden.
fn docker_compose_available() -> bool {
    std::process::Command::new("docker")
        .args(["compose", "version"])
        .output()
        .map(|output| output.status.success())
        .unwrap_or(false)
}

/// THE no-rig pin: empty cwd, no config rigs, isolated convention
/// roots → exit 7 (`rig_error`), `profile: null`, and the message
/// carries the full search trail (cwd candidates + roots) so agents
/// self-diagnose. No docker is ever spawned — discovery fails before
/// the resolve run.
#[test]
fn missing_rig_exits_7_with_search_trail() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "status", "--compact"]);
    assert_eq!(out.status.code(), Some(7), "rig class");
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "docker-only: profile null");
    assert_eq!(
        body["error"]["code"],
        Value::String("rig_error".into()),
        "stable slug"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("no compose file discovered"),
        "the diagnosis leads: {message}"
    );
    assert!(
        message.contains("docker/compose.yml") && message.contains("docker-compose.yml"),
        "cwd candidates named in the trail: {message}"
    );
    // The hint stays the class-wide docker hint.
    assert!(
        body["error"]["hint"]
            .as_str()
            .unwrap_or("")
            .contains("docker ps")
    );
}

/// `--rig unknown-name`: exit 7 listing the known rigs (the
/// ProfileNotFound shape precedent — BTreeMap order). No docker is
/// spawned (the lookup fails before resolve). The message is pinned
/// EXACTLY via the parsed envelope (snapbox's inline goldens
/// normalize embedded quotes in string values — the PK//x03//x04
/// gotcha's sibling).
#[test]
fn unknown_rig_name_lists_knowns_golden() {
    let (_config_dir, config) = isolated_config();
    std::fs::write(
        &config,
        "[rigs.known-rig]\ncompose_file = \"/tmp/known-rig-compose.yml\"\n",
    )
    .expect("write config");
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &["rig", "--rig", "nope", "status", "--compact"],
    );
    assert_eq!(out.status.code(), Some(7));
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "docker-only: profile null");
    assert_eq!(body["error"]["code"], Value::String("rig_error".into()));
    assert_eq!(
        body["error"]["message"],
        Value::String(
            "rig error: rig \"nope\" not found (known rigs: [\"known-rig\"]); add a \
             [rigs.nope] entry or run from the rig's directory"
                .into()
        ),
        "the exact refusal message — knowns listed, actionable fix named"
    );
    assert_eq!(
        body["error"]["endpoint"],
        Value::Null,
        "discovery refusals carry no endpoint"
    );
}

/// The discovery precedence pin (must-have truth #4): `[rig].default`
/// BEATS a cwd full of compose candidates. The assertion rides the
/// resolve run's deterministic failure on docker-less machines — the
/// spawned command names the file it tried, so the golden proves the
/// DEFAULT's compose file (not the cwd's) was chosen. Machines WITH
/// docker skip (auto-probe + `IGNITION_SKIP_RIG_DOCKER_TESTS`): there
/// the resolve runs for real and the outcome is machine-dependent.
#[test]
fn discovery_precedence_config_default_beats_cwd() {
    if std::env::var("IGNITION_SKIP_RIG_DOCKER_TESTS").is_ok() || docker_compose_available() {
        eprintln!("skipping: docker present (or skip forced) — resolve would run for real");
        return;
    }

    let (_config_dir, config) = isolated_config();
    let rig_dir = tempfile::tempdir().expect("rig tempdir");
    let remote_compose = rig_dir.path().join("remote-compose.yml");
    std::fs::write(
        &remote_compose,
        "services:\n  sidecar:\n    image: alpine:latest\n",
    )
    .expect("write remote compose");

    std::fs::write(
        &config,
        format!(
            "[rig]\ndefault = \"remote\"\n\n[rigs.remote]\ncompose_file = '{}'\n",
            remote_compose.display()
        ),
    )
    .expect("write config");

    // The cwd ALSO has a compose file — the default must win.
    let cwd = tempfile::tempdir().expect("cwd tempdir");
    std::fs::write(
        cwd.path().join("compose.yml"),
        "services:\n  other:\n    image: alpine:latest\n",
    )
    .expect("write cwd compose");

    let (_roots_dir, roots) = isolated_roots();
    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "status", "--compact"]);
    assert_eq!(out.status.code(), Some(7), "no docker: resolve fails");

    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["profile"], Value::Null);
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("remote-compose.yml"),
        "the DEFAULT rig's file was the one resolved: {message}"
    );
    let cwd_compose = cwd.path().join("compose.yml").display().to_string();
    assert!(
        !message.contains(&cwd_compose),
        "the cwd candidate lost the precedence race: {message}"
    );
    // Belt: the message names the spawn failure (docker absent).
    assert!(
        message.contains("failed to spawn") || message.contains("docker"),
        "{message}"
    );
}

/// The `--help` surface: the rig subtree is visible with all five
/// verbs and the `--rig` flag (contains-assertions, not a golden —
/// clap's help rendering churns across versions by design).
#[test]
fn rig_help_shows_the_subtree() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "--help"]);
    assert!(out.status.success(), "help exits 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    for expected in ["--rig <NAME>", "up", "down", "reset", "status", "logs"] {
        assert!(
            stdout.contains(expected),
            "help mentions {expected}: {stdout}"
        );
    }

    // Bare `ign rig` (no verb) is the friendly usage error, exit 2.
    let out = ign_rig(&config, &roots, cwd.path(), &["rig"]);
    assert_eq!(out.status.code(), Some(2));
}

/// THE destructive-guard pin (04-02): `rig reset` without `--yes`
/// refuses with exit 2 (`confirmation_required`), profile null, and
/// the hint naming BOTH `--yes` and `IGNITION_YES=1` — and the ZERO
/// WORK proof rides the environment: the cwd has NO compose file and
/// the convention roots are empty, so if the guard did not fire
/// BEFORE discovery the command would exit 7 (`no compose file
/// discovered`). Exit 2 here pins the guard-before-resolution
/// ordering at the binary level (the sessions-terminate precedent,
/// docker-only edition).
#[test]
fn rig_reset_refuses_without_yes_before_any_discovery() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "reset", "--compact"]);
    assert_eq!(
        out.status.code(),
        Some(2),
        "guard exit 2 — NOT the exit 7 a discovery run would produce"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "docker-only: profile null");
    assert_eq!(
        body["error"]["code"],
        Value::String("confirmation_required".into()),
        "stable slug"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("rig reset"),
        "names the operation: {message}"
    );
    let hint = body["error"]["hint"].as_str().expect("hint required");
    assert!(
        hint.contains("--yes") && hint.contains("IGNITION_YES"),
        "hint names the flag and the env escape hatch: {hint}"
    );
}

/// The other half of the guard story: WITH `--yes` (guard passed) the
/// same no-rig environment fails CLEANLY at discovery — exit 7
/// `rig_error` with the search trail. The guard pass-through is
/// proven by the error class changing from 2 to 7.
#[test]
fn rig_reset_with_yes_in_no_rig_cwd_fails_cleanly_at_discovery() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &["rig", "reset", "--yes", "--compact"],
    );
    assert_eq!(
        out.status.code(),
        Some(7),
        "guard passed: discovery failure"
    );
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["profile"], Value::Null);
    assert_eq!(body["error"]["code"], Value::String("rig_error".into()));
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("no compose file discovered"),
        "the discovery diagnosis leads: {message}"
    );
}

/// The `rig logs` flag surface: --tail, -f/--follow, and the SERVICE
/// positional are all visible in help (contains-assertions — clap's
/// help rendering churns across versions by design).
#[test]
fn rig_logs_help_shows_tail_follow_service() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "logs", "--help"]);
    assert!(out.status.success(), "help exits 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("--tail"), "tail visible: {stdout}");
    assert!(stdout.contains("--follow"), "follow visible: {stdout}");
    assert!(stdout.contains("-f"), "the -f short form visible: {stdout}");
    assert!(
        stdout.contains("[SERVICE]"),
        "the SERVICE positional visible: {stdout}"
    );
}

/// `IGNITION_RIG` fills a missing `--rig` (the env→flag fold in
/// apply_env_defaults — the IGNITION_PROFILE precedent): with the env
/// set to an unknown name the named-lookup error fires, proving the
/// env reached the selection. No docker spawned.
#[test]
fn ignition_rig_env_folds_into_selection() {
    let (_config_dir, config) = isolated_config();
    std::fs::write(
        &config,
        "[rigs.known-rig]\ncompose_file = \"/tmp/known-rig-compose.yml\"\n",
    )
    .expect("write config");
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let mut command = Command::cargo_bin("ign").expect("binary 'ign' not found");
    command
        .env("IGNITION_CLI_CONFIG", &config)
        .env("IGNITION_RIG_ROOTS", &roots)
        .env("IGNITION_RIG", "env-named-rig")
        .current_dir(cwd.path())
        .args(["rig", "status", "--compact"]);
    let out = command.output().expect("spawn ign");
    assert_eq!(out.status.code(), Some(7));
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("env-named-rig") && message.contains("known rigs"),
        "the env-provided name drove the lookup: {message}"
    );
}

/// THE destructive-guard pin (04-03): `rig trial reset` without
/// `--yes` refuses with exit 2 (`confirmation_required`), profile
/// null — and the ZERO WORK proof rides the same no-rig environment
/// as `rig reset` (the cwd has NO compose file; un-guarded execution
/// would exit 7 at discovery). The guard-before-resolution ordering,
/// fourth destructive-verb instance.
#[test]
fn rig_trial_reset_refuses_without_yes_before_any_discovery() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &["rig", "trial", "reset", "--compact"],
    );
    assert_eq!(
        out.status.code(),
        Some(2),
        "guard exit 2 — NOT the exit 7 a discovery run would produce"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "refusal: profile null");
    assert_eq!(
        body["error"]["code"],
        Value::String("confirmation_required".into()),
        "stable slug"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("rig trial reset"),
        "names the operation: {message}"
    );
}

/// THE destructive-guard pin for `rig module uninstall` (Phase 19,
/// SC-2, D-19-02): no `--yes` refuses exit 2 (`confirmation_required`),
/// profile null — the ZERO WORK proof rides the same no-rig environment
/// as `rig reset` (the cwd has NO compose file; un-guarded execution
/// would exit 7 at discovery). Sixth destructive-verb instance
/// (sessions terminate -> project delete -> rig reset -> rig trial
/// reset -> rig restore -> rig module uninstall).
#[test]
fn rig_module_uninstall_refuses_without_yes_before_any_discovery() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &["rig", "module", "uninstall", "git", "--compact"],
    );
    assert_eq!(
        out.status.code(),
        Some(2),
        "guard exit 2 — NOT the exit 7 a discovery run would produce"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "docker-only: profile null");
    assert_eq!(
        body["error"]["code"],
        Value::String("confirmation_required".into()),
        "stable slug"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("rig module uninstall"),
        "names the operation: {message}"
    );
    let hint = body["error"]["hint"].as_str().expect("hint required");
    assert!(
        hint.contains("--yes") && hint.contains("IGNITION_YES"),
        "hint names the flag and the env escape hatch: {hint}"
    );
}

/// The unregistered-id refusal for `rig module uninstall` (Phase 19,
/// D-19-05, SC-4's CLI-surface half): exit 3, `module_not_registered`,
/// the message lists the known registry ids. Proven to fire BEFORE any
/// credential is sourced by the environment itself: `IGNITION_TOKEN` is
/// unset (`ign_rig`'s default `env_remove`), so if this check ran AFTER
/// the token step the run would instead surface `secret_unavailable` —
/// the distinct slug IS the ordering proof (the same technique as the
/// `--yes`-guard goldens' exit-code distinction). Requires docker:
/// `resolve_plan` parses the fixture's compose file via `docker compose
/// config` before the `Module` arm is ever reached — skips when docker
/// is unavailable (this file's established convention), never runs a
/// container.
#[test]
fn module_uninstall_unregistered_id_is_exit_3_before_credential_step() {
    if std::env::var("IGNITION_SKIP_RIG_DOCKER_TESTS").is_ok() || !docker_compose_available() {
        eprintln!(
            "skipping: docker unavailable (or skip forced) — resolve_plan needs \
             `docker compose config`"
        );
        return;
    }

    let (_config_dir, config, _project_dir) = rig_config_with_real_compose_file();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "--rig",
            "fixture",
            "module",
            "uninstall",
            "not-a-real-module",
            "--yes",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(3),
        "unregistered id refuses at exit 3, never reaching the credential step"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(
        body["error"]["code"],
        Value::String("module_not_registered".into()),
        "stable slug — NOT secret_unavailable, which is what an out-of-order \
         check would produce with no IGNITION_TOKEN set"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("not-a-real-module"),
        "names the bad id: {message}"
    );
    assert!(message.contains("git"), "lists a known id: {message}");
}

/// The still-declared refusal for `rig module uninstall`: a registry id
/// the rig's own `[rigs.NAME.modules]` table still names refuses exit 7
/// (`rig_error`), naming the config table to edit and `ign rig up` —
/// never reaching the credential step (same ordering proof as the
/// unregistered-id golden above: `IGNITION_TOKEN` is unset, so an
/// out-of-order check would surface `secret_unavailable` instead).
/// Requires docker for the same reason as the unregistered-id golden.
#[test]
fn module_uninstall_still_declared_id_is_exit_7_before_credential_step() {
    if std::env::var("IGNITION_SKIP_RIG_DOCKER_TESTS").is_ok() || !docker_compose_available() {
        eprintln!(
            "skipping: docker unavailable (or skip forced) — resolve_plan needs \
             `docker compose config`"
        );
        return;
    }

    let project_dir = tempfile::tempdir().expect("project tempdir");
    let compose_file = project_dir.path().join("docker-compose.yml");
    std::fs::write(
        &compose_file,
        "services:\n  app:\n    image: alpine:latest\n",
    )
    .expect("write compose file");

    let (_config_dir, config) = isolated_config();
    std::fs::write(
        &config,
        format!(
            "[rigs.fixture]\ncompose_file = '{}'\nproject_name = \"fixture\"\n\n\
             [rigs.fixture.modules.git]\nversion = \"2.3.4\"\n",
            compose_file.display()
        ),
    )
    .expect("write config");
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "--rig",
            "fixture",
            "module",
            "uninstall",
            "git",
            "--yes",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(7),
        "still-declared id refuses at exit 7, never reaching the credential step"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(
        body["error"]["code"],
        Value::String("rig_error".into()),
        "stable slug — NOT secret_unavailable, which is what an out-of-order \
         check would produce with no IGNITION_TOKEN set"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(message.contains("git"), "names the module: {message}");
    assert!(message.contains("fixture"), "names the rig: {message}");
    assert!(
        message.contains("[rigs.fixture.modules.git]"),
        "names the config table to edit: {message}"
    );
    assert!(message.contains("ign rig up"), "names the fix: {message}");
}

/// The `rig trial` help surface: both verbs + `--user`; a PASSWORD
/// flag must NOT exist (env-only redaction discipline — pinned by
/// this absence in the same golden as the presence checks).
/// A status-path binary golden is NOT testable without a gateway —
/// the status contract lives at the unit/wiremock layer
/// (crates/ignition-core/tests/trial_contract.rs + actions tests).
#[test]
fn rig_trial_help_shows_verbs_and_no_password_flag() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "trial", "--help"]);
    assert!(out.status.success(), "help exits 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    for expected in ["status", "reset"] {
        assert!(
            stdout.contains(expected),
            "help mentions {expected}: {stdout}"
        );
    }

    // The reset verb's own help carries --user; a PASSWORD flag must
    // NOT exist anywhere (env-only redaction discipline — pinned by
    // this absence in the same golden as the presence checks).
    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &["rig", "trial", "reset", "--help"],
    );
    assert!(out.status.success(), "reset help exits 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("--user <NAME>"), "--user visible: {stdout}");
    assert!(
        !stdout.to_lowercase().contains("--password"),
        "password NEVER rides a flag: {stdout}"
    );

    // Bare `ign rig trial` (no verb) is the friendly usage error.
    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "trial"]);
    assert_eq!(out.status.code(), Some(2));
}

/// THE destructive-guard pin (04-04): `rig restore` without `--yes`
/// refuses with exit 2 (`confirmation_required`), profile null — the
/// ZERO WORK proof rides the same no-rig environment as `rig reset`
/// (the cwd has NO compose file; un-guarded execution would exit 7 at
/// discovery). Fifth destructive-verb instance (sessions terminate →
/// project delete → rig reset → rig trial reset → rig restore).
#[test]
fn rig_restore_refuses_without_yes_before_any_discovery() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "restore",
            "--file",
            "/nonexistent/snap.gwbk",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(2),
        "guard exit 2 — NOT the exit 7 a discovery run would produce"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "refusal: profile null");
    assert_eq!(
        body["error"]["code"],
        Value::String("confirmation_required".into()),
        "stable slug"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("rig restore"),
        "names the operation: {message}"
    );
}

/// The guard's other half: WITH `--yes` and no IGNITION_TOKEN, the
/// same no-rig environment fails at DISCOVERY (exit 7) — never at the
/// token check — proving the guard fired first and discovery owns the
/// next failure. (On a machine where discovery WOULD find a rig, the
/// token check is next: exit 3.)
#[test]
fn rig_restore_with_yes_in_no_rig_cwd_fails_cleanly_at_discovery() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "restore",
            "--file",
            "/nonexistent/snap.gwbk",
            "--yes",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(7),
        "guard passed: discovery failure"
    );
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["profile"], Value::Null);
    assert_eq!(body["error"]["code"], Value::String("rig_error".into()));
    assert!(
        body["error"]["message"]
            .as_str()
            .expect("message")
            .contains("no compose file discovered"),
        "the discovery diagnosis leads"
    );
}

/// The snapshot/restore help surfaces (contains-assertions — clap's
/// help rendering churns across versions by design): snapshot shows
/// `-o/--output <DIR>`; restore shows `--file <PATH>` +
/// `--timeout <SECS>` and names `--yes` in its destructive doc.
#[test]
fn rig_snapshot_restore_help_surfaces() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "snapshot", "--help"]);
    assert!(out.status.success(), "snapshot help exits 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("--output <DIR>"),
        "output visible: {stdout}"
    );
    assert!(stdout.contains("-o"), "the -o short form visible: {stdout}");

    let out = ign_rig(&config, &roots, cwd.path(), &["rig", "restore", "--help"]);
    assert!(out.status.success(), "restore help exits 0");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("--file <PATH>"), "file visible: {stdout}");
    assert!(
        stdout.contains("--timeout <SECS>"),
        "timeout visible: {stdout}"
    );
    assert!(
        stdout.contains("--yes"),
        "the destructive guard is documented in the verb's help: {stdout}"
    );
}

// ---------------------------------------------------------------------
// --with-module / fetch-policy flags (16-02 Task 2, D-15 through D-17)
// ---------------------------------------------------------------------

/// A config carrying one named rig whose compose file genuinely exists
/// on disk (a minimal, valid compose document — never resolved through
/// Docker by the tests that use this fixture, since their refusal
/// fires before `resolve_plan` ever runs). Returns the rig's PROJECT
/// DIRECTORY guard (kept alive by the CALLER — dropping it deletes the
/// directory, which is why this returns the `TempDir` itself and not
/// just its `.path()`) so a test can assert nothing new was written
/// there.
fn rig_config_with_real_compose_file() -> (tempfile::TempDir, PathBuf, tempfile::TempDir) {
    let project_dir = tempfile::tempdir().expect("project tempdir");
    let compose_file = project_dir.path().join("docker-compose.yml");
    std::fs::write(
        &compose_file,
        "services:\n  app:\n    image: alpine:latest\n",
    )
    .expect("write compose file");

    let (config_dir, config) = isolated_config();
    std::fs::write(
        &config,
        format!(
            "[rigs.fixture]\ncompose_file = '{}'\n",
            compose_file.display()
        ),
    )
    .expect("write config");

    (config_dir, config, project_dir)
}

/// THE malformed-flag refusal (Task 2, D-15): `--with-module` with no
/// `@` separator refuses exit 2 (`invalid_input`) with ZERO Docker
/// invocation — `preflight_with_module_flags` runs BEFORE
/// `resolve_plan`, so a REAL, resolvable rig config is used here
/// specifically to prove nothing was written to its project directory
/// (the directory holds ONLY the compose file this test seeded, never
/// an `ign`-generated override).
#[test]
fn malformed_with_module_value_is_exit_2() {
    let (_config_dir, config, project_dir_guard) = rig_config_with_real_compose_file();
    let project_dir = project_dir_guard.path();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "--rig",
            "fixture",
            "up",
            "--with-module",
            "git-no-separator",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(2),
        "malformed --with-module refuses at exit 2, never reaching a docker/resolve failure"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "docker-only: profile null");
    assert_eq!(
        body["error"]["code"],
        Value::String("invalid_input".into()),
        "stable slug"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(
        message.contains("git-no-separator"),
        "message names the received value: {message}"
    );

    let entries: Vec<_> = std::fs::read_dir(project_dir)
        .expect("read project dir")
        .map(|entry| entry.expect("dir entry").file_name())
        .collect();
    assert_eq!(
        entries,
        vec![std::ffi::OsString::from("docker-compose.yml")],
        "nothing was written to the rig's project directory — the refusal fired \
         before resolve_plan (and therefore before Docker) ever ran"
    );
}

/// THE unregistered-id refusal (Task 2, D-13): a well-formed
/// `--with-module` value naming an id with no registry entry refuses
/// exit 3 (`module_not_registered`), naming both the offending id and
/// every currently registered one — with ZERO Docker invocation, the
/// same `preflight_with_module_flags` guard as the malformed case.
#[test]
fn unknown_module_id_via_flag_lists_knowns() {
    let (_config_dir, config, project_dir_guard) = rig_config_with_real_compose_file();
    let project_dir = project_dir_guard.path();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "--rig",
            "fixture",
            "up",
            "--with-module",
            "nope@1.0.0",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(3),
        "unregistered module id refuses at exit 3, never reaching a docker/resolve failure"
    );
    assert!(out.stdout.is_empty(), "errors never touch stdout");
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(body["ok"], Value::Bool(false));
    assert_eq!(body["profile"], Value::Null, "docker-only: profile null");
    assert_eq!(
        body["error"]["code"],
        Value::String("module_not_registered".into()),
        "stable slug"
    );
    let message = body["error"]["message"].as_str().expect("message");
    assert!(message.contains("nope"), "names the bad id: {message}");
    assert!(message.contains("git"), "lists a known id: {message}");
    assert!(
        message.contains("project-scan-endpoint"),
        "lists the OTHER known id too: {message}"
    );

    let entries: Vec<_> = std::fs::read_dir(project_dir)
        .expect("read project dir")
        .map(|entry| entry.expect("dir entry").file_name())
        .collect();
    assert_eq!(
        entries,
        vec![std::ffi::OsString::from("docker-compose.yml")],
        "nothing was written to the rig's project directory"
    );
}

/// `rig reset` gets the SAME two refusals as `rig up` (D-15: `reset`
/// runs the same up-half internally) — proven once here rather than
/// duplicating both golden-message assertions above.
#[test]
fn rig_reset_with_module_refusals_match_rig_up() {
    let (_config_dir, config, _project_dir) = rig_config_with_real_compose_file();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "--rig",
            "fixture",
            "reset",
            "--yes",
            "--with-module",
            "nope@1.0.0",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(3),
        "same exit-3 refusal as `rig up`"
    );
    let body: Value = serde_json::from_str(&stderr_envelope(&out)).expect("error envelope parses");
    assert_eq!(
        body["error"]["code"],
        Value::String("module_not_registered".into())
    );
}

/// The `--with-module` / `--refresh` / `--accept-upstream-change` help
/// surface on BOTH `up` and `reset` (contains-assertions — clap's help
/// rendering churns across versions by design).
#[test]
fn rig_up_reset_help_shows_with_module_and_fetch_policy_flags() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    for verb in ["up", "reset"] {
        let out = ign_rig(&config, &roots, cwd.path(), &["rig", verb, "--help"]);
        assert!(out.status.success(), "{verb} help exits 0");
        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("--with-module <ID@VERSION>"),
            "{verb}: --with-module visible: {stdout}"
        );
        assert!(
            stdout.contains("--refresh"),
            "{verb}: --refresh visible: {stdout}"
        );
        assert!(
            stdout.contains("--accept-upstream-change"),
            "{verb}: --accept-upstream-change visible: {stdout}"
        );
        assert!(
            stdout.to_lowercase().contains("no subtractive form")
                || stdout.to_lowercase().contains("additive"),
            "{verb}: D-16's no-subtractive-form contract is discoverable in help: {stdout}"
        );
    }
}

/// D-17: `--refresh` and `--accept-upstream-change` together is a
/// usage-class refusal (clap's `conflicts_with`, exit 2) — BEFORE any
/// of this crate's own dispatch code runs, which is the strongest form
/// of "neither flag implies the other": the combination is not even a
/// reachable runtime state.
#[test]
fn refresh_and_accept_upstream_change_together_is_a_usage_error() {
    let (_config_dir, config) = isolated_config();
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let out = ign_rig(
        &config,
        &roots,
        cwd.path(),
        &[
            "rig",
            "up",
            "--refresh",
            "--accept-upstream-change",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(2),
        "clap's conflicts_with refuses the combination as a usage error"
    );
}

/// True when `docker` itself can be spawned and answers to a bare
/// invocation — distinct from [`docker_compose_available`] (which also
/// requires the compose plugin): this gate only needs the daemon to
/// accept `up -d`/`down`, so the cheaper probe is enough and avoids a
/// redundant `compose version` round-trip.
fn docker_daemon_available() -> bool {
    if !docker_compose_available() {
        return false;
    }
    // A reachable daemon is NOT enough: this test's fixture runs an
    // `alpine` image, and a Windows-container daemon answers every probe
    // happily and then fails the pull with "no matching manifest for
    // windows(...)/amd64" (observed on CI's windows-latest). Ask what the
    // daemon can actually RUN, not merely whether it is there.
    std::process::Command::new("docker")
        .args(["version", "--format", "{{.Server.Os}}"])
        .output()
        .ok()
        .filter(|out| out.status.success())
        .map(|out| String::from_utf8_lossy(&out.stdout).trim() == "linux")
        .unwrap_or(false)
}

/// RMOD-01 / the must_haves artifact table's "--json provisioning key"
/// half: `rig up --with-module git@VERSION` against a real (lightweight
/// alpine, no gateway port) rig — cache-seeded so the fetch is a pure
/// cache hit and no network request is ever made — succeeds and the
/// `--json` envelope's `data.provisioned_modules` carries exactly the
/// provisioned module's id/version/gateway_module_id/digest/source/
/// mount_target. Skips when Docker is unavailable or
/// `IGNITION_SKIP_RIG_DOCKER_TESTS` forces the skip (the file's
/// established convention) — teardown runs via a scope guard so a
/// mid-test panic never leaks the container.
#[test]
fn rig_up_with_module_json_reports_provisioned_modules() {
    if std::env::var("IGNITION_SKIP_RIG_DOCKER_TESTS").is_ok() || !docker_daemon_available() {
        eprintln!("skipping: docker unavailable (or skip forced) — this test drives a real rig");
        return;
    }

    let project_dir = tempfile::tempdir().expect("project tempdir");
    let compose_file = project_dir.path().join("docker-compose.yml");
    std::fs::write(
        &compose_file,
        "services:\n  app:\n    image: alpine:latest\n    command: [\"sleep\", \"infinity\"]\n",
    )
    .expect("write compose file");

    let project_name = format!(
        "ign-cli-test-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("clock")
            .as_nanos()
    );

    let (_config_dir, config) = isolated_config();
    std::fs::write(
        &config,
        format!(
            "[rigs.fixture]\ncompose_file = '{}'\nproject_name = '{}'\nmodule_service = \"app\"\n",
            compose_file.display(),
            project_name
        ),
    )
    .expect("write config");
    let (_roots_dir, roots) = isolated_roots();
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    // Pre-seed the module cache — CacheFirst (the default policy) is a
    // pure cache hit, so this test never contacts GitHub.
    let payload =
        b"synthetic .modl payload for rig_up_with_module_json_reports_provisioned_modules".to_vec();
    let digest = sha256_hex(&payload);
    let cache_root = tempfile::tempdir().expect("cache tempdir");
    let module_dir = cache_root.path().join("modules").join("git");
    std::fs::create_dir_all(&module_dir).expect("create module cache dir");
    std::fs::write(module_dir.join(format!("2.3.4-{digest}.modl")), &payload)
        .expect("seed cached artifact");

    // Teardown guard: `docker compose -p <name> -f <file> down -v
    // --remove-orphans` runs on drop (success, failure, or panic
    // alike) — best-effort, errors ignored.
    struct Teardown {
        compose_file: PathBuf,
        project_name: String,
    }
    impl Drop for Teardown {
        fn drop(&mut self) {
            let _ = std::process::Command::new("docker")
                .args([
                    "compose",
                    "-p",
                    &self.project_name,
                    "-f",
                    self.compose_file.to_str().expect("utf8 path"),
                    "down",
                    "-v",
                    "--remove-orphans",
                ])
                .output();
        }
    }
    let _teardown = Teardown {
        compose_file: compose_file.clone(),
        project_name: project_name.clone(),
    };

    let mut command = Command::cargo_bin("ign").expect("binary 'ign' not found");
    command
        .env("IGNITION_CLI_CONFIG", &config)
        .env("IGNITION_RIG_ROOTS", &roots)
        .env("IGNITION_CLI_CACHE", cache_root.path())
        .env_remove("IGNITION_RIG")
        .env_remove("IGNITION_TOKEN")
        .current_dir(cwd.path())
        .args([
            "rig",
            "--rig",
            "fixture",
            "up",
            "--with-module",
            "git@2.3.4",
            "--timeout",
            "60",
            "--json",
            "--compact",
        ]);
    let out = command.output().expect("spawn ign");
    assert!(
        out.status.success(),
        "rig up succeeds: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );

    let body: Value = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
        .expect("stdout envelope parses");
    assert_eq!(body["ok"], Value::Bool(true));
    let modules = body["data"]["provisioned_modules"]
        .as_array()
        .expect("provisioned_modules is always an array");
    assert_eq!(modules.len(), 1, "exactly the one --with-module module");
    assert_eq!(
        body["data"]["orphaned_modules"],
        serde_json::json!([]),
        "a NEWLY declared module is not an orphan, and the key is present-and-empty"
    );
    let module = &modules[0];
    assert_eq!(module["id"], Value::String("git".into()));
    assert_eq!(module["version"], Value::String("2.3.4".into()));
    assert_eq!(
        module["gateway_module_id"],
        Value::String("com.axone_io.ignition.git".into())
    );
    assert_eq!(module["digest_sha256"], Value::String(digest.clone()));
    assert_eq!(module["source"], Value::String("cache".into()));
    assert_eq!(
        module["mount_target"],
        Value::String("/usr/local/bin/ignition/user-lib/modules/git.modl".into())
    );

    let override_file = project_dir.path().join("compose.ign-modules.yml");
    assert!(
        override_file.exists(),
        "the override file was written to the rig's project directory"
    );
    let contents = std::fs::read_to_string(&override_file).expect("read override");
    assert!(contents.contains("git.modl"), "{contents}");
    assert!(contents.contains("com.axone_io.ignition.git"), "{contents}");
}

/// A real (lightweight alpine, no gateway port) rig fixture for the
/// Phase-19 orphan tests: a compose file, a rig config in TOML
/// LITERAL strings (a Windows path's backslashes are escapes in a
/// basic string), a pre-seeded module cache so `--with-module` is a
/// pure cache hit, and a teardown guard so a mid-test panic never
/// leaks the container.
struct OrphanRig {
    _config_dir: tempfile::TempDir,
    config: PathBuf,
    _roots_dir: tempfile::TempDir,
    roots: PathBuf,
    cwd: tempfile::TempDir,
    project_dir: tempfile::TempDir,
    compose_file: PathBuf,
    project_name: String,
    cache_root: tempfile::TempDir,
}

impl Drop for OrphanRig {
    fn drop(&mut self) {
        let _ = std::process::Command::new("docker")
            .args([
                "compose",
                "-p",
                &self.project_name,
                "-f",
                self.compose_file.to_str().expect("utf8 path"),
                "down",
                "-v",
                "--remove-orphans",
            ])
            .output();
    }
}

impl OrphanRig {
    fn new(tag: &str) -> Self {
        let project_dir = tempfile::tempdir().expect("project tempdir");
        let compose_file = project_dir.path().join("docker-compose.yml");
        std::fs::write(
            &compose_file,
            "services:\n  app:\n    image: alpine:latest\n    command: [\"sleep\", \"infinity\"]\n",
        )
        .expect("write compose file");
        let project_name = format!(
            "ign-cli-orphan-{tag}-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        );
        let (config_dir, config) = isolated_config();
        // NOTE: NO `[rigs.fixture.modules.*]` table — the rig declares
        // nothing, which is the "user deleted the table" state. The
        // `--with-module` flag stands in for the declaration on the
        // FIRST run only.
        std::fs::write(
            &config,
            format!(
                "[rigs.fixture]\ncompose_file = '{}'\nproject_name = '{}'\nmodule_service = \"app\"\n",
                compose_file.display(),
                project_name
            ),
        )
        .expect("write config");
        let (roots_dir, roots) = isolated_roots();

        let payload = format!("synthetic .modl payload for orphan test {tag}").into_bytes();
        let digest = sha256_hex(&payload);
        let cache_root = tempfile::tempdir().expect("cache tempdir");
        let module_dir = cache_root.path().join("modules").join("git");
        std::fs::create_dir_all(&module_dir).expect("create module cache dir");
        std::fs::write(module_dir.join(format!("2.3.4-{digest}.modl")), &payload)
            .expect("seed cached artifact");

        Self {
            _config_dir: config_dir,
            config,
            _roots_dir: roots_dir,
            roots,
            cwd: tempfile::tempdir().expect("cwd tempdir"),
            project_dir,
            compose_file,
            project_name,
            cache_root,
        }
    }

    fn override_file(&self) -> PathBuf {
        self.project_dir.path().join("compose.ign-modules.yml")
    }

    /// `ign rig --rig fixture up <extra…> --timeout 60 [--json --compact]`.
    fn up(&self, extra: &[&str], json: bool) -> std::process::Output {
        self.run("up", &[], extra, json)
    }

    /// `ign rig --rig fixture reset --yes --timeout 60 [--json --compact]`.
    fn reset(&self, json: bool) -> std::process::Output {
        self.run("reset", &["--yes"], &[], json)
    }

    fn run(&self, verb: &str, guard: &[&str], extra: &[&str], json: bool) -> std::process::Output {
        let mut command = Command::cargo_bin("ign").expect("binary 'ign' not found");
        command
            .env("IGNITION_CLI_CONFIG", &self.config)
            .env("IGNITION_RIG_ROOTS", &self.roots)
            .env("IGNITION_CLI_CACHE", self.cache_root.path())
            .env_remove("IGNITION_RIG")
            .env_remove("IGNITION_TOKEN")
            .current_dir(self.cwd.path())
            .args(["rig", "--rig", "fixture", verb])
            .args(guard)
            .args(extra)
            .args(["--timeout", "60"]);
        if json {
            command.args(["--json", "--compact"]);
        }
        command.output().expect("spawn ign")
    }
}

fn assert_success(out: &std::process::Output, what: &str) {
    assert!(
        out.status.success(),
        "{what} succeeds: stdout={} stderr={}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Phase 19 / SC-3 / the test-matrix rule, through the REAL binary with
/// real on-disk state. Three consecutive `rig up`s against one rig:
///
/// 1. a rig that has never provisioned anything reports
///    `orphaned_modules: []` — PRESENT and empty, never absent;
/// 2. `--with-module git@2.3.4` makes `ign` itself write a real
///    override naming `git` (not a hand-written stub);
/// 3. that override is then TAMPERED with — a mount naming an id the
///    registry does not know, and one whose path sits outside the
///    module directory — and `rig up` runs with nothing declared:
///    exactly `git` is reported (the tampered entries are dropped, SC-4),
///    it names its removal command, and the override file is GONE
///    (the read happened before the delete).
#[test]
fn rig_up_after_undeclaring_reports_the_orphan_and_deletes_the_override() {
    if std::env::var("IGNITION_SKIP_RIG_DOCKER_TESTS").is_ok() || !docker_daemon_available() {
        eprintln!("skipping: docker unavailable (or skip forced) — this test drives a real rig");
        return;
    }
    let rig = OrphanRig::new("json");

    // 1. Never provisioned: key present, empty.
    let out = rig.up(&[], true);
    assert_success(&out, "rig up on a never-provisioned rig");
    let body: Value = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
        .expect("stdout envelope parses");
    assert_eq!(
        body["data"]["orphaned_modules"],
        serde_json::json!([]),
        "an unprovisioned rig still carries the key"
    );
    assert!(!rig.override_file().exists(), "nothing was provisioned");

    // 2. ign writes a real override.
    let out = rig.up(&["--with-module", "git@2.3.4"], true);
    assert_success(&out, "rig up --with-module git");
    assert!(
        rig.override_file().exists(),
        "ign itself wrote the override that run 3 will find"
    );

    // 3. Tamper, then undeclare.
    let mut planted = std::fs::read_to_string(rig.override_file()).expect("read override");
    assert!(
        planted.contains("target: '/usr/local/bin/ignition/user-lib/modules/git.modl'"),
        "the real override names git: {planted}"
    );
    planted.push_str(
        "        target: '/usr/local/bin/ignition/user-lib/modules/totally-made-up.modl'\n\
         \x20       target: '/tmp/outside/project-scan-endpoint.modl'\n",
    );
    std::fs::write(rig.override_file(), planted).expect("plant tampered targets");

    let out = rig.up(&[], true);
    assert_success(&out, "rig up after undeclaring");
    let body: Value = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
        .expect("stdout envelope parses");
    let orphans = body["data"]["orphaned_modules"]
        .as_array()
        .expect("orphaned_modules is always an array");
    assert_eq!(
        orphans.len(),
        1,
        "exactly git: the unknown id and the out-of-directory path are dropped: {orphans:?}"
    );
    assert_eq!(orphans[0]["id"], Value::String("git".into()));
    assert_eq!(
        orphans[0]["gateway_module_id"],
        Value::String("com.axone_io.ignition.git".into())
    );
    assert_eq!(
        orphans[0]["remove_with"],
        Value::String("ign rig module uninstall git --rig fixture --yes".into())
    );
    assert_eq!(
        body["data"]["provisioned_modules"],
        serde_json::json!([]),
        "nothing is provisioned on the undeclared run"
    );
    assert!(
        !rig.override_file().exists(),
        "the stale override is deleted on the undeclare path"
    );

    // 4. Reported once, then quiet: the next up has nothing to report.
    let out = rig.up(&[], true);
    assert_success(&out, "rig up after the report");
    let body: Value = serde_json::from_str(&String::from_utf8_lossy(&out.stdout))
        .expect("stdout envelope parses");
    assert_eq!(body["data"]["orphaned_modules"], serde_json::json!([]));
}

/// The human render: the orphan line reaches the user's terminal and
/// names the command that removes the module — the verb is otherwise
/// undiscoverable. A routine `rig up` (no orphan) prints no orphan line.
#[test]
fn rig_up_after_undeclaring_prints_the_removal_command_for_humans() {
    if std::env::var("IGNITION_SKIP_RIG_DOCKER_TESTS").is_ok() || !docker_daemon_available() {
        eprintln!("skipping: docker unavailable (or skip forced) — this test drives a real rig");
        return;
    }
    let rig = OrphanRig::new("human");

    let out = rig.up(&["--with-module", "git@2.3.4"], false);
    assert_success(&out, "rig up --with-module git");
    let routine = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(
        !routine.contains("orphaned module"),
        "a routine up stays quiet: {routine}"
    );

    let out = rig.up(&[], false);
    assert_success(&out, "rig up after undeclaring");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("orphaned module: git (com.axone_io.ignition.git)"),
        "the orphan is named: {stdout}"
    );
    assert!(
        stdout.contains("ign rig module uninstall git --rig fixture --yes"),
        "the removal command is named: {stdout}"
    );
}

/// `rig reset` carries the same report as `rig up`: a reset is a
/// teardown plus an up, so a user who undeclared a module and then
/// RESETS (not ups) must still be told — through the real binary, the
/// real `reset` dispatch and the reset human renderer (which the
/// `rig up` tests do not reach).
#[test]
fn rig_reset_after_undeclaring_prints_the_removal_command() {
    if std::env::var("IGNITION_SKIP_RIG_DOCKER_TESTS").is_ok() || !docker_daemon_available() {
        eprintln!("skipping: docker unavailable (or skip forced) — this test drives a real rig");
        return;
    }
    let rig = OrphanRig::new("reset");

    let out = rig.up(&["--with-module", "git@2.3.4"], false);
    assert_success(&out, "rig up --with-module git");
    assert!(rig.override_file().exists(), "ign wrote the override");

    let out = rig.reset(false);
    assert_success(&out, "rig reset after undeclaring");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("orphaned module: git (com.axone_io.ignition.git)")
            && stdout.contains("ign rig module uninstall git --rig fixture --yes"),
        "reset names the orphan and its removal command: {stdout}"
    );
    assert!(
        !rig.override_file().exists(),
        "the stale override is deleted on the reset path too"
    );
}

/// sha256 hex digest — local helper (no dependency added: `sha2` is
/// already a workspace dependency of `ignition-core`, but this binary
/// crate's test target keeps its own copy rather than reaching into
/// core's private surface for one hash).
fn sha256_hex(bytes: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    format!("{:x}", hasher.finalize())
}