ignition-cli 1.6.4

ign — operate Ignition 8.3+ gateways from the terminal
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
//! Opt-in e2e harness for the project family — dogfoods the BUILT
//! `ign` binary against a real commissioned Ignition 8.3+ gateway via
//! `assert_cmd` (true end-to-end, not trait-level; 03-RESEARCH §e2e
//! Harness Skeleton). Phases 4 (rig) and 5 (webdev deploy) EXTEND
//! this file: shared env helpers here, one test per capability loop.
//!
//! ```text
//! cargo test -p ignition-cli --test e2e_projects -- --ignored
//! ```
//!
//! Skip behavior (the 02-01 live-suite convention): every test reads
//! its env vars at start and returns quietly when they are absent —
//! `-- --ignored` with no envs set is a GREEN no-op, so the suite
//! adds ZERO default CI cost. Reads need `IGNITION_LIVE_URL` +
//! `IGNITION_LIVE_TOKEN`; MUTATIONS additionally require
//! `IGNITION_LIVE_MUTATIONS=1` (the 02-04 precedent — an explicit
//! opt-in before anything touches gateway state).
//!
//! ## Environment
//!
//! | var | required by | meaning |
//! |---|---|---|
//! | `IGNITION_LIVE_URL` | every test | base URL, e.g. `http://localhost:18088` |
//! | `IGNITION_LIVE_TOKEN` | every test | full `name:key` API-token string |
//! | `IGNITION_LIVE_MUTATIONS` | the loop test | `1` to allow create/put/import/rename/copy/delete |
//!
//! ## The loop test's contract pins (the phase's open questions)
//!
//! 05-02 RE-POINT: the resource verbs ride project-export ZIP
//! surgery (export → member surgery → overwrite-import) — this loop
//! is live-runnable against a real 8.3 gateway for the FIRST time
//! since Phase 3 (the `/projects/{p}/resources/**` REST routes never
//! existed; the STATE.md cross-phase blocker is CLOSED by that
//! plan). Resource `put`/`delete` are `--yes`-guarded now — every
//! mutation implicitly re-imports the project.
//!
//! ORDER MATTERS — the loop additionally pins TWO-SIDED put honesty
//! (a get before the second put witnesses the OLD member content —
//! get rides the same export; the put after it flips the content a
//! follow-up get reads back) and the delete surgery (the member is
//! `not_found` after `resource delete`). 05-07 adds THE put-new-on-a-
//! USED-project witness (UAT Gap 1's exact failure shape): a new
//! member in a new folder chain on a project that already carries
//! resources must LAND — read-back verified, never trusted on the
//! import's success body (the gateway answers success:true for
//! descriptor-less appends while landing NOTHING, live-proven). The
//! PROJECT-level pins stay from 03-02: export happens AFTER the
//! first resource put and BEFORE the second, because overwrite
//! import REPLACES the entire project (Pitfall 4). The two
//! post-import gets pin BOTH halves of the replace-not-merge
//! contract: the pre-export resource SURVIVED (export→import
//! round-trip fidelity) and the post-export resource is GONE
//! (`not_found` — resources absent from the ZIP are deleted; merge
//! is Designer-only). Timestamped project names mean a failure
//! leaves forensic state on the gateway for inspection; cleanup is
//! best-effort.

use std::path::{Path, PathBuf};
use std::process::Output;
use std::time::{SystemTime, UNIX_EPOCH};

use assert_cmd::Command;
use ignition_core::client::install_crypto_provider;
use serde_json::Value;

/// The gathered env contract for one live-gateway run.
struct LiveEnv {
    /// `IGNITION_LIVE_URL` — gateway base URL.
    url: String,
    /// `IGNITION_LIVE_TOKEN` — the full `name:key` string.
    token: String,
}

/// Non-empty `IGNITION_LIVE_URL`, when set.
fn live_url() -> Option<String> {
    std::env::var("IGNITION_LIVE_URL")
        .ok()
        .filter(|value| !value.trim().is_empty())
}

/// Non-empty `IGNITION_LIVE_TOKEN`, when set.
fn live_token() -> Option<String> {
    std::env::var("IGNITION_LIVE_TOKEN")
        .ok()
        .filter(|value| !value.trim().is_empty())
}

/// Whether `IGNITION_LIVE_MUTATIONS=1` opted the mutations in.
fn live_mutations() -> bool {
    std::env::var("IGNITION_LIVE_MUTATIONS").is_ok_and(|value| value == "1")
}

fn skip(message: &str) {
    eprintln!("skipping: {message}");
}

/// Read the read-suite env contract; `None` (caller skips quietly)
/// when either half is absent.
fn live_env() -> Option<LiveEnv> {
    match (live_url(), live_token()) {
        (Some(url), Some(token)) => Some(LiveEnv { url, token }),
        _ => None,
    }
}

/// The mutation gate: read env + the explicit mutations opt-in.
fn live_env_mutations() -> Option<LiveEnv> {
    if !live_mutations() {
        return None;
    }
    live_env()
}

/// An isolated config dir + a one-profile config pointing the `dev`
/// profile at the LIVE gateway with the token from `IGNITION_TOKEN`.
/// `--profile`-free: every spawn carries `IGNITION_URL` +
/// `IGNITION_TOKEN` env instead (the snapbox lesson — isolated
/// `IGNITION_CLI_CONFIG` per run so nothing leaks between tests).
fn isolated_live_config(env: &LiveEnv) -> (tempfile::TempDir, PathBuf) {
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    std::fs::write(
        &config,
        format!(
            "active = \"dev\"\n\n[profiles.dev]\nurl = \"{}\"\nauth = {{ token_env = \"IGNITION_TOKEN\" }}\n",
            env.url
        ),
    )
    .expect("write config");
    (dir, config)
}

/// Spawn the built `ign` binary at the live gateway with args.
fn ign(config: &Path, env: &LiveEnv, args: &[&str]) -> Output {
    let mut command = Command::cargo_bin("ign").expect("binary 'ign' not found");
    command
        .env("IGNITION_CLI_CONFIG", config)
        .env("IGNITION_TOKEN", &env.token)
        .env("IGNITION_URL", &env.url);
    command.args(args).output().expect("spawn ign")
}

/// A timestamped project name — failures leave forensic state on the
/// gateway (deliberate: `ign project list` shows what a run left
/// behind) and parallel runs never collide.
fn timestamped_name(suffix: &str) -> String {
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock after the unix epoch")
        .as_secs();
    format!("ign-e2e-{ts}{suffix}")
}

/// Assert success, printing stderr for diagnosis on failure.
fn expect_ok(what: &str, out: &Output) {
    assert!(
        out.status.success(),
        "{what} failed (exit {:?}):\nstdout: {}\nstderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Parse the compact JSON success envelope from stdout.
fn data_envelope(out: &Output) -> Value {
    let stdout = String::from_utf8_lossy(&out.stdout);
    serde_json::from_str(stdout.trim())
        .unwrap_or_else(|err| panic!("stdout envelope parses ({err}): {stdout}"))
}

/// Assert a failure exit + slug, returning the full error envelope
/// (callers assert the endpoint/context they care about).
fn expect_exit(out: &Output, code: i32, slug: &str, what: &str) -> Value {
    assert_eq!(
        out.status.code(),
        Some(code),
        "{what} must exit {code} (got {:?}):\nstdout: {}\nstderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    let envelope: Value = serde_json::from_str(stderr[stderr.find('{').unwrap_or(0)..].trim())
        .unwrap_or_else(|err| panic!("stderr envelope parses ({err}): {stderr}"));
    assert_eq!(
        envelope["error"]["code"], slug,
        "{what} must be {slug}: {envelope}"
    );
    envelope
}

/// The scratch script resource the loop writes — a `code.py`-style
/// JSON body under the CORE module's real folder name (`ignition/`,
/// not the mcp docs' `com.inductiveautomation.ignition`).
const SCRATCH_PATH: &str = "ignition/script-python/e2e/scratch";
/// The SECOND scratch, written only AFTER the export so it exists on
/// the gateway but NOT in the ZIP (the replace-not-merge witness).
const SCRATCH2_PATH: &str = "ignition/script-python/e2e/scratch2";
/// The THIRD scratch (05-07, UAT Gap 1's exact failure shape): a NEW
/// member in a NEW folder chain on a USED project — the half the
/// fresh-project loop could never catch (put-new must LAND, verified
/// by read-back, not by the import's success body).
const SCRATCH3_PATH: &str = "ignition/script-python/uat2/second.py";

/// THE full loop (order is the contract — see the module docs):
/// new → list-contains → resource list EMPTY → put scratch --yes
/// (surgery) → get round-trip → resource list CONTAINS → TWO-SIDED
/// put honesty (get OLD → export (scope metadata) → put scratch NEW
/// --yes → get NEW) → put scratch2 --yes (gateway-only) → abort
/// import (`project_exists`) → overwrite import (+`--yes`) →
/// scratch SURVIVED with OLD content + scratch2 `not_found`
/// (replace-not-merge, Pitfall 4) → resource delete scratch --yes →
/// get `not_found` (the delete surgery witness) → rename → copy →
/// delete both (cleanup).
#[test]
#[ignore = "opt-in e2e: set IGNITION_LIVE_URL + IGNITION_LIVE_TOKEN + IGNITION_LIVE_MUTATIONS=1"]
fn full_project_resource_loop() {
    let Some(env) = live_env_mutations() else {
        skip(
            "IGNITION_LIVE_MUTATIONS=1 (with URL+TOKEN) not set — refusing to touch a live gateway",
        );
        return;
    };
    let (_dir, config) = isolated_live_config(&env);
    let name = timestamped_name("");
    let workdir = tempfile::tempdir().expect("workdir");
    let zip_path = workdir.path().join("loop.zip");

    // 1. project new — the loop's substrate.
    expect_ok(
        "project new",
        &ign(&config, &env, &["project", "new", &name, "--compact"]),
    );

    // 2. project list contains it.
    let out = ign(&config, &env, &["project", "list", "--compact"]);
    expect_ok("project list", &out);
    let listing = data_envelope(&out);
    let listed = listing["data"]["projects"]
        .as_array()
        .expect("projects array")
        .iter()
        .any(|project| project["name"] == Value::String(name.clone()));
    assert!(listed, "the new project appears in `project list`");

    // 3. resource list on the FRESH project is EMPTY (all-keys
    // always: resources [], zero members under the resource roots —
    // the surgery list over a real export).
    let out = ign(&config, &env, &["resource", "list", &name, "--compact"]);
    expect_ok("resource list (fresh)", &out);
    let fresh = data_envelope(&out)["data"].clone();
    assert_eq!(
        fresh["resources"],
        Value::Array(vec![]),
        "a brand-new project exports zero resource members: {fresh}"
    );

    // 4. resource put a scratch script (--yes: the put re-imports
    // the whole project — the 05-02 guarded-verb set).
    let scratch_body = format!(
        r#"{{"scope":"G","code":"print('{}')", "e2e": true}}"#,
        name.replace('\'', "")
    );
    let scratch_file = workdir.path().join("scratch.json");
    std::fs::write(&scratch_file, &scratch_body).expect("write scratch body");
    expect_ok(
        "resource put scratch",
        &ign(
            &config,
            &env,
            &[
                "resource",
                "put",
                &name,
                SCRATCH_PATH,
                "--file",
                scratch_file.to_str().unwrap(),
                "--yes",
                "--compact",
            ],
        ),
    );

    // 5. resource get verifies the round-trip (content survives the
    // surgery write path byte-honestly — sniffed json, same code).
    let out = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH_PATH, "--compact"],
    );
    expect_ok("resource get scratch", &out);
    let got = data_envelope(&out)["data"].clone();
    assert_eq!(got["content_kind"], Value::String("json".into()));
    assert_eq!(
        got["content"]["e2e"],
        Value::Bool(true),
        "the written content reads back: {got}"
    );

    // 6. resource list now CONTAINS the scratch path (the surgery
    // list sees the member the put injected).
    let out = ign(&config, &env, &["resource", "list", &name, "--compact"]);
    expect_ok("resource list (populated)", &out);
    let populated = data_envelope(&out)["data"].clone();
    assert!(
        populated["resources"]
            .as_array()
            .expect("resources array")
            .iter()
            .any(|entry| entry["path"] == Value::String(SCRATCH_PATH.into())),
        "the put member appears in the surgery list: {populated}"
    );

    // 7. TWO-SIDED PUT HONESTY, first half: a get BEFORE the second
    // put witnesses the OLD content (get rides the same export the
    // put's surgery will operate on).
    let out = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH_PATH, "--compact"],
    );
    expect_ok("resource get scratch (pre-second-put)", &out);
    let old_content = data_envelope(&out)["data"]["content"].clone();
    assert_eq!(
        old_content["e2e"],
        Value::Bool(true),
        "the export BEFORE the second put carries the member with OLD content: {old_content}"
    );

    // 8. export AFTER the first put — the ZIP must CONTAIN scratch
    // (this is also the replace-not-merge substrate below).
    let out = ign(
        &config,
        &env,
        &[
            "project",
            "export",
            &name,
            "-o",
            zip_path.to_str().unwrap(),
            "--compact",
        ],
    );
    expect_ok("project export", &out);
    let export = data_envelope(&out)["data"].clone();
    assert!(zip_path.exists(), "the export file landed");
    assert!(export["bytes"].as_u64().expect("bytes") > 0);
    assert!(
        export["scope"]["includes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|v| v == "scripts"),
        "scope.includes carries scripts: {export}"
    );
    assert!(
        export["scope"]["excludes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|v| v == "tags"),
        "scope.excludes carries tags: {export}"
    );

    // 9. TWO-SIDED PUT HONESTY, second half: put the scratch with
    // NEW content, then a get reads the NEW content back.
    let scratch_new = workdir.path().join("scratch-new.json");
    std::fs::write(
        &scratch_new,
        r#"{"scope":"G","code":"print('second-edition')", "e2e": true, "edited": true}"#,
    )
    .expect("write scratch-new body");
    expect_ok(
        "resource put scratch (new content)",
        &ign(
            &config,
            &env,
            &[
                "resource",
                "put",
                &name,
                SCRATCH_PATH,
                "--file",
                scratch_new.to_str().unwrap(),
                "--yes",
                "--compact",
            ],
        ),
    );
    let out = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH_PATH, "--compact"],
    );
    expect_ok("resource get scratch (post-second-put)", &out);
    let new_content = data_envelope(&out)["data"]["content"].clone();
    assert_eq!(
        new_content["edited"],
        Value::Bool(true),
        "the export AFTER the second put carries the member with NEW content: {new_content}"
    );

    // 10. put a SECOND scratch that exists ONLY on the gateway — the
    // ZIP on disk predates it.
    let scratch2_file = workdir.path().join("scratch2.json");
    std::fs::write(&scratch2_file, r#"{"scope":"G","code":"print('second')"}"#)
        .expect("write scratch2 body");
    expect_ok(
        "resource put scratch2",
        &ign(
            &config,
            &env,
            &[
                "resource",
                "put",
                &name,
                SCRATCH2_PATH,
                "--file",
                scratch2_file.to_str().unwrap(),
                "--yes",
                "--compact",
            ],
        ),
    );

    // 10b. THE put-new-on-a-USED-project witness (05-07, UAT Gap 1):
    // a NEW member in a NEW folder chain (`uat2/`, disjoint from
    // `e2e/`) on a project that already carries resources — the
    // fresh-project half alone never caught the landing gap, and the
    // wiremock fixtures own only the DENIAL honesty. The put must
    // LAND: a follow-up get reads the exact content back and the
    // list carries the member (and its synthesized parent
    // descriptor) — never trusting the import's success body alone.
    let scratch3_file = workdir.path().join("scratch3.txt");
    std::fs::write(&scratch3_file, "print('used-project-put-new')\n").expect("write scratch3");
    expect_ok(
        "resource put scratch3 (new chain, used project)",
        &ign(
            &config,
            &env,
            &[
                "resource",
                "put",
                &name,
                SCRATCH3_PATH,
                "--file",
                scratch3_file.to_str().unwrap(),
                "--yes",
                "--compact",
            ],
        ),
    );
    let out = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH3_PATH, "--compact"],
    );
    expect_ok("resource get scratch3", &out);
    let landed = data_envelope(&out)["data"].clone();
    assert_eq!(
        landed["content_kind"],
        Value::String("text".into()),
        "plain text put classifies text: {landed}"
    );
    assert_eq!(
        landed["content"],
        Value::String("print('used-project-put-new')\n".into()),
        "THE UAT Gap-1 truth: put-new LANDS on a used project — get reads it back: {landed}"
    );
    let out = ign(&config, &env, &["resource", "list", &name, "--compact"]);
    expect_ok("resource list (scratch3 landed)", &out);
    let listed3 = data_envelope(&out)["data"].clone();
    assert!(
        listed3["resources"]
            .as_array()
            .expect("resources array")
            .iter()
            .any(|entry| entry["path"] == Value::String(SCRATCH3_PATH.into())),
        "the new-chain member appears in the list: {listed3}"
    );
    assert!(
        listed3["resources"]
            .as_array()
            .expect("resources array")
            .iter()
            .any(|entry| entry["path"]
                == Value::String("ignition/script-python/uat2/resource.json".into())),
        "the synthesized parent descriptor rides the archive (the live-proven landing shape): {listed3}"
    );

    // 11. abort-policy import into the SAME name → project_exists,
    // BEFORE any upload.
    let abort = ign(
        &config,
        &env,
        &[
            "project",
            "import",
            &name,
            "--file",
            zip_path.to_str().unwrap(),
            "--compact",
        ],
    );
    expect_exit(&abort, 6, "project_exists", "abort import");

    // 12. overwrite import (guarded) → success.
    expect_ok(
        "overwrite import",
        &ign(
            &config,
            &env,
            &[
                "project",
                "import",
                &name,
                "--file",
                zip_path.to_str().unwrap(),
                "--collision-policy",
                "overwrite",
                "--yes",
                "--compact",
            ],
        ),
    );

    // 13. THE two-sided replace-not-merge pin (Pitfall 4):
    //     scratch SURVIVED with the OLD (in-ZIP) content — the
    //     overwrite import replaced the second put's edit…
    let out = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH_PATH, "--compact"],
    );
    expect_ok("resource get scratch post-import", &out);
    let survived = data_envelope(&out)["data"].clone();
    assert_eq!(
        survived["content"]["e2e"],
        Value::Bool(true),
        "the pre-export resource survived the overwrite import: {survived}"
    );
    assert_eq!(
        survived["content"]["edited"],
        Value::Null,
        "…and carries the IN-ZIP (old) content — the import replaced the later edit: {survived}"
    );
    //    …and scratch2 is GONE (absent from the ZIP → deleted), as is
    //    the new-chain scratch3 (it postdated the export too).
    let wiped = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH2_PATH, "--compact"],
    );
    expect_exit(&wiped, 6, "not_found", "resource get scratch2 post-import");
    let wiped3 = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH3_PATH, "--compact"],
    );
    expect_exit(&wiped3, 6, "not_found", "resource get scratch3 post-import");

    // 14. THE delete-surgery witness: `resource delete --yes` then a
    // get is `not_found` (remove_member → overwrite-import).
    expect_ok(
        "resource delete scratch",
        &ign(
            &config,
            &env,
            &[
                "resource",
                "delete",
                &name,
                SCRATCH_PATH,
                "--yes",
                "--compact",
            ],
        ),
    );
    let deleted = ign(
        &config,
        &env,
        &["resource", "get", &name, SCRATCH_PATH, "--compact"],
    );
    expect_exit(&deleted, 6, "not_found", "resource get scratch post-delete");

    // 15. rename + copy (the family's remaining verbs).
    let renamed = timestamped_name("-renamed");
    expect_ok(
        "project rename",
        &ign(
            &config,
            &env,
            &["project", "rename", &name, &renamed, "--compact"],
        ),
    );
    let copied = timestamped_name("-copy");
    expect_ok(
        "project copy",
        &ign(
            &config,
            &env,
            &["project", "copy", &renamed, &copied, "--compact"],
        ),
    );

    // 16. cleanup (best-effort by design — a failure above leaves
    // forensic state under the timestamped names).
    for candidate in [name.as_str(), renamed.as_str(), copied.as_str()] {
        let _ = ign(
            &config,
            &env,
            &["project", "delete", candidate, "--yes", "--compact"],
        )
        .status
        .success();
    }
}

/// The openapi-capture gate (03-RESEARCH Open Question 1): GET
/// `{base}/openapi.json` (authed) and write a trimmed extract of
/// every `/data/api/v1/(projects|scan|resources)` path into the phase
/// dir — the authoritative artifact that settles the resource-family
/// wire-truth question the moment a token exists (02's
/// `openapi-8.3.6-phase2-extract.json` is the precedent file). The
/// projects family is soft-asserted present; whether
/// `/projects/{project}/resources` appears is PRINTED (not asserted)
/// — a negative is the answer, not a failure.
#[tokio::test]
#[ignore = "opt-in: set IGNITION_LIVE_URL + IGNITION_LIVE_TOKEN"]
async fn openapi_capture_writes_phase3_extract() {
    let Some(env) = live_env() else {
        skip("IGNITION_LIVE_URL / IGNITION_LIVE_TOKEN not both set");
        return;
    };

    let url = format!("{}/openapi.json", env.url.trim_end_matches('/'));
    install_crypto_provider();
    let response = reqwest::Client::new()
        .get(&url)
        .header("X-Ignition-API-Token", &env.token)
        .send()
        .await
        .unwrap_or_else(|err| panic!("openapi fetch from {url}: {err}"));
    assert!(
        response.status().is_success(),
        "openapi fetch answered {} — check the token's permissions",
        response.status()
    );
    let spec: Value = response.json().await.expect("openapi.json parses as JSON");

    // The phase-3 families, verbatim from the spec's paths map.
    let families = [
        "/data/api/v1/projects",
        "/data/api/v1/scan",
        "/data/api/v1/resources",
    ];
    let mut trimmed = serde_json::Map::new();
    if let Some(paths) = spec["paths"].as_object() {
        for (path, operations) in paths {
            if families.iter().any(|prefix| path.starts_with(prefix)) {
                trimmed.insert(path.clone(), operations.clone());
            }
        }
    }

    // Soft-assert the projects family; PRINT the resource-endpoint
    // verdict (Open Question 1's answer, whatever it is).
    let projects_present = trimmed
        .keys()
        .any(|path| path.starts_with("/data/api/v1/projects"));
    assert!(
        projects_present,
        "the official openapi carries the projects family — a negative means the spec moved"
    );
    let resources_present = trimmed
        .keys()
        .any(|path| path.contains("/projects/{project}/resources") || path.contains("/resources"));
    println!(
        "project-resources family present in openapi.json: {resources_present} \
         (FALSE settles 03-RESEARCH Open Question 1 against ignition-mcp — \
         re-plan the resource family from the extract)"
    );

    let extract = serde_json::json!({
        "captured_from": url,
        "families": families,
        "path_count": trimmed.len(),
        "project_resources_present": resources_present,
        "info": spec["info"],
        "paths": Value::Object(trimmed),
    });
    let out: PathBuf = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(".planning/phases/03-project-operations/openapi-8.3.6-phase3-extract.json");
    std::fs::write(
        &out,
        serde_json::to_vec_pretty(&extract).expect("extract serializes"),
    )
    .unwrap_or_else(|err| panic!("write {}: {err}", out.display()));
    println!(
        "wrote {} ({} phase-3 paths)",
        out.display(),
        extract["path_count"]
    );
}

/// Non-empty `IGNITION_LIVE_URL_B` — the SECOND gateway (side B of
/// the cross-gateway pair). Absent → the sync witness skips quietly
/// (the 02-01 convention: an unset env is a green no-op).
fn live_url_b() -> Option<String> {
    std::env::var("IGNITION_LIVE_URL_B")
        .ok()
        .filter(|value| !value.trim().is_empty())
}

/// THE cross-gateway sync witness (07-01, SYNC-02): with two live
/// gateways from env, put a differing resource on A, `project diff`
/// it (the resource reports `removed` — B-relative-to-A: in A only),
/// `project sync --resource --yes` it A→B, then re-read on B (the
/// 06-08 adoption oracle — never trust the import's success body) and
/// assert the member bytes match A's. `IGNITION_LIVE_TOKEN` applies
/// to BOTH sides (the documented two-sided-secret caveat) — use
/// per-profile keyring entries for genuinely distinct credentials.
#[tokio::test]
#[ignore = "opt-in: set IGNITION_LIVE_URL + IGNITION_LIVE_URL_B + IGNITION_LIVE_TOKEN + IGNITION_LIVE_MUTATIONS=1"]
async fn project_sync_two_gateways_witness() {
    let Some(env) = live_env_mutations() else {
        skip("IGNITION_LIVE_URL / IGNITION_LIVE_TOKEN / IGNITION_LIVE_MUTATIONS not all set");
        return;
    };
    let Some(url_b) = live_url_b() else {
        skip("IGNITION_LIVE_URL_B not set (no second gateway)");
        return;
    };

    // The two-profile config with BOTH URLs baked in — no
    // IGNITION_URL overlay (it would clobber one side).
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("config.toml");
    std::fs::write(
        &config,
        format!(
            "active = \"dev\"\n\n[profiles.dev]\nurl = \"{}\"\nauth = {{ token_env = \"IGNITION_TOKEN\" }}\n\n[profiles.other]\nurl = \"{}\"\nauth = {{ token_env = \"IGNITION_TOKEN\" }}\n",
            env.url, url_b
        ),
    )
    .expect("write config");

    let ign_two = |args: &[&str]| -> Output {
        let mut command = Command::cargo_bin("ign").expect("binary 'ign' not found");
        command
            .env("IGNITION_CLI_CONFIG", &config)
            .env("IGNITION_TOKEN", &env.token);
        command.args(args).output().expect("spawn ign")
    };

    let name = timestamped_name("-sync");
    let path = "ignition/script-python/uat/synced";

    // 1. The project exists on BOTH gateways.
    expect_ok(
        "project new on A",
        &ign_two(&["--profile", "dev", "project", "new", &name, "--compact"]),
    );
    expect_ok(
        "project new on B",
        &ign_two(&["--profile", "other", "project", "new", &name, "--compact"]),
    );

    // 2. A carries the differing resource; B does not.
    let body_dir = tempfile::tempdir().expect("body dir");
    let body_file = body_dir.path().join("synced.json");
    let body = br#"{"scope":"G","code":"print('promoted by sync')"}"#;
    std::fs::write(&body_file, body).expect("write body");
    expect_ok(
        "resource put on A",
        &ign_two(&[
            "--profile",
            "dev",
            "resource",
            "put",
            &name,
            path,
            "--file",
            body_file.to_str().unwrap(),
            "--yes",
            "--compact",
        ]),
    );

    // 3. The diff names it `removed` (in A only, B-relative-to-A).
    let diff_out = ign_two(&[
        "project",
        "diff",
        "dev",
        "other",
        "--project",
        &name,
        "--compact",
    ]);
    expect_ok("project diff", &diff_out);
    let diff = data_envelope(&diff_out);
    let entries = diff["data"]["entries"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    let entry = entries
        .iter()
        .find(|entry| entry["path"].as_str() == Some(path))
        .unwrap_or_else(|| panic!("diff carries the resource: {diff}"));
    assert_eq!(entry["status"], Value::String("removed".into()));

    // 4. The guarded promotion.
    let sync_out = ign_two(&[
        "project",
        "sync",
        "dev",
        "other",
        "--project",
        &name,
        "--resource",
        path,
        "--yes",
        "--compact",
    ]);
    expect_ok("project sync", &sync_out);
    let synced = data_envelope(&sync_out);
    assert_eq!(
        synced["data"]["synced"],
        Value::Array(vec![Value::String(path.into())]),
        "the synced list names exactly the promoted path: {synced}"
    );

    // 5. THE adoption oracle: B's re-read carries A's bytes (a fresh
    // export under the get — never the import's success body).
    let get_out = ign_two(&[
        "--profile",
        "other",
        "resource",
        "get",
        &name,
        path,
        "--compact",
    ]);
    expect_ok("resource get on B", &get_out);
    let got = data_envelope(&get_out);
    let expected: Value = serde_json::from_slice(body).expect("body parses");
    assert_eq!(
        got["data"]["content"], expected,
        "B adopted A's member content: {got}"
    );

    // 6. Best-effort cleanup on both sides.
    for profile in ["dev", "other"] {
        let _ = ign_two(&[
            "--profile",
            profile,
            "project",
            "delete",
            &name,
            "--yes",
            "--compact",
        ])
        .status
        .success();
    }
}