ignition-cli 1.6.2

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
//! CORE-11 stdout-purity harness: byte-exact stdout over the REAL spawned
//! binary under MAXIMUM diagnostics. The invariant being pinned: tracing is
//! stderr-only by construction (`init_tracing` ends
//! `.with_writer(std::io::stderr)`, main.rs) — so unknown-key config
//! warnings plus `IGNITION_LOG=trace` noise can never leak one stray byte
//! into stdout. If a regression ever prints a tracing line, panic message,
//! or partial write to stdout under noise, the byte compare fails on that
//! single stray byte.
//!
//! Noise recipe (both tests): a tempdir config file carrying an unknown
//! top-level key (`bogus_key = 1` — fires `warn_unknown_keys` tracing on
//! EVERY config load) and `IGNITION_LOG=trace` (max diagnostics).
//!
//! Harness design: ASSERT-based, deliberately NOT snapbox goldens, so
//! `SNAPSHOTS=overwrite` cannot silently sanitize a failure — a leaked byte
//! here must FAIL, never be rewritten. The expected bytes are hard-coded
//! (derived once from the pinned envelope shape in contract_profile.rs /
//! the real binary): pretty-JSON empty-list envelope + its single trailing
//! `println!` newline; human mode with no profiles and no active profile
//! prints NOTHING (the `[profile: …]` header is suppressed when no profile
//! resolved and there are no rows to render).
//!
//! Every spawn also strips the ambient `IGNITION_PROFILE` / `IGNITION_JSON`
//! / `IGNITION_YES` knobs — a developer shell with one of those exported
//! would otherwise change the envelope bytes (profile echo / render mode)
//! and turn a byte-exact assertion into a shell-dependent flake.

mod common;

use assert_cmd::Command;

/// Expected `ign profile list --json` stdout for the empty config, byte for
/// byte (pretty envelope, single trailing newline from `println!`).
const EXPECTED_JSON_STDOUT: &[u8] = b"{\n  \"ok\": true,\n  \"profile\": null,\n  \"data\": {\n    \"active\": null,\n    \"profiles\": []\n  }\n}\n";

/// Expected `ign profile list` (human mode) stdout for the empty config:
/// ZERO bytes — no header (no active profile), no rows.
const EXPECTED_HUMAN_STDOUT: &[u8] = b"";

/// Build `ign` under maximum diagnostics: isolated tempdir config whose
/// file carries an unknown top-level key, trace logging on, and the
/// ambient IGNITION_* knobs stripped for determinism.
fn noisy_ign() -> (tempfile::TempDir, Command) {
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    std::fs::write(&config, "bogus_key = 1\n").expect("write noisy config");
    let mut cmd = Command::cargo_bin("ign").expect("binary 'ign' not found");
    cmd.env("IGNITION_CLI_CONFIG", &config);
    cmd.env("IGNITION_LOG", "trace");
    cmd.env_remove("IGNITION_PROFILE");
    cmd.env_remove("IGNITION_JSON");
    cmd.env_remove("IGNITION_YES");
    (dir, cmd)
}

/// Byte-equality with a diff-friendly panic message (first differing offset
/// plus both sides' lengths) — a bare `assert_eq!` on byte slices dumps
/// hundreds of escaped bytes for one stray character.
fn assert_stdout_bytes(actual: &[u8], expected: &[u8], label: &str) {
    if actual == expected {
        return;
    }
    let first_diff = actual
        .iter()
        .zip(expected.iter())
        .position(|(a, e)| a != e)
        .unwrap_or(actual.len().min(expected.len()));
    panic!(
        "{label}: stdout is not byte-pure under max diagnostics.\n  first \
         differing byte at offset {first_diff}\n  actual len: {}, expected \
         len: {}\n  actual:   {:?}\n  expected: {:?}",
        actual.len(),
        expected.len(),
        String::from_utf8_lossy(actual),
        String::from_utf8_lossy(expected),
    );
}

/// JSON mode: stdout must be EXACTLY the empty-list envelope — one leaked
/// tracing byte under unknown-key warnings + `IGNITION_LOG=trace` fails.
#[test]
fn stdout_is_byte_pure_under_max_diagnostics() {
    let (_dir, mut cmd) = noisy_ign();
    let output = cmd
        .args(["profile", "list", "--json"])
        .output()
        .expect("spawn ign");
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    // Byte-exact: raw stdout equals the expected envelope bytes (single
    // trailing newline included).
    assert_stdout_bytes(&output.stdout, EXPECTED_JSON_STDOUT, "json mode");

    // Belt and braces (documents intent; byte-equality already implies it):
    // stdout is valid UTF-8 and parses as exactly ONE serde_json value with
    // nothing after it — `from_slice` rejects trailing non-whitespace bytes,
    // so this assertion localizes a future failure to "trailing junk"
    // versus "wrong bytes".
    let text = std::str::from_utf8(&output.stdout).expect("stdout is valid UTF-8");
    serde_json::from_slice::<serde_json::Value>(&output.stdout)
        .expect("stdout parses as exactly one JSON value with nothing after it");
    assert!(
        text.trim_end().ends_with('}'),
        "stdout ends inside a JSON value, not after it: {text:?}"
    );

    // The noise really fired: stderr carried the unknown-key warning.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("bogus_key"),
        "expected the unknown-key warning on stderr (noise precondition): {stderr}"
    );
}

/// Human mode: stdout must be EXACTLY zero bytes — the `[profile: …]`
/// header is suppressed when no profile resolved, there are no rows, and
/// the diagnostics noise stays on stderr.
#[test]
fn human_stdout_is_line_pure_under_max_diagnostics() {
    let (_dir, mut cmd) = noisy_ign();
    let output = cmd.args(["profile", "list"]).output().expect("spawn ign");
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    assert_stdout_bytes(&output.stdout, EXPECTED_HUMAN_STDOUT, "human mode");

    // The noise really fired here too.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("bogus_key"),
        "expected the unknown-key warning on stderr (noise precondition): {stderr}"
    );
}

/// 11-05 TAGS-12 scenario: the loss-gate REFUSAL prose (multi-line,
/// loss-report) must appear ONLY on stderr — byte-exact zero stdout
/// under max diagnostics. The gate runs PRE-resolution, so no
/// profile or gateway is needed: the refusal happens before any
/// resolution work and stdout must carry nothing at all.
#[test]
fn tags_import_loss_prose_never_touches_stdout() {
    let (_dir, mut cmd) = noisy_ign();
    let dir = tempfile::tempdir().expect("tempdir");
    // A gateway-export-shaped file (MinVersion root attr) — the
    // xml_export_edited_only fact fires the gate.
    let xml = dir.path().join("p5.xml");
    std::fs::write(
        &xml,
        "<Tags MinVersion=\"8.0.0\" locale=\"en_US\">\r\n   <Tag name=\"T1\" type=\"AtomicTag\">\r\n      <Property name=\"valueSource\">memory</Property>\r\n   </Tag>\r\n</Tags>\r\n",
    )
    .expect("write xml fixture");
    let output = cmd
        .args([
            "tags",
            "import",
            "--format",
            "xml",
            "--file",
            xml.to_str().expect("utf-8 path"),
            "--provider",
            "p5import",
        ])
        .output()
        .expect("spawn ign");

    assert_eq!(
        output.status.code(),
        Some(2),
        "the gate refuses exit 2 pre-resolution"
    );
    assert_stdout_bytes(&output.stdout, b"", "loss-gate refusal");

    // The prose really fired — on stderr.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("loss report (xml)") && stderr.contains("re-run with --yes"),
        "expected the loss report prose on stderr: {stderr}"
    );
}

/// 11-05 sibling: the stdout-mode raw export (`tags export --format
/// xml -o -`) writes the payload bytes and NOTHING else to stdout —
/// but the raw path needs a gateway, so this pins the failure-side
/// purity instead: any xml/csv export ERROR (precondition refusal)
/// leaves stdout byte-empty under noise, same invariant, zero wire.
#[test]
fn tags_export_error_keeps_stdout_byte_empty() {
    let (_dir, mut cmd) = noisy_ign();
    let output = cmd
        .args([
            "tags",
            "export",
            "[default]P5",
            "--format",
            "xml",
            "-o",
            "-",
        ])
        .output()
        .expect("spawn ign");
    assert_ne!(
        output.status.code(),
        Some(0),
        "no gateway configured — must refuse"
    );
    assert_stdout_bytes(&output.stdout, b"", "xml export refusal");
}

/// 13-07: the workspace family joins the purity harness — the three
/// new verbs are normal envelope verbs, so every refusal renders as
/// the contract error envelope on STDERR and stdout stays byte-empty
/// under max diagnostics. `workspace status` refuses PRE-resolution
/// (the missing-manifest read needs no gateway): profile null, exit
/// 2, zero requests, zero stdout bytes.
#[test]
fn workspace_status_missing_manifest_refusal_never_touches_stdout() {
    let (_dir, mut cmd) = noisy_ign();
    let missing = tempfile::tempdir().expect("tempdir").path().join("nope");
    let output = cmd
        .args(["workspace", "status", missing.to_str().expect("utf-8 path")])
        .output()
        .expect("spawn ign");
    assert_eq!(
        output.status.code(),
        Some(2),
        "the pre-resolve refusal exits 2"
    );
    assert_stdout_bytes(&output.stdout, b"", "missing-manifest refusal");

    // 13-03's stable refusal prefix really fired — on stderr.
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("not an ign workspace"),
        "expected the stable manifest refusal on stderr: {stderr}"
    );
}

/// 13-07 sibling: the same purity invariant for `workspace push`
/// (the PRE-resolve missing-manifest refusal — the reachable
/// zero-gateway case) and `workspace checkout` against a DEAD PORT —
/// the action-layer network refusal must also leave stdout untouched
/// under noise.
#[test]
fn workspace_push_and_checkout_refusals_keep_stdout_byte_empty() {
    // push: pre-resolve manifest refusal (no gateway involved).
    let (_dir, mut cmd) = noisy_ign();
    let absent = tempfile::tempdir().expect("tempdir");
    let missing = absent.path().join("nope");
    let output = cmd
        .args(["workspace", "push", missing.to_str().expect("utf-8 path")])
        .output()
        .expect("spawn ign");
    assert_eq!(
        output.status.code(),
        Some(2),
        "the pre-resolve refusal exits 2"
    );
    assert_stdout_bytes(&output.stdout, b"", "push missing-manifest refusal");

    // checkout: resolution succeeds against a profile whose URL is a
    // dead port — the action-layer network refusal (exit 6) rides the
    // envelope on stderr too.
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    std::fs::write(
        &config,
        "active = \"dev\"\n\n[profiles.dev]\nurl = \"http://127.0.0.1:9\"\nauth = { token_env = \"IGNITION_TOKEN\" }\n",
    )
    .expect("write dead-port config");
    let output = Command::cargo_bin("ign")
        .expect("binary 'ign' not found")
        .env("IGNITION_CLI_CONFIG", &config)
        .env("IGNITION_TOKEN", "mock:name-key")
        .env("IGNITION_LOG", "trace")
        .env_remove("IGNITION_PROFILE")
        .env_remove("IGNITION_JSON")
        .env_remove("IGNITION_YES")
        .args(["workspace", "checkout", "proj", "/tmp/ign-purity-checkout"])
        .output()
        .expect("spawn ign");
    assert_ne!(output.status.code(), Some(0), "a dead port must refuse");
    assert_stdout_bytes(&output.stdout, b"", "checkout network refusal");
}

/// 21-04: `deploy render` is an offline envelope verb; with `--json` stdout
/// is exactly one JSON value and its single trailing newline, even under
/// max diagnostics (unknown-key warnings + `IGNITION_LOG=trace`).
#[test]
fn deploy_render_json_stdout_is_the_envelope_only() {
    let (_dir, mut cmd) = noisy_ign();
    let output = cmd
        .args([
            "--json",
            "deploy",
            "render",
            "--env",
            "dev",
            "--repo",
            concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../ignition-core/tests/fixtures/deploy/repos/tracer"
            ),
        ])
        .output()
        .expect("spawn ign");
    assert_eq!(
        output.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = &output.stdout;
    assert!(
        stdout.ends_with(b"\n") && !stdout.ends_with(b"\n\n"),
        "exactly one trailing newline: {:?}",
        String::from_utf8_lossy(stdout)
    );
    let mut stream = serde_json::Deserializer::from_slice(stdout).into_iter::<serde_json::Value>();
    let envelope = stream
        .next()
        .expect("one JSON value")
        .expect("stdout parses as JSON");
    assert_eq!(envelope["ok"], true);
    // capture the offset BEFORE polling again: the next poll skips whitespace
    let value_end = stream.byte_offset();
    assert!(
        stream.next().is_none(),
        "stdout holds exactly one JSON value"
    );
    assert_eq!(
        stdout[value_end..],
        *b"\n",
        "nothing but the newline follows the envelope"
    );
}

/// 21-09: with `--out` the same holds: stdout is the envelope alone, and
/// `data.out` is the path as given.
#[test]
fn deploy_render_out_json_stdout_is_the_envelope_only() {
    let scratch = tempfile::tempdir().expect("tempdir");
    let out_dir = scratch.path().join("r");
    let (_dir, mut cmd) = noisy_ign();
    let output = cmd
        .args([
            "--json",
            "deploy",
            "render",
            "--env",
            "dev",
            "--repo",
            concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../ignition-core/tests/fixtures/deploy/repos/tracer"
            ),
            "--out",
        ])
        .arg(&out_dir)
        .output()
        .expect("spawn ign");
    assert_eq!(
        output.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = &output.stdout;
    assert!(
        stdout.ends_with(b"\n") && !stdout.ends_with(b"\n\n"),
        "exactly one trailing newline: {:?}",
        String::from_utf8_lossy(stdout)
    );
    let mut stream = serde_json::Deserializer::from_slice(stdout).into_iter::<serde_json::Value>();
    let envelope = stream
        .next()
        .expect("one JSON value")
        .expect("stdout parses as JSON");
    assert_eq!(envelope["ok"], true);
    assert_eq!(envelope["data"]["out"], out_dir.to_string_lossy().as_ref());
    let value_end = stream.byte_offset();
    assert!(
        stream.next().is_none(),
        "stdout holds exactly one JSON value"
    );
    assert_eq!(stdout[value_end..], *b"\n");
    assert!(out_dir.join("render.json").is_file());
}

/// 21-04: a `deploy render` refusal (unknown `--env`) exits 2 with the
/// error envelope on stderr and stdout byte-empty under max diagnostics.
#[test]
fn deploy_render_refusal_keeps_stdout_byte_empty() {
    let (_dir, mut cmd) = noisy_ign();
    let output = cmd
        .args([
            "--json",
            "deploy",
            "render",
            "--env",
            "nope",
            "--repo",
            concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../ignition-core/tests/fixtures/deploy/repos/tracer"
            ),
        ])
        .output()
        .expect("spawn ign");
    assert_eq!(output.status.code(), Some(2));
    assert_stdout_bytes(&output.stdout, b"", "deploy render refusal");
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("deploy_tree_invalid"),
        "expected the slug on stderr: {stderr}"
    );
}

/// 22-02: `deploy plan` over a `local:` tracer copy (an empty live
/// `config/resources/`, so every unit is `added`) keeps stdout to exactly one
/// JSON value and its trailing newline under max diagnostics.
#[test]
fn deploy_plan_json_stdout_is_the_envelope_only() {
    fn copy_dir(from: &std::path::Path, to: &std::path::Path) {
        std::fs::create_dir_all(to).expect("mkdir");
        for entry in std::fs::read_dir(from).expect("read_dir") {
            let entry = entry.expect("entry");
            let dest = to.join(entry.file_name());
            if entry.file_type().expect("type").is_dir() {
                copy_dir(&entry.path(), &dest);
            } else {
                std::fs::copy(entry.path(), &dest).expect("copy");
            }
        }
    }
    let scratch = tempfile::tempdir().expect("tempdir");
    let repo = scratch.path().join("repo");
    copy_dir(
        std::path::Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../ignition-core/tests/fixtures/deploy/repos/tracer"
        )),
        &repo,
    );
    let data = scratch.path().join("data");
    std::fs::create_dir_all(data.join("config").join("resources")).expect("resources dir");
    std::fs::write(
        repo.join("targets/dev.yaml"),
        format!(
            "schema_version: 1\ngateway: tracer-gw\nmode: dev\nnodes:\n  master:\n    profile: dev\n    local:\n      data_dir: '{}'\n",
            data.display()
        ),
    )
    .expect("target file");

    let (_dir, mut cmd) = noisy_ign();
    let output = cmd
        .args(["--json", "deploy", "plan", "--env", "dev", "--repo"])
        .arg(&repo)
        .output()
        .expect("spawn ign");
    assert_eq!(
        output.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = &output.stdout;
    assert!(
        stdout.ends_with(b"\n") && !stdout.ends_with(b"\n\n"),
        "exactly one trailing newline: {:?}",
        String::from_utf8_lossy(stdout)
    );
    let mut stream = serde_json::Deserializer::from_slice(stdout).into_iter::<serde_json::Value>();
    let envelope = stream
        .next()
        .expect("one JSON value")
        .expect("stdout parses as JSON");
    assert_eq!(envelope["ok"], true);
    assert_eq!(envelope["data"]["summary"]["has_changes"], true);
    let value_end = stream.byte_offset();
    assert!(
        stream.next().is_none(),
        "stdout holds exactly one JSON value"
    );
    assert_eq!(
        stdout[value_end..],
        *b"\n",
        "nothing but the newline follows the envelope"
    );
}

/// 22-11: a RED `deploy verify` against a wiremock gateway keeps stdout to
/// exactly one JSON value and its trailing newline under max diagnostics, and
/// exits 6 (the verdict exception).
#[tokio::test]
async fn deploy_verify_json_stdout_is_the_envelope_only() {
    use serde_json::json;
    use wiremock::matchers::{method, path, query_param};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn copy_dir(from: &std::path::Path, to: &std::path::Path) {
        std::fs::create_dir_all(to).expect("mkdir");
        for entry in std::fs::read_dir(from).expect("read_dir") {
            let entry = entry.expect("entry");
            let dest = to.join(entry.file_name());
            if entry.file_type().expect("type").is_dir() {
                copy_dir(&entry.path(), &dest);
            } else {
                std::fs::copy(entry.path(), &dest).expect("copy");
            }
        }
    }
    let scratch = tempfile::tempdir().expect("tempdir");
    let repo = scratch.path().join("repo");
    copy_dir(
        std::path::Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../ignition-core/tests/fixtures/deploy/repos/tracer"
        )),
        &repo,
    );
    // an empty live data dir: the REST list below is empty too, so the
    // verdict is red (resources missing) without any other setup
    let data = scratch.path().join("data");
    std::fs::create_dir_all(data.join("config").join("resources")).expect("resources dir");
    std::fs::write(
        repo.join("targets/dev.yaml"),
        format!(
            "schema_version: 1\ngateway: tracer-gw\nmode: dev\nnodes:\n  master:\n    profile: dev\n    local:\n      data_dir: '{}'\n",
            data.display()
        ),
    )
    .expect("target file");

    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/data/api/v1/scan/config"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "scanActive": false, "lastScanTimestamp": 1_792_000_000_000_i64, "lastScanDuration": 300
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/data/api/v1/gateway-info"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"deploymentMode": "dev"})))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path(
            "/data/api/v1/resources/list/ignition/database-translator",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "items": [], "metadata": {"total": 0, "matching": 0, "limit": -1, "offset": 0}
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path(
            "/data/api/v1/resources/singleton/ignition/general-alarm-settings",
        ))
        .respond_with(ResponseTemplate::new(404))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/data/api/v1/logs"))
        .and(query_param("limit", "1"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "items": [{"timestamp": 1_792_999_999_999_i64, "loggerName": "x", "level": "INFO", "message": "m"}],
            "metadata": {"total": 1, "matching": 1, "limit": 1, "offset": 0}
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/data/api/v1/logs"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "items": [], "metadata": {"total": 0, "matching": 0, "limit": 200, "offset": 0}
        })))
        .mount(&server)
        .await;

    let config = scratch.path().join("config.toml");
    std::fs::write(
        &config,
        format!(
            "active = \"dev\"\n\n[profiles.dev]\nurl = \"{}\"\nauth = {{ token_env = \"IGNITION_TOKEN\" }}\n",
            server.uri()
        ),
    )
    .expect("write config");
    let mut cmd = Command::cargo_bin("ign").expect("binary 'ign' not found");
    cmd.env("IGNITION_CLI_CONFIG", &config)
        .env("IGNITION_TOKEN", "mock:name-key")
        .env("IGNITION_LOG", "trace")
        .env_remove("IGNITION_URL")
        .env_remove("IGNITION_PROFILE")
        .env_remove("IGNITION_JSON")
        .env_remove("IGNITION_YES");
    let output = cmd
        .args(["--json", "deploy", "verify", "--env", "dev", "--repo"])
        .arg(&repo)
        .output()
        .expect("spawn ign");
    assert_eq!(
        output.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = &output.stdout;
    assert!(
        stdout.ends_with(b"\n") && !stdout.ends_with(b"\n\n"),
        "exactly one trailing newline: {:?}",
        String::from_utf8_lossy(stdout)
    );
    let mut stream = serde_json::Deserializer::from_slice(stdout).into_iter::<serde_json::Value>();
    let envelope = stream
        .next()
        .expect("one JSON value")
        .expect("stdout parses as JSON");
    assert_eq!(envelope["ok"], true);
    assert_eq!(envelope["data"]["ok"], false);
    assert_eq!(envelope["data"]["slug"], "deploy_verify_failed");
    let value_end = stream.byte_offset();
    assert!(
        stream.next().is_none(),
        "stdout holds exactly one JSON value"
    );
    assert_eq!(
        stdout[value_end..],
        *b"\n",
        "nothing but the newline follows the envelope"
    );
}

// ============================================================================
// 23-15: `deploy apply` and `deploy rollback` keep stdout to one envelope
// ============================================================================

/// `ign` pointed at the mock gateway at `url`, under the same noise as
/// [`noisy_ign`]: an unknown config key on every load and
/// `IGNITION_LOG=trace`. A tracing line on stdout fails the byte checks below.
fn noisy_gateway_ign(url: &str) -> (tempfile::TempDir, Command) {
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    std::fs::write(
        &config,
        format!(
            "bogus_key = 1\nactive = \"dev\"\n\n[profiles.dev]\nurl = \"{url}\"\nauth = {{ token_env = \"IGNITION_TOKEN\" }}\n"
        ),
    )
    .expect("write noisy config");
    let mut cmd = Command::cargo_bin("ign").expect("binary 'ign' not found");
    cmd.env("IGNITION_CLI_CONFIG", &config)
        .env("IGNITION_TOKEN", "mock:name-key")
        .env("IGNITION_LOG", "trace");
    for var in [
        "IGNITION_URL",
        "IGNITION_PROFILE",
        "IGNITION_JSON",
        "IGNITION_YES",
    ] {
        cmd.env_remove(var);
    }
    (dir, cmd)
}

/// Stdout is exactly one JSON value followed by its single newline.
fn assert_one_envelope(stdout: &[u8], label: &str) -> serde_json::Value {
    assert!(
        stdout.ends_with(b"\n") && !stdout.ends_with(b"\n\n"),
        "{label}: exactly one trailing newline: {:?}",
        String::from_utf8_lossy(stdout)
    );
    let mut stream = serde_json::Deserializer::from_slice(stdout).into_iter::<serde_json::Value>();
    let envelope = stream
        .next()
        .unwrap_or_else(|| panic!("{label}: one JSON value"))
        .unwrap_or_else(|e| panic!("{label}: stdout parses as JSON: {e}"));
    let value_end = stream.byte_offset();
    assert!(
        stream.next().is_none(),
        "{label}: stdout holds exactly one JSON value"
    );
    assert_eq!(
        stdout[value_end..],
        *b"\n",
        "{label}: nothing but the newline follows the envelope"
    );
    envelope
}

/// The JSON-mode apply and rollback args for `repo`, `--yes` unless `yes`
/// is false.
fn apply_cmd(
    server: &wiremock::MockServer,
    repo: &std::path::Path,
    hash: &str,
    yes: bool,
) -> std::process::Output {
    let (_cfg, mut cmd) = noisy_gateway_ign(&server.uri());
    cmd.args(common::apply_args(repo, Some(hash), true, yes))
        .output()
        .expect("spawn ign")
}

fn rollback_cmd(
    server: &wiremock::MockServer,
    repo: &std::path::Path,
    run: &str,
) -> std::process::Output {
    let (_cfg, mut cmd) = noisy_gateway_ign(&server.uri());
    cmd.args(common::rollback_args(repo, run, true, true))
        .output()
        .expect("spawn ign")
}

/// Apply through the quiet harness and return the run id.
async fn applied_run(server: &wiremock::MockServer, repo: &std::path::Path) -> String {
    common::apply_through_binary(server, repo, &[]).await
}

/// `deploy apply --json` writes one envelope to stdout and nothing else, for
/// an applied run, a rolled-back verdict (exit 6) and an error (no stdout).
#[tokio::test]
async fn deploy_apply_json_stdout_is_the_envelope_only() {
    use serde_json::json;

    // applied
    let (_scratch, repo, data) = common::apply_tracer();
    let hash = common::plan_hash(&repo);
    let server = wiremock::MockServer::start().await;
    common::mount_apply_gateway(&server, &data, Vec::new()).await;
    let out = apply_cmd(&server, &repo, &hash, true);
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let envelope = assert_one_envelope(&out.stdout, "apply applied");
    assert_eq!(envelope["data"]["outcome"], "applied");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("bogus_key"),
        "the noise really fired (precondition): {stderr}"
    );

    // error: no --yes is a refusal, stdout stays empty
    let (_scratch, repo, data) = common::apply_tracer();
    let hash = common::plan_hash(&repo);
    let server = wiremock::MockServer::start().await;
    common::mount_apply_gateway(&server, &data, Vec::new()).await;
    let out = apply_cmd(&server, &repo, &hash, false);
    assert_eq!(out.status.code(), Some(2));
    assert_stdout_bytes(&out.stdout, b"", "apply confirmation refusal");
    assert!(String::from_utf8_lossy(&out.stderr).contains("confirmation_required"));

    // rolled back: a verdict envelope on stdout and exit 6
    let (_scratch, repo, data) = common::apply_tracer();
    let hash = common::plan_hash(&repo);
    let server = wiremock::MockServer::start().await;
    common::mount_apply_gateway(
        &server,
        &data,
        vec![json!({
            "timestamp": 1_792_999_999_000_i64,
            "loggerName": "NamedResourceHandler-ignition/database-translator",
            "level": "WARN",
            "message": format!(
                "Resource {} does not have required UUID attribute, will not be loaded",
                common::NAMED_TRANSLATOR
            ),
        })],
    )
    .await;
    let out = apply_cmd(&server, &repo, &hash, true);
    assert_eq!(
        out.status.code(),
        Some(6),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let envelope = assert_one_envelope(&out.stdout, "apply rolled back");
    assert_eq!(envelope["data"]["outcome"], "rolled_back");
    assert_eq!(envelope["data"]["slug"], "deploy_rolled_back");
}

/// `deploy rollback --json` writes one envelope to stdout for a restore and a
/// cleared interrupted run, and leaves stdout empty on an error.
#[tokio::test]
async fn deploy_rollback_json_stdout_is_the_envelope_only() {
    use ignition_core::deploy::apply::journal::JournalPhase;

    // restored
    let (_scratch, repo, data) = common::apply_tracer();
    let server = wiremock::MockServer::start().await;
    common::mount_apply_gateway(&server, &data, Vec::new()).await;
    let run = applied_run(&server, &repo).await;
    let out = rollback_cmd(&server, &repo, &run);
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let envelope = assert_one_envelope(&out.stdout, "rollback restored");
    assert_eq!(envelope["data"]["outcome"], "restored");
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("bogus_key"),
        "the noise really fired (precondition)"
    );

    // cleared: a journal a run killed before its first move leaves, over a
    // host that equals its pre-apply state (the rollback above put it back)
    common::plant_journal_at(&data, &run, JournalPhase::Ready);
    let out = rollback_cmd(&server, &repo, &run);
    assert_eq!(
        out.status.code(),
        Some(0),
        "{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let envelope = assert_one_envelope(&out.stdout, "rollback cleared");
    assert_eq!(envelope["data"]["outcome"], "cleared");

    // error: a later edit refuses the rollback; stdout stays empty
    let (_scratch, repo, data) = common::apply_tracer();
    let server = wiremock::MockServer::start().await;
    common::mount_apply_gateway(&server, &data, Vec::new()).await;
    let run = applied_run(&server, &repo).await;
    common::edit_live_unit(&data);
    let out = rollback_cmd(&server, &repo, &run);
    assert_eq!(out.status.code(), Some(6));
    assert_stdout_bytes(&out.stdout, b"", "rollback live-changed refusal");
    assert!(String::from_utf8_lossy(&out.stderr).contains("deploy_live_changed"));
}

// ============================================================================
// 25-17: `deploy projects` keeps stdout to one envelope
// ============================================================================

/// A project repo for `CapApp` (deployable to `dev`), a targets root for the
/// `capgw` gateway whose host is a local data directory, and a git work tree
/// that ignores `.ign/`. Returns `(scratch, repo, targets)`.
fn projects_repo() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
    use std::fs::{create_dir_all, write};
    let scratch = tempfile::tempdir().expect("tempdir");
    let repo = scratch.path().join("repo");
    let targets = scratch.path().join("targets-root");
    let data = scratch.path().join("data");
    let put = |root: &std::path::Path, rel: &str, bytes: &[u8]| {
        let file = root.join(rel);
        create_dir_all(file.parent().expect("parent")).expect("mkdir");
        write(file, bytes).expect("write");
    };
    create_dir_all(data.join("projects")).expect("data dir");
    put(
        &repo,
        "project.json",
        br#"{"title":"Cap App","enabled":true}"#,
    );
    put(
        &repo,
        "deploy/project.yaml",
        b"schema_version: 1\nproject: CapApp\nenvironments: [dev]\n",
    );
    put(
        &repo,
        "ignition/script-python/cap/resource.json",
        br#"{"scope":"A","files":["code.py"],"attributes":{"enabled":true}}"#,
    );
    put(
        &repo,
        "ignition/script-python/cap/code.py",
        b"def f():\n    return 1\n",
    );
    put(&repo, ".gitignore", b".ign/\n");
    put(
        &data,
        "config/resources/core/ignition/system-properties/config.json",
        br#"{"systemName":"capgw"}"#,
    );
    put(
        &targets,
        "targets/dev.yaml",
        format!(
            "schema_version: 1\ngateway: capgw\nmode: dev\nnodes:\n  master:\n    profile: dev\n    local:\n      data_dir: '{}'\n",
            data.display()
        )
        .as_bytes(),
    );
    let status = std::process::Command::new("git")
        .args(["init", "-q"])
        .arg(&repo)
        .status()
        .expect("git runs");
    assert!(status.success());
    (scratch, repo, targets)
}

/// A gateway that does not have `CapApp` yet: an import creates it, and the
/// export that follows is exactly the artifact built from `repo`.
async fn mount_projects_gateway(server: &wiremock::MockServer, repo: &std::path::Path) -> String {
    use serde_json::json;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, ResponseTemplate};

    let artifact =
        ignition_core::deploy::project_artifact::build_artifact(repo).expect("the fixture builds");
    let get = |route: &str, response: ResponseTemplate| {
        Mock::given(method("GET"))
            .and(path(route.to_string()))
            .respond_with(response)
    };
    get(
        "/data/api/v1/gateway-info",
        ResponseTemplate::new(200).set_body_json(json!({
            "name": "capgw",
            "deploymentMode": "dev",
            "ignitionVersion": "8.3.6 (b2026042713)"
        })),
    )
    .mount(server)
    .await;
    get(
        "/data/api/v1/designers",
        ResponseTemplate::new(200).set_body_json(json!({
            "items": [],
            "metadata": {"total": 0, "matching": 0, "limit": -1, "offset": 0}
        })),
    )
    .mount(server)
    .await;
    get(
        "/data/api/v1/projects/list",
        ResponseTemplate::new(200).set_body_json(json!({
            "items": [],
            "metadata": {"total": 0, "matching": 0, "limit": -1, "offset": 0}
        })),
    )
    .mount(server)
    .await;
    get(
        "/data/api/v1/projects/find/CapApp",
        ResponseTemplate::new(404).set_body_json(json!({"message": "Project not found"})),
    )
    .mount(server)
    .await;
    get(
        "/data/api/v1/projects/export/CapApp",
        ResponseTemplate::new(200).set_body_raw(artifact.zip, "application/zip"),
    )
    .mount(server)
    .await;
    Mock::given(method("POST"))
        .and(path("/data/api/v1/projects/import/CapApp"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({"success": true, "changes": [{"name": "CapApp"}]})),
        )
        .mount(server)
        .await;
    artifact.digest.sha256
}

/// `deploy projects --check --json` and a confirmed `--json` apply write
/// exactly one envelope to stdout under maximum diagnostics, and the noise
/// really fired on stderr.
#[tokio::test]
async fn projects_stdout_one_envelope() {
    for (confirmed, outcome) in [(false, "checked"), (true, "created")] {
        let (_scratch, repo, targets) = projects_repo();
        let server = wiremock::MockServer::start().await;
        let hash = mount_projects_gateway(&server, &repo).await;
        let (_cfg, mut cmd) = noisy_gateway_ign(&server.uri());
        cmd.args([
            "--json",
            "deploy",
            "projects",
            "--env",
            "dev",
            "--release",
            "v1.0.0",
            "--repo",
        ])
        .arg(&repo)
        .arg("--targets")
        .arg(&targets);
        if confirmed {
            cmd.args(["--artifact-sha256", &hash, "--yes"]);
        } else {
            cmd.arg("--check");
        }
        let out = cmd.output().expect("spawn ign");
        let label = if confirmed {
            "projects apply"
        } else {
            "projects check"
        };
        assert_eq!(
            out.status.code(),
            Some(0),
            "{label}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        let envelope = assert_one_envelope(&out.stdout, label);
        assert_eq!(envelope["ok"], true, "{label}");
        assert_eq!(envelope["data"]["outcome"], outcome, "{label}");
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            stderr.contains("bogus_key"),
            "{label}: the noise really fired (precondition): {stderr}"
        );
    }
}