ignition-cli 1.0.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
//! Opt-in LIVE gate for `ign webdev` (05-03) — dogfoods the BUILT
//! `ign` binary through the full deploy→status→redeploy→scriptExec
//! loop against a real commissioned Ignition 8.3+ gateway.
//!
//! ```text
//! cargo test -p ignition-cli --test e2e_webdev -- --ignored
//! ```
//!
//! Skip behavior (the 02-01 live-suite convention, e2e_projects
//! precedent): 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. The loop MUTATES the gateway (it imports the
//! CLI-owned `ign-cli` project wholesale), so it additionally
//! requires the explicit `IGNITION_LIVE_MUTATIONS=1` opt-in.
//!
//! ## 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 the deploys (webdev deploy imports/overwrites the ign-cli project) |
//!
//! ## The loop's contract pins
//!
//! 1. **status-before-deploy is DATA** — exit 0 whether the routes
//!    are absent (fresh gateway) or present (a re-run); the LOCK from
//!    the contract goldens, witnessed live.
//! 2. **deploy → status all-present** — the version handshake reads
//!    back `ROUTE_BUNDLE_VERSION` on every always-on route.
//! 3. **redeploy clean-replaces** — a second deploy (overwrite=true)
//!    leaves the sweep all-present.
//! 4. **scriptExec ships ONLY on request, gated by the secret** —
//!    `--with-script-exec` generates + persists the secret (0600);
//!    RAW wire probes then witness the security posture: no secret
//!    header → `secret_required`, wrong secret → `secret_mismatch`,
//!    the stored secret → the version handshake (the same posture
//!    the research rig witnessed live).
//! 5. **redaction** — the stored secret appears in NO stdout/stderr
//!    of any spawn (the binary-level proof; the value lives in
//!    exactly one place: the baked zip member + the 0600 config).

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

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

/// The gathered env contract for one live-gateway run (the
/// e2e_projects shape verbatim).
struct LiveEnv {
    url: String,
    token: String,
}

fn live_url() -> Option<String> {
    std::env::var("IGNITION_LIVE_URL")
        .ok()
        .filter(|value| !value.trim().is_empty())
}

fn live_token() -> Option<String> {
    std::env::var("IGNITION_LIVE_TOKEN")
        .ok()
        .filter(|value| !value.trim().is_empty())
}

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

fn live_env_mutations() -> Option<LiveEnv> {
    if std::env::var("IGNITION_LIVE_MUTATIONS").as_deref() != Ok("1") {
        return None;
    }
    match (live_url(), live_token()) {
        (Some(url), Some(token)) => Some(LiveEnv { url, token }),
        _ => None,
    }
}

/// ONE isolated config for the WHOLE loop — the scriptExec secret is
/// generated by the `--with-script-exec` deploy and must persist into
/// the later status/probe steps (that persistence is itself under
/// test).
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 {
    spawn_ign(config, env, args, None, None)
}

/// `ign` with a JSON document piped to stdin (`--file -`).
fn ign_stdin(config: &Path, env: &LiveEnv, args: &[&str], stdin: &str) -> Output {
    spawn_ign(config, env, args, Some(stdin), None)
}

/// The one spawn primitive: env pinning, optional stdin, optional
/// pinned working directory (the default-file export path).
fn spawn_ign(
    config: &Path,
    env: &LiveEnv,
    args: &[&str],
    stdin: Option<&str>,
    cwd: Option<&Path>,
) -> 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);
    if let Some(dir) = cwd {
        command.current_dir(dir);
    }
    command.args(args);
    if let Some(text) = stdin {
        command.write_stdin(text);
    }
    command.output().expect("spawn ign")
}

/// Parse the compact JSON FAILURE envelope from stderr (the
/// first-`{` convention — log-tolerant).
fn err_envelope(out: &Output) -> Value {
    let stderr = String::from_utf8_lossy(&out.stderr);
    let from = stderr.find('{').expect("envelope starts somewhere");
    serde_json::from_str(&stderr[from..]).expect("envelope parses")
}

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}"))
}

/// The row for one route out of a status envelope.
fn status_row<'a>(envelope: &'a Value, route: &str) -> &'a Value {
    envelope["data"]["routes"]
        .as_array()
        .unwrap_or_else(|| panic!("routes[] present: {envelope}"))
        .iter()
        .find(|row| row["route"] == route)
        .unwrap_or_else(|| panic!("{route} row: {envelope}"))
}

/// Read the stored webdev secret back out of the config (test eyes
/// only — the raw-probe oracle; the same read the contract redaction
/// test performs).
fn stored_secret(config: &Path) -> String {
    ignition_core::config::load(config)
        .expect("config reloads")
        .profiles
        .get("dev")
        .and_then(|profile| profile.webdev_secret.clone())
        .expect("the --with-script-exec deploy persisted a secret")
}

/// ONE raw wire probe against the deployed scriptExec route — POST
/// the version action with the gateway token auth and a CHOICE of
/// secret presentation: None (no secret header), Some(secret). The
/// route's answer is the 200 body envelope (denials ride 200 — the
/// seam's first wire rule); the function returns `error.code` on a
/// denial or panics with the body when ok:true.
async fn raw_scriptexec_probe(env: &LiveEnv, secret: Option<&str>) -> Result<(), String> {
    let client = reqwest::Client::new();
    let url = format!("{}/system/webdev/ign-cli/cli/scriptExec", env.url);
    let mut request = client
        .post(&url)
        .header("X-Ignition-API-Token", &env.token)
        .json(&serde_json::json!({"action": "version"}));
    if let Some(secret) = secret {
        request = request.header("X-Ignition-CLI-Secret", secret);
    }
    let response = request.send().await.expect("probe reaches the gateway");
    assert_eq!(
        response.status().as_u16(),
        200,
        "the webdev servlet answers 200 (denials ride the body)"
    );
    let body: Value = response.json().await.expect("envelope parses");
    if body["ok"] == Value::Bool(true) {
        assert_eq!(
            body["data"]["routeVersion"],
            ignition_core::webdev::ROUTE_BUNDLE_VERSION,
            "the handshake version: {body}"
        );
        Ok(())
    } else {
        Err(body["error"]["code"]
            .as_str()
            .unwrap_or("(no code)")
            .to_string())
    }
}

const ALWAYS_ON: [&str; 4] = ["tags", "tagConfig", "alarms", "tagHistory"];

/// THE live loop — order is the contract (see the module docs).
#[tokio::test]
#[ignore = "opt-in e2e: set IGNITION_LIVE_URL + IGNITION_LIVE_TOKEN + IGNITION_LIVE_MUTATIONS=1"]
async fn live_webdev_deploy_status_scriptexec_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);
    // THE serializer: one live gate at a time (shared gateway state).
    let _gate = LIVE_GATE.lock().await;
    let mut all_output = String::new();

    // (1) status BEFORE any deploy: a READ — exit 0 whether the
    // routes are absent (fresh gateway) or present (a re-run against
    // an already-deployed gateway). Degradation is data.
    let out = ign(&config, &env, &["webdev", "status", "--compact"]);
    all_output.push_str(&String::from_utf8_lossy(&out.stdout));
    all_output.push_str(&String::from_utf8_lossy(&out.stderr));
    expect_ok("status before deploy (a read — degradation is data)", &out);
    let envelope = data_envelope(&out);
    for route in ALWAYS_ON {
        let row = status_row(&envelope, route);
        let status = row["status"].as_str().unwrap_or_default();
        assert!(
            [
                "present",
                "absent",
                "unlicensed",
                "auth_gated",
                "version_mismatch"
            ]
            .contains(&status),
            "{route}: a known matrix state, got {row}"
        );
    }

    // (2) deploy → the 4 always-on routes install; status verifies
    // the version handshake on every one.
    let out = ign(&config, &env, &["webdev", "deploy", "--compact"]);
    all_output.push_str(&String::from_utf8_lossy(&out.stdout));
    all_output.push_str(&String::from_utf8_lossy(&out.stderr));
    expect_ok("deploy", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["routes"].as_array().map(Vec::len), Some(4));
    assert_eq!(envelope["data"]["script_exec"], Value::Bool(false));

    let out = ign(&config, &env, &["webdev", "status", "--compact"]);
    all_output.push_str(&String::from_utf8_lossy(&out.stdout));
    all_output.push_str(&String::from_utf8_lossy(&out.stderr));
    expect_ok("status after deploy", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["ok"], Value::Bool(true), "{envelope}");
    for route in ALWAYS_ON {
        let row = status_row(&envelope, route);
        assert_eq!(row["status"], "present", "{route}: {row}");
        assert_eq!(
            row["deployed_version"], row["expected_version"],
            "{route}: the handshake matches: {row}"
        );
    }

    // (3) redeploy → clean replace (overwrite=true); still all-present.
    let out = ign(&config, &env, &["webdev", "deploy", "--compact"]);
    all_output.push_str(&String::from_utf8_lossy(&out.stdout));
    all_output.push_str(&String::from_utf8_lossy(&out.stderr));
    expect_ok("redeploy (clean replace)", &out);
    let out = ign(&config, &env, &["webdev", "status", "--compact"]);
    all_output.push_str(&String::from_utf8_lossy(&out.stdout));
    all_output.push_str(&String::from_utf8_lossy(&out.stderr));
    expect_ok("status after redeploy", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["ok"], Value::Bool(true), "{envelope}");

    // (4) deploy --with-script-exec → 5 routes + a GENERATED secret
    // (fresh config → secret_rotated true); status sweeps 5 rows
    // (scriptExec probed WITH the stored secret).
    let out = ign(
        &config,
        &env,
        &["webdev", "deploy", "--with-script-exec", "--compact"],
    );
    all_output.push_str(&String::from_utf8_lossy(&out.stdout));
    all_output.push_str(&String::from_utf8_lossy(&out.stderr));
    expect_ok("deploy --with-script-exec", &out);
    let envelope = data_envelope(&out);
    assert_eq!(
        envelope["data"]["routes"].as_array().map(Vec::len),
        Some(5),
        "{envelope}"
    );
    assert_eq!(envelope["data"]["script_exec"], Value::Bool(true));
    assert_eq!(envelope["data"]["secret_rotated"], Value::Bool(true));

    let out = ign(&config, &env, &["webdev", "status", "--compact"]);
    all_output.push_str(&String::from_utf8_lossy(&out.stdout));
    all_output.push_str(&String::from_utf8_lossy(&out.stderr));
    expect_ok("status after scriptExec deploy", &out);
    let envelope = data_envelope(&out);
    let script_exec = status_row(&envelope, "scriptExec");
    assert_eq!(script_exec["status"], "present", "{script_exec}");

    // (5) the security posture, RAW on the wire: no secret header →
    // secret_required; wrong secret → secret_mismatch; the STORED
    // secret → the version handshake answers ok.
    let code = raw_scriptexec_probe(&env, None)
        .await
        .expect_err("no header refuses");
    assert_eq!(code, "secret_required", "the fail-closed gate");
    let code = raw_scriptexec_probe(&env, Some("deadbeef-wrong-secret"))
        .await
        .expect_err("wrong secret refuses");
    assert_eq!(code, "secret_mismatch", "constant-time mismatch refusal");
    raw_scriptexec_probe(&env, Some(&stored_secret(&config)))
        .await
        .expect("the stored secret opens the version handshake");

    // (6) redaction — the binary-level proof across EVERY spawn of
    // this loop: the stored secret appears in no output stream.
    let secret = stored_secret(&config);
    assert!(
        !all_output.contains(&secret),
        "redaction: the secret leaked into a spawn's output"
    );
}

/// Best-effort pre-clean (idempotent re-runs): delete a provider
/// with the guarded verb, IGNORE failures (an absent provider is the
/// usual case; the OWN-OCCUPANT convention — a mid-run panic must
/// not poison the next run against the same rig).
fn clean_provider(config: &Path, env: &LiveEnv, provider: &str) {
    let _ = ign(
        config,
        env,
        &["tags", "provider", "delete", provider, "--yes", "--compact"],
    );
}

/// Best-effort pre-clean: delete tag configs, ignoring failures.
fn clean_tag_configs(config: &Path, env: &LiveEnv, paths: &[&str]) {
    let mut args: Vec<&str> = vec!["tags", "config", "delete"];
    args.extend_from_slice(paths);
    args.push("--yes");
    args.push("--compact");
    let _ = ign(config, env, &args);
}

/// THE live-gate serializer: every live test mutates SHARED gateway
/// state (the CLI-owned ign-cli deploy project — five concurrent
/// overwrite-imports race each other — plus tag providers), so the
/// gates hold this lock for their whole body and run ONE AT A TIME
/// within the process (cargo's default parallelism would 409-race
/// the deploys and provider creates; live-proven 05-06).
static LIVE_GATE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// THE tags live loop (05-04) — the first route-consuming family,
/// self-contained: deploy the routes (browse/read/write need them),
/// then provider create → browse root sees it → read/write on a
/// NONEXISTENT path assert the QUALITY passthrough (quality IS data
/// — `Bad_NotFound`/`Bad` come back as exit-0 data, the honest
/// oracle verifiable without mutation side effects) → provider
/// delete cleans up. Provider verbs themselves ride the NATIVE REST
/// (no route dependency).
#[tokio::test]
#[ignore = "opt-in e2e: set IGNITION_LIVE_URL + IGNITION_LIVE_TOKEN + IGNITION_LIVE_MUTATIONS=1"]
async fn live_tags_provider_browse_read_write_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);
    // THE serializer: one live gate at a time (shared gateway state).
    let _gate = LIVE_GATE.lock().await;

    // Routes first: browse/read/write refuse exit 6 without them.
    let out = ign(&config, &env, &["webdev", "deploy", "--compact"]);
    expect_ok("deploy (the tags route's precondition)", &out);

    // Pre-clean a leftover occupant from a prior aborted run.
    clean_provider(&config, &env, "p5e2e");

    // Provider create (NATIVE REST): a STANDARD provider named p5e2e.
    let out = ign(
        &config,
        &env,
        &["tags", "provider", "create", "p5e2e", "--compact"],
    );
    expect_ok("provider create p5e2e", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["name"], "p5e2e");

    // Provider list sees it (native), browse root sees it (route).
    let out = ign(&config, &env, &["tags", "provider", "list", "--compact"]);
    expect_ok("provider list", &out);
    let envelope = data_envelope(&out);
    assert!(
        envelope["data"]["providers"]
            .as_array()
            .expect("providers[]")
            .iter()
            .any(|row| row["name"] == "p5e2e"),
        "p5e2e in the native list: {envelope}"
    );
    let out = ign(&config, &env, &["tags", "browse", "--compact"]);
    expect_ok("browse root", &out);
    let envelope = data_envelope(&out);
    assert!(
        envelope["data"]["entries"]
            .as_array()
            .expect("entries[]")
            .iter()
            .any(|entry| entry["path"] == "[p5e2e]"),
        "browse root contains the fresh provider: {envelope}"
    );

    // Read a NONEXISTENT path: exit 0, the quality passthrough IS
    // the honest oracle (Bad_NotFound(...) — quality never parsed, so
    // a missing tag is DATA, not an error; the LIVE string carries
    // embedded detail: `Bad_NotFound("Path ... not found.")`).
    let out = ign(
        &config,
        &env,
        &["tags", "read", "[p5e2e]DoesNotExist", "--compact"],
    );
    expect_ok("read nonexistent path (quality is data)", &out);
    let envelope = data_envelope(&out);
    assert!(
        envelope["data"]["results"][0]["quality"]
            .as_str()
            .unwrap_or_default()
            .starts_with("Bad_NotFound"),
        "quality is data with embedded detail: {envelope}"
    );

    // Write to the nonexistent path likewise returns a Bad quality
    // (verifiable without mutation side effects on a fresh
    // provider).
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "write",
            "[p5e2e]DoesNotExist",
            "--value",
            "7",
            "--compact",
        ],
    );
    expect_ok("write nonexistent path (quality is data)", &out);
    let envelope = data_envelope(&out);
    assert!(
        envelope["data"]["quality"]
            .as_str()
            .expect("quality present")
            .starts_with("Bad"),
        "a nonexistent target writes Bad quality: {envelope}"
    );

    // Cleanup: the guarded, signature-chained native delete.
    let out = ign(
        &config,
        &env,
        &["tags", "provider", "delete", "p5e2e", "--yes", "--compact"],
    );
    expect_ok("provider delete p5e2e (guarded)", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["deleted"], "p5e2e");
}

/// THE tagConfig live round-trip (05-05) — the research-proven loop
/// that closes TAGS-05/09: config create an Int4 memory tag (value
/// 123) → read back Good/123 (05-04's read IS the oracle) → export
/// the provider → import into a fresh provider (abort first: the
/// second import refuses `tag_collision`, then overwrite --yes
/// replaces) → read the IMPORTED tag == 123/Good (values intact —
/// TAGS-09's live proof) → config delete cleanup → provider deletes.
#[tokio::test]
#[ignore = "opt-in e2e: set IGNITION_LIVE_URL + IGNITION_LIVE_TOKEN + IGNITION_LIVE_MUTATIONS=1"]
async fn live_tags_config_export_import_roundtrip() {
    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);
    // THE serializer: one live gate at a time (shared gateway state).
    let _gate = LIVE_GATE.lock().await;

    // Routes first: every tagConfig verb refuses exit 6 without them.
    let out = ign(&config, &env, &["webdev", "deploy", "--compact"]);
    expect_ok("deploy (the tagConfig route's precondition)", &out);

    // Pre-clean leftovers from a prior aborted run (idempotent).
    for provider in ["p5e2e", "p5import"] {
        clean_provider(&config, &env, provider);
    }

    // Fresh providers for the round-trip (native REST, pre-cleaned).
    for provider in ["p5e2e", "p5import"] {
        let out = ign(
            &config,
            &env,
            &["tags", "provider", "create", provider, "--compact"],
        );
        expect_ok(&format!("provider create {provider}"), &out);
    }

    // Config create: an Int4 memory tag, value 123 (stdin definition —
    // the surgical edit loop's write half).
    let out = ign_stdin(
        &config,
        &env,
        &[
            "tags",
            "config",
            "create",
            "[p5e2e]T1",
            "--file",
            "-",
            "--compact",
        ],
        r#"{"tagType": "AtomicTag", "dataType": "Int4", "value": 123}"#,
    );
    expect_ok("config create [p5e2e]T1", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["quality"], "Good");

    // Read back: Good/123 — 05-04's read verb is the oracle.
    let out = ign(&config, &env, &["tags", "read", "[p5e2e]T1", "--compact"]);
    expect_ok("read [p5e2e]T1", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["results"][0]["quality"], "Good");
    assert_eq!(envelope["data"]["results"][0]["value"], 123);

    // Export the provider subtree → a JSON file.
    let tmp = tempfile::tempdir().expect("tempdir");
    let export_file = tmp.path().join("p5e2e.json");
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "export",
            "[p5e2e]",
            "-o",
            export_file.to_str().expect("path"),
            "--compact",
        ],
    );
    expect_ok("export [p5e2e]", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["tag_count"], 1, "one top-level subtree");
    assert_eq!(envelope["data"]["file"], export_file.display().to_string());

    // Import #1 (abort, clean target): the browse pre-check passes,
    // configure 'a' imports.
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "import",
            "--file",
            export_file.to_str().expect("path"),
            "--provider",
            "p5import",
            "--compact",
        ],
    );
    expect_ok("import #1 (abort, clean target)", &out);
    let envelope = data_envelope(&out);
    // The provider-shaped export wrapper (empty name) lands its
    // CHILDREN at the target — the effective top-level count is the
    // children's (T1 + the provider's _types_ folder).
    assert_eq!(envelope["data"]["imported"], 2, "{envelope}");

    // Import #2 (abort again): the collision refusal — exit 6,
    // tag_collision, BEFORE any write.
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "import",
            "--file",
            export_file.to_str().expect("path"),
            "--provider",
            "p5import",
            "--compact",
        ],
    );
    assert_eq!(
        out.status.code(),
        Some(6),
        "collision refuses exit 6; stdout: {} stderr: {}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let envelope = err_envelope(&out);
    assert_eq!(envelope["error"]["code"], "tag_collision");

    // Import #3 (overwrite --yes): the guarded replace.
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "import",
            "--file",
            export_file.to_str().expect("path"),
            "--provider",
            "p5import",
            "--collision-policy",
            "overwrite",
            "--yes",
            "--compact",
        ],
    );
    expect_ok("import #3 (overwrite --yes)", &out);

    // THE round-trip proof: the imported tag reads back 123/Good —
    // values intact across the export/import interchange.
    let out = ign(
        &config,
        &env,
        &["tags", "read", "[p5import]T1", "--compact"],
    );
    expect_ok("read [p5import]T1 (the round-trip oracle)", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["results"][0]["quality"], "Good");
    assert_eq!(envelope["data"]["results"][0]["value"], 123);

    // Cleanup: config delete both tags (guarded), then the providers.
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "config",
            "delete",
            "[p5e2e]T1",
            "[p5import]T1",
            "--yes",
            "--compact",
        ],
    );
    expect_ok("config delete cleanup", &out);
    for provider in ["p5e2e", "p5import"] {
        let out = ign(
            &config,
            &env,
            &["tags", "provider", "delete", provider, "--yes", "--compact"],
        );
        expect_ok(&format!("provider delete {provider} (guarded)"), &out);
    }
}

// ---- 05-06 live fixtures: the historian/binding spike + the alarm
// lifecycle (TAGS-07/08) ----

/// Wall-clock epoch milliseconds.
fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock after epoch")
        .as_millis() as i64
}

/// The InternalHistorian create path (native config-resource REST —
/// NO database needed, the 05-RESEARCH live-proven recipe).
const HISTORIAN_PROVIDER_PATH: &str =
    "/data/api/v1/resources/com.inductiveautomation.historian/historian-provider";

/// Provision an InternalHistorian via native REST (token auth, the
/// ARRAY body — the tag-provider create precedent). Idempotent: a
/// create that comes back non-OK with an "already exists"-flavored
/// body passes (re-runs against a provisioned rig).
async fn provision_internal_historian(env: &LiveEnv, name: &str) {
    let client = reqwest::Client::new();
    let url = format!("{}{HISTORIAN_PROVIDER_PATH}", env.url);
    let body = serde_json::json!([{
        "name": name,
        "type": "com.inductiveautomation.historian/historian-provider",
        "collection": "core",
        "enabled": true,
        "config": {"profile": {"type": "InternalHistorian"}, "settings": {}}
    }]);
    let response = client
        .post(&url)
        .header("X-Ignition-API-Token", &env.token)
        .json(&body)
        .send()
        .await
        .expect("historian create reaches the gateway");
    let status = response.status().as_u16();
    let text = response.text().await.unwrap_or_default();
    assert!(
        status == 200
            || text.to_lowercase().contains("exist")
            || text.to_lowercase().contains("duplicate"),
        "InternalHistorian create failed (HTTP {status}): {text}"
    );
    println!("historian {name} provisioned (HTTP {status})");
}

/// Delete the InternalHistorian (find → signature → DELETE — the
/// tag-provider delete chain's shape). A find miss means it is
/// already gone.
async fn delete_internal_historian(env: &LiveEnv, name: &str) {
    let client = reqwest::Client::new();
    let find_url = format!("{}{HISTORIAN_PROVIDER_PATH}/find/{name}", env.url);
    let response = client
        .get(&find_url)
        .header("X-Ignition-API-Token", &env.token)
        .send()
        .await
        .expect("historian find reaches the gateway");
    if response.status().as_u16() != 200 {
        println!(
            "historian {name} already gone (find → {})",
            response.status()
        );
        return;
    }
    let record: Value = response.json().await.expect("find record parses");
    let Some(signature) = record.get("signature").and_then(Value::as_str) else {
        println!("historian {name} find record carried no signature — leaving it (manual cleanup)");
        return;
    };
    let delete_url = format!("{}{HISTORIAN_PROVIDER_PATH}/{name}/{signature}", env.url);
    let response = client
        .delete(&delete_url)
        .header("X-Ignition-API-Token", &env.token)
        .send()
        .await
        .expect("historian delete reaches the gateway");
    println!(
        "historian {name} deleted (HTTP {})",
        response.status().as_u16()
    );
}

/// Do the history rows carry ANY non-null value cell (beyond the
/// t_stamp column)? The spike's data oracle.
fn history_has_data(envelope: &Value) -> bool {
    let Some(rows) = envelope["data"]["rows"].as_array() else {
        return false;
    };
    rows.iter().any(|row| {
        row.as_array()
            .map(|cells| cells.iter().skip(1).any(|cell| !cell.is_null()))
            .unwrap_or(false)
    })
}

/// THE tag-history live fixture + binding spike (05-06, TAGS-08 —
/// 05-RESEARCH Open Question 1, bounded ≤30 min by construction):
///
/// 1. provision `InternalHistorian` `p5hist` via native REST (no
///    database, the live-proven recipe),
/// 2. configure one Int4 tag with `historyEnabled` +
///    `historicalProvider` through the deployed tagConfig route,
/// 3. write values, then query `ign tags history query`,
/// 4. THE SPIKE: null values trigger the three documented
///    candidates in order — (1) execution scan-class keys in the
///    configure shape, (2) wider windows + aggregationMode
///    variations, (3) a browseHistoricalTags cross-check. A winner
///    is printed + pinned as a comment; NO winner asserts the
///    STRUCTURAL outcome only (columns present, no error, null
///    values — the research pre-cleared this fallback; query
///    capability is the phase criterion, never hang on the spike).
#[tokio::test]
#[ignore = "opt-in e2e: set IGNITION_LIVE_URL + IGNITION_LIVE_TOKEN + IGNITION_LIVE_MUTATIONS=1"]
async fn live_tags_history_historian_and_binding_spike() {
    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);
    // THE serializer: one live gate at a time (shared gateway state).
    let _gate = LIVE_GATE.lock().await;
    let tag = "[default]P5H/T1";

    // Pre-clean leftovers from a prior aborted run (idempotent):
    // the tag first (create over an existing node would abort), then
    // the historian.
    clean_tag_configs(&config, &env, &[tag]);
    delete_internal_historian(&env, "p5hist").await;

    // Routes first: history query refuses exit 6 without them.
    let out = ign(&config, &env, &["webdev", "deploy", "--compact"]);
    expect_ok("deploy (the tagHistory route's precondition)", &out);

    // (1) The historian — native REST, no database.
    provision_internal_historian(&env, "p5hist").await;

    // (2) The history-enabled Int4 tag (the research's stored shape:
    // historyEnabled + historicalProvider BOTH at the top level).
    let out = ign_stdin(
        &config,
        &env,
        &["tags", "config", "create", tag, "--file", "-", "--compact"],
        r#"{"tagType": "AtomicTag", "dataType": "Int4", "value": 0, "historyEnabled": true, "historicalProvider": "p5hist"}"#,
    );
    expect_ok("config create the history-enabled tag", &out);

    // (3) Write values (spaced so a sampling historian can catch
    // distinct values), then query.
    let start_ms = now_ms() - 5_000;
    for value in [7, 8, 9] {
        let out = ign(
            &config,
            &env,
            &[
                "tags",
                "write",
                tag,
                "--value",
                &value.to_string(),
                "--compact",
            ],
        );
        expect_ok("write a history value", &out);
        tokio::time::sleep(std::time::Duration::from_millis(1_100)).await;
    }
    let end_ms = now_ms() + 5_000;
    // The query argv builder (String args — the value-typed flags
    // need formatting; spawn converts to &str).
    let query_args = |start_ms: i64, end_ms: i64, aggregation: Option<&str>| {
        let mut args: Vec<String> = vec![
            "tags".into(),
            "history".into(),
            "query".into(),
            tag.into(),
            "--start".into(),
            start_ms.to_string(),
            "--end".into(),
            end_ms.to_string(),
        ];
        if let Some(mode) = aggregation {
            args.push("--aggregation".into());
            args.push(mode.into());
        }
        args.push("--compact".into());
        args
    };
    let query = |config: &std::path::Path,
                 env: &LiveEnv,
                 start_ms: i64,
                 end_ms: i64,
                 aggregation: Option<&str>| {
        let args = query_args(start_ms, end_ms, aggregation);
        let refs: Vec<&str> = args.iter().map(String::as_str).collect();
        ign(config, env, &refs)
    };
    let out = query(&config, &env, start_ms, end_ms, None);
    expect_ok("history query (base shape)", &out);
    let envelope = data_envelope(&out);
    let columns = envelope["data"]["columns"]
        .as_array()
        .cloned()
        .unwrap_or_default();
    assert_eq!(
        columns.first().and_then(Value::as_str),
        Some("t_stamp"),
        "{envelope}"
    );
    // LIVE-DISCOVERED (05-06): history tag columns ride PROVIDER-RELATIVE
    // (the bracket is stripped — `[default]P5H/T1` surfaces as `P5H/T1`);
    // t_stamp is preserved exactly, never renamed.
    let relative = tag
        .trim_start_matches('[')
        .split_once(']')
        .map(|(_, rest)| rest);
    assert!(
        columns
            .iter()
            .any(|column| column.as_str() == relative && relative.is_some()),
        "the tag column rides provider-relative: {envelope}"
    );

    if history_has_data(&envelope) {
        // SPIKE RESOLVED at the base shape.
        println!(
            "SPIKE RESOLVED (base shape): historyEnabled + historicalProvider on an Int4 tag \
             with a REST-provisioned InternalHistorian produces DATA — pin this shape \
             (see the comment at this fixture in e2e_webdev.rs)"
        );
        // PIN: the base binding shape is
        //   {tagType: AtomicTag, dataType: Int4, historyEnabled: true,
        //    historicalProvider: <name>} + InternalHistorian via native REST.
    } else {
        println!("SPIKE: base shape returned null values — trying the documented candidates");
        let mut resolved: Option<String> = None;

        // Candidate 1: execution scan-class keys in the configure
        // shape (edit = full node config under 'o' — carry the base
        // keys, add the execution block).
        let out = ign_stdin(
            &config,
            &env,
            &["tags", "config", "edit", tag, "--file", "-", "--compact"],
            r#"{"tagType": "AtomicTag", "dataType": "Int4", "value": 9, "historyEnabled": true, "historicalProvider": "p5hist", "execution": {"mode": "TagGroup", "rate": 1000}}"#,
        );
        expect_ok("candidate 1: execution scan-class edit", &out);
        let out = ign(
            &config,
            &env,
            &["tags", "write", tag, "--value", "11", "--compact"],
        );
        expect_ok("candidate 1: write", &out);
        tokio::time::sleep(std::time::Duration::from_millis(2_500)).await;
        let out = query(&config, &env, start_ms, end_ms, None);
        expect_ok("candidate 1: query", &out);
        let envelope = data_envelope(&out);
        if history_has_data(&envelope) {
            resolved = Some("candidate 1: execution scan-class keys in the configure shape".into());
        }

        // Candidate 2: wider window + aggregationMode variations.
        if resolved.is_none() {
            let wide_start = now_ms() - 600_000;
            let wide_end = now_ms() + 5_000;
            for mode in ["Average", "MinMax", "DurationOn"] {
                let out = query(&config, &env, wide_start, wide_end, Some(mode));
                expect_ok(&format!("candidate 2: query ({mode})"), &out);
                let envelope = data_envelope(&out);
                if history_has_data(&envelope) {
                    resolved = Some(format!(
                        "candidate 2: aggregationMode {mode} on a 10-minute window"
                    ));
                    break;
                }
            }
        }

        // Candidate 3: browseHistoricalTags cross-check — the
        // historian registered? (Diagnostic: proves the provider is
        // alive even when the tag binding is not.)
        let out = ign(
            &config,
            &env,
            &["tags", "browse", "histprov:p5hist", "--compact"],
        );
        let historian_registered = out.status.success()
            && data_envelope(&out)["data"]["entries"]
                .as_array()
                .is_some_and(|entries| !entries.is_empty());
        println!(
            "candidate 3 cross-check: histprov:p5hist browse {}",
            if historian_registered {
                "ANSWERS (the historian is registered)"
            } else {
                "answered empty (the historian is registered but holds no tags)"
            }
        );

        match resolved {
            Some(winner) => println!("SPIKE RESOLVED: {winner} — pin the winning shape"),
            None => {
                // The pre-cleared fallback: the STRUCTURAL outcome is
                // the assertion (t_stamp + tag columns, no error);
                // null values are the documented limitation.
                println!(
                    "SPIKE OUTCOME (no winner): history query is structurally working \
                     (t_stamp + tag columns, exit 0) but the tag↔historian DATA binding \
                     remains unresolved after all documented candidates — recorded as a \
                     documented limitation (README 'Tag history'); the Designer-diff \
                     follow-up (create one history tag by hand in the Designer, getConfig \
                     it via this CLI, diff the shapes) is the resolution path"
                );
            }
        }
    }

    // Cleanup (self-cleaning): the tag, then the historian.
    let out = ign(
        &config,
        &env,
        &["tags", "config", "delete", tag, "--yes", "--compact"],
    );
    expect_ok("config delete the history tag", &out);
    delete_internal_historian(&env, "p5hist").await;
}

/// THE alarm lifecycle live fixture (05-06, TAGS-07) — configure a
/// tag with a LIST-form alarm (AboveValue 100, High — the
/// research-proven configure shape) → write past the setpoint →
/// poll `alarms active` until the event appears (bounded) → ack with
/// note+username (the 3-arg form) → assert the state flip to
/// `Active, Acknowledged` + the remainder shape → the history leg
/// (a default rig asserts the honest `alarm_journal_missing`
/// refusal LIVE — the pinned default-rig path; a journal-provisioned
/// rig asserts rows) → the journal stretch is SKIP-WITH-REASON (the
/// sidecar-postgres chain is documented in the README; the wiremock
/// pins carry the capability proof).
#[tokio::test]
#[ignore = "opt-in e2e: set IGNITION_LIVE_URL + IGNITION_LIVE_TOKEN + IGNITION_LIVE_MUTATIONS=1"]
async fn live_tags_alarm_lifecycle() {
    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);
    // THE serializer: one live gate at a time (shared gateway state).
    let _gate = LIVE_GATE.lock().await;
    let tag = "[p5alarm]AlarmTag";

    // Routes first: every alarms verb refuses exit 6 without them.
    let out = ign(&config, &env, &["webdev", "deploy", "--compact"]);
    expect_ok("deploy (the alarms route's precondition)", &out);

    // Pre-clean a leftover occupant from a prior aborted run.
    clean_provider(&config, &env, "p5alarm");

    // Fresh provider (native REST, self-cleaning).
    let out = ign(
        &config,
        &env,
        &["tags", "provider", "create", "p5alarm", "--compact"],
    );
    expect_ok("provider create p5alarm", &out);

    // Configure the alarmed tag: alarms are a LIST (the name-keyed
    // dict form is silently ignored — 05-RESEARCH's live finding).
    let out = ign_stdin(
        &config,
        &env,
        &["tags", "config", "create", tag, "--file", "-", "--compact"],
        r#"{"tagType": "AtomicTag", "dataType": "Int4", "value": 0, "alarms": [{"name": "HighLimit", "enabled": true, "mode": "AboveValue", "setpointA": 100, "priority": "High"}]}"#,
    );
    expect_ok("config create the alarmed tag", &out);

    // Trigger: write past the setpoint.
    let out = ign(
        &config,
        &env,
        &["tags", "write", tag, "--value", "150", "--compact"],
    );
    expect_ok("write past the setpoint", &out);

    // Poll `alarms active` until the event appears (bounded).
    let find_event = |envelope: &Value| -> Option<Value> {
        envelope["data"]["alarms"].as_array().and_then(|alarms| {
            alarms
                .iter()
                .find(|alarm| {
                    alarm["source"]
                        .as_str()
                        .is_some_and(|source| source.contains("p5alarm"))
                })
                .cloned()
        })
    };
    let mut event = None;
    for _ in 0..20 {
        let out = ign(&config, &env, &["tags", "alarms", "active", "--compact"]);
        expect_ok("alarms active poll", &out);
        let envelope = data_envelope(&out);
        if let Some(found) = find_event(&envelope) {
            event = Some(found);
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    }
    let event = event.expect("the alarm event appeared (bounded retries)");
    let event_id = event["event_id"]
        .as_str()
        .expect("event_id present")
        .to_string();
    assert!(
        event["state"]
            .as_str()
            .unwrap_or_default()
            .contains("Unacknowledged"),
        "the fresh event is Active, Unacknowledged: {event}"
    );
    assert_eq!(event["priority"], "High", "{event}");
    println!(
        "alarm active: {event_id} {}",
        event["state"].as_str().unwrap_or_default()
    );

    // Acknowledge: the 3-arg form (note + username explicit).
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "alarms",
            "ack",
            &event_id,
            "--note",
            "e2e lifecycle ack",
            "--username",
            "ign-e2e",
            "--compact",
        ],
    );
    expect_ok("alarms ack (3-arg form)", &out);
    let envelope = data_envelope(&out);
    assert_eq!(envelope["data"]["acknowledged"], 1, "{envelope}");
    assert_eq!(
        envelope["data"]["unacknowledged"].as_array().map(Vec::len),
        Some(0),
        "empty remainder: {envelope}"
    );

    // The state flip: poll active until 'Active, Acknowledged'.
    let mut acknowledged = false;
    for _ in 0..20 {
        let out = ign(&config, &env, &["tags", "alarms", "active", "--compact"]);
        expect_ok("alarms active poll (ack)", &out);
        let envelope = data_envelope(&out);
        if let Some(event) = find_event(&envelope)
            && event["state"]
                .as_str()
                .is_some_and(|state| state.contains("Acknowledged"))
        {
            assert!(
                event["state"]
                    .as_str()
                    .unwrap_or_default()
                    .contains("Active"),
                "the acked alarm stays active until cleared: {event}"
            );
            acknowledged = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    }
    assert!(acknowledged, "the event flipped to 'Active, Acknowledged'");
    println!("alarm acked: state flipped to Active, Acknowledged");

    // The history leg: a DEFAULT rig asserts the honest refusal LIVE
    // (exit 6 + alarm_journal_missing — the pinned default-rig
    // path); a journal-provisioned rig asserts rows instead.
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "alarms",
            "history",
            "--start",
            &(now_ms() - 600_000).to_string(),
            "--end",
            &now_ms().to_string(),
            "--compact",
        ],
    );
    if out.status.code() == Some(6) {
        let envelope = err_envelope(&out);
        assert_eq!(
            envelope["error"]["code"], "alarm_journal_missing",
            "the default-rig refusal is the journal slug: {envelope}"
        );
        println!(
            "alarm history: default-rig honest refusal pinned live \
             (alarm_journal_missing, exit 6 — the actionable journal-chain hint)"
        );
    } else {
        expect_ok("alarms history (journal-provisioned rig)", &out);
        let envelope = data_envelope(&out);
        println!(
            "alarm history: journal answered ({} row(s)) — the provisioned path",
            envelope["data"]["count"]
        );
    }

    // The journal stretch: SKIP-WITH-REASON (the documented
    // sidecar-postgres chain lives in the README; the wiremock pins
    // carry the capability proof).
    println!(
        "journal provisioning stretch: skipped — the chain (sidecar postgres container → \
         database-connection resource → alarm-journal profile → general-alarm-settings \
         singleton) is documented in the README 'Alarm history' section; provision it \
         manually and re-run to walk the provisioned path above"
    );

    // Cleanup (self-cleaning): quiet the tag value, delete the tag,
    // delete the provider.
    let _ = ign(
        &config,
        &env,
        &["tags", "write", tag, "--value", "0", "--compact"],
    );
    let out = ign(
        &config,
        &env,
        &["tags", "config", "delete", tag, "--yes", "--compact"],
    );
    expect_ok("config delete the alarmed tag", &out);
    let out = ign(
        &config,
        &env,
        &[
            "tags",
            "provider",
            "delete",
            "p5alarm",
            "--yes",
            "--compact",
        ],
    );
    expect_ok("provider delete p5alarm (guarded)", &out);
}