ignition-core 1.7.0

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
//! The WebDev client seam (05-03) — the CLI's own gateway-side
//! surface at `/system/webdev/{project}/cli/{route}` (NOT
//! `/data/webdev/*` — that prefix does not exist; 05-RESEARCH wire
//! protocol, live-proven on 8.3.3).
//!
//! This module owns the seam's PURE pieces so the trait impl in
//! [`super`] stays thin delegation (the per-capability-file
//! convention): the ONE path builder ([`route_url`]), the
//! presence/version discrimination enum ([`RouteProbe`]), the
//! shared 200-body envelope parser ([`parse_route_body`]) and its
//! taxonomy mapping ([`denial_to_error`]), and the deploy zip
//! builder ([`build_deploy_zip`]).
//!
//! THE wire rules pinned here (05-RESEARCH, all live-proven):
//! - **405 = absent, NOT 404** — missing routes AND missing projects
//!   both answer 405 (Pitfall 1; doctor's Phase-2 404 assumption was
//!   wrong and 05-03 re-pins it).
//! - **402 = module unlicensed** — a trial-expired gateway's WebDev
//!   servlet answers 402 with an HTML page (cross-verified 8.3.6).
//! - **Denials ride HTTP 200** — WebDev IGNORES a `status` key in
//!   route returns; every refusal is detectable only from the body
//!   envelope `{ok, data|error}`. The status code alone is NEVER a
//!   success verdict (Pitfall 2).
//!
//! [`build_deploy_zip`] packs the embedded 05-01 bundle
//! ([`crate::webdev`]) into the project-zip the deploy action
//! uploads through the 03-02 import machinery — scriptExec ONLY with
//! a SUBSTITUTED secret (fail closed: the template's placeholder
//! must never ship, the 05-01 structural guarantee enforced here at
//! the type level).

use std::io::Write;

use serde_json::Value;

use crate::error::CoreError;
use crate::webdev as bundle;

/// The deploy project the CLI owns wholesale — born from the first
/// deploy zip, overwrite-replaced by every later deploy (05-RESEARCH
/// deploy guidance; `--project` overrides it deliberately).
pub const DEFAULT_PROJECT: &str = "ign-cli";

/// The scriptExec route folder's zip root (the template's static
/// siblings — 05-01 embedded only the doPost.py TEMPLATE in
/// `crate::webdev`, so the two gate files embed HERE, at the seam
/// that packs them).
const SCRIPT_EXEC_ROUTE_ROOT: &str = "com.inductiveautomation.webdev/resources/cli/scriptExec";
const SCRIPT_EXEC_RESOURCE_JSON: &str = include_str!(
    "../../webdev/routes/com.inductiveautomation.webdev/resources/cli/scriptExec/resource.json"
);
const SCRIPT_EXEC_CONFIG_JSON: &str = include_str!(
    "../../webdev/routes/com.inductiveautomation.webdev/resources/cli/scriptExec/config.json"
);

/// The always-on route folders, in manifest order — DERIVED from
/// [`bundle::ROUTE_FILES`] so the deploy set, the status sweep, and
/// the manifest itself can never drift apart.
pub fn always_on_routes() -> Vec<String> {
    let mut routes = Vec::new();
    for (name, _) in bundle::ROUTE_FILES {
        let Some(rest) = name.strip_prefix("com.inductiveautomation.webdev/resources/cli/") else {
            continue;
        };
        if let Some((route, file)) = rest.rsplit_once('/')
            && file == "doPost.py"
            && !routes.iter().any(|known: &String| known == route)
        {
            routes.push(route.to_string());
        }
    }
    routes
}

/// Path builder: `/system/webdev/{project}/cli/{route}` — the `cli/`
/// folder segment is PART of the route folder path (the wire
/// protocol's URL shape; the `cli` folder groups the CLI's routes
/// inside the deploy project).
pub(crate) fn route_url(project: &str, route: &str) -> String {
    format!("/system/webdev/{project}/cli/{route}")
}

/// The testing bundle's URL space — `/system/webdev/{project}/testing/
/// {route}` (the `run`/`tags` folders live BESIDE `cli/`, not under
/// it; ADOPT-04).
pub(crate) fn testing_route_url(project: &str, route: &str) -> String {
    format!("/system/webdev/{project}/testing/{route}")
}

/// `POST …/testing/run` with `{"discover": true}` — the module list
/// (the route is POST-ONLY: the two-method doGet+doPost config does
/// not register on live 8.3.6 — both methods read disabled → 501;
/// live-pinned, so discover rides the POST body). Answers
/// `{"discovered_modules": [...], "count": N}`.
pub async fn testing_discover(
    api: &super::ReqwestGatewayApi,
    project: &str,
) -> Result<serde_json::Value, CoreError> {
    api.post_json(
        &testing_route_url(project, "run"),
        &serde_json::json!({ "discover": true }),
    )
    .await?
    .json::<serde_json::Value>()
    .await
    .map_err(|err| {
        CoreError::Internal(format!(
            "testing discover response did not match the expected shape: {err}"
        ))
    })
}

/// `POST …/testing/run` — execute tests (`{"module"|"package"|"format"}`
/// body; empty body = run_all). The doPost sets HTTP 207 on
/// failures/errors and 200 on green — BOTH are classified-success
/// shapes here; the pass/fail verdict rides the BODY
/// (`passed/failed/errors/total`), never the status line (the
/// module's own Pitfall-2 rule).
pub async fn testing_run(
    api: &super::ReqwestGatewayApi,
    project: &str,
    body: &serde_json::Value,
) -> Result<serde_json::Value, CoreError> {
    let response = api
        .post_json(&testing_route_url(project, "run"), body)
        .await?;
    response.json::<serde_json::Value>().await.map_err(|err| {
        CoreError::Internal(format!(
            "testing run response did not match the expected shape: {err}"
        ))
    })
}

/// The TESTING bundle's presence discrimination (QUICK-p0g) — the
/// [`RouteProbe`] twin for the `testing/` URL space. A SEPARATE enum
/// on purpose: `RouteProbe`'s variant set is pinned by the webdev
/// tests and the two route families answer different shapes (the
/// testing routes have no `{ok, data|error}` envelope and no
/// `routeVersion` handshake).
///
/// WHY a raw-status path exists at all: [`super::classify::classify`]
/// maps 404 → `NotFound` and collapses **405, 500 and 501** into
/// `Internal` (exit 1, no status preserved). Running the presence
/// check through it would make "the testing bundle was never
/// deployed" (a target-state refusal, exit 6) indistinguishable from
/// a CLI bug — so the status code IS the answer here, the
/// [`super::GatewayApi::webdev_route_probe`] precedent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TestingProbe {
    /// 2xx — the bundle answers; the parsed discover body rides along
    /// so the probe doubles as the discover round trip.
    Present {
        /// The `{"discovered_modules": [...], "count": N}` answer.
        discovered: serde_json::Value,
    },
    /// 404 | 405 | 501 — the bundle is not deployed in this project.
    /// All three are absent markers: 405 is the live-proven 8.3
    /// WebDev marker for a missing route folder, 404 appears when the
    /// project itself is absent on some paths, and 501 is what a
    /// route whose methods failed to register answers.
    Absent,
    /// 402 — the WebDev module is installed but unlicensed.
    Unlicensed,
    /// 401 | 403 — something answers but rejects the credential.
    AuthGated {
        /// The rejecting status, preserved for the error.
        status: u16,
    },
    /// 500 — the first-touch lazy-compile blowup (a freshly deployed
    /// route can answer 500 on its FIRST request while WebDev
    /// compiles the module; live-pinned in `actions::adopt`). The
    /// body rides along so a SECOND 500 can be reported honestly.
    LazyCompile {
        /// The route's 500 body, verbatim.
        body: String,
    },
}

/// `POST …/testing/run` with `{"discover": true}` through the RAW
/// transport — the presence probe. Only transport failures are
/// errors; every status the gateway answered maps onto a
/// [`TestingProbe`] variant (or an `Internal` naming the status when
/// the enum has no variant for it).
pub async fn testing_probe(
    api: &super::ReqwestGatewayApi,
    project: &str,
) -> Result<TestingProbe, CoreError> {
    let (url, response) = api
        .testing_post_raw(project, "run", &serde_json::json!({"discover": true}))
        .await?;
    let status = response.status();
    if status.is_success() {
        let text = response.text().await.unwrap_or_default();
        let discovered = serde_json::from_str::<Value>(&text).map_err(|err| {
            CoreError::Internal(format!(
                "testing discover response did not match the expected shape: {err}"
            ))
        })?;
        return Ok(TestingProbe::Present { discovered });
    }
    match status.as_u16() {
        401 | 403 => Ok(TestingProbe::AuthGated {
            status: status.as_u16(),
        }),
        402 => Ok(TestingProbe::Unlicensed),
        404 | 405 | 501 => Ok(TestingProbe::Absent),
        500 => Ok(TestingProbe::LazyCompile {
            body: response.text().await.unwrap_or_default(),
        }),
        other => Err(CoreError::Internal(format!(
            "unexpected HTTP {other} from the testing route probe at {url}"
        ))),
    }
}

/// The presence/version discrimination — the probe enum. The status
/// code IS the answer (deliberately NOT run through classify, the
/// [`super::GatewayApi::webdev_route_status`] precedent); only
/// transport failures are errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RouteProbe {
    /// 200 + ok body from the version action: deployed and answering
    /// its handshake `routeVersion`.
    Present {
        /// The route's `routeVersion` handshake answer.
        route_version: String,
    },
    /// 405 — the live-proven 8.3 absent marker (missing route or
    /// missing project; NOT 404).
    Absent,
    /// 402 — the WebDev module is installed but unlicensed
    /// (trial-expired gateway).
    Unlicensed,
    /// 401/403 — something answers at the path but rejects the
    /// credential: present but auth-gated (research Open Question 4's
    /// resolution: report, never conflate with absent).
    AuthGated,
    /// 200 body denial (`{ok:false, error{code,message}}`) — present
    /// and refusing: the scriptExec gate's `secret_required` /
    /// `secret_mismatch`, or any other stable route-contract code.
    Denied {
        /// The route's machine error code (05-01 contract).
        code: String,
        /// The route's human message.
        message: String,
        /// The route's Python traceback, when the denial carries one
        /// (the envelope's optional `error.traceback` — surfaced so
        /// route-side exceptions are not a black box, 05-08).
        traceback: Option<String>,
    },
}

/// The 200-body verdict shared by [`super::GatewayApi::webdev_route_call`]
/// and [`super::GatewayApi::webdev_route_probe`].
#[derive(Debug)]
pub(crate) enum RouteBody {
    /// `ok:true` — `data` (Null when the route sent none).
    Ok(Value),
    /// `ok:false` — the route's structured refusal (traceback when
    /// the envelope carried one).
    Denied {
        code: String,
        message: String,
        traceback: Option<String>,
    },
}

/// Parse a 200 body as the route envelope. A body that is not the
/// `{ok, data|error}` shape is an internal-class honesty error — the
/// CLI's own routes ALWAYS answer the envelope, so anything else
/// means the path is not ours (a foreign route or an HTML error page
/// that smuggled past the status line). Missing `error` fields
/// degrade to the route contract's generic `route_error` code rather
/// than guessing.
pub(crate) fn parse_route_body(body: &str) -> Result<RouteBody, CoreError> {
    let value: Value = serde_json::from_str(body).map_err(|err| {
        CoreError::Internal(format!(
            "webdev route answered a body that is not the {{ok, data|error}} envelope: {err}"
        ))
    })?;
    if value.get("ok").and_then(Value::as_bool) == Some(true) {
        Ok(RouteBody::Ok(
            value.get("data").cloned().unwrap_or(Value::Null),
        ))
    } else {
        let code = value
            .pointer("/error/code")
            .and_then(Value::as_str)
            .unwrap_or("route_error")
            .to_string();
        let message = value
            .pointer("/error/message")
            .and_then(Value::as_str)
            .unwrap_or("(the route sent no message)")
            .to_string();
        let traceback = value
            .pointer("/error/traceback")
            .and_then(Value::as_str)
            .map(str::to_string);
        Ok(RouteBody::Denied {
            code,
            message,
            traceback,
        })
    }
}

/// Map a body denial onto the taxonomy: the route contract's
/// `not_found` code reuses the existing [`CoreError::NotFound`] slug
/// (it means exactly that — the named thing is absent); the alarms
/// route's `no_alarm_journal` maps to the actionable
/// [`CoreError::AlarmJournalMissing`] (default rigs ALWAYS deny
/// history there — the missing journal chain is target state, not a
/// route bug, 05-06); every other code — known-but-unmapped like
/// `secret_required`, or unknown from a future route — rides
/// [`CoreError::WebdevRouteError`] with code + message verbatim, the
/// stable contract agents branch on. A denial that carried a
/// traceback gets it appended to the message
/// (`"\nroute traceback: {tb}"`) — the route-side exception is
/// visible instead of a black box (05-08); without one the message
/// is byte-identical to the pre-traceback era.
pub(crate) fn denial_to_error(
    code: &str,
    message: &str,
    traceback: Option<&str>,
    endpoint: String,
) -> CoreError {
    match code {
        "not_found" => CoreError::NotFound {
            endpoint: Some(endpoint),
        },
        "no_alarm_journal" => CoreError::AlarmJournalMissing {
            endpoint: Some(endpoint),
        },
        // The tagConfig route's provider-root refusal (07-06): the
        // route detects the bracket form pre-call and translates the
        // bare form's 'No RpcContext' throw — the honest
        // platform-limitation slug over a generic route error (the
        // no_alarm_journal seam precedent).
        "provider_root_unsupported" => CoreError::ProviderRootUnsupported {
            endpoint: Some(endpoint),
        },
        _ => {
            let mut full = message.to_string();
            if let Some(traceback) = traceback {
                full.push_str("\nroute traceback: ");
                full.push_str(traceback);
            }
            CoreError::WebdevRouteError {
                code: code.to_string(),
                message: full,
                endpoint: Some(endpoint),
            }
        }
    }
}

/// Pack the deploy zip: the embedded always-on bundle VERBATIM (the
/// project title substituted into `project.json`'s `title` ONLY when
/// `project_title` differs from [`DEFAULT_PROJECT`] — the manifest
/// already says `ign-cli`), plus — when `with_script_exec` —
/// scriptExec's three members with the secret SUBSTITUTED into the
/// template's `__IGN_CLI_SECRET__` marker (exactly-once replace; the
/// 05-01 contract test pins the marker count).
///
/// FAIL CLOSED: `with_script_exec` + `None` secret is an internal
/// bug guard (the deploy action generates the secret BEFORE packing;
/// shipping the unsubstituted template would arm the gate with the
/// publicly-known placeholder). `Some` WITHOUT `with_script_exec` is
/// tolerated and ignored — a stored profile secret never forces a
/// scriptExec deploy.
///
/// `with_testing` appends the embedded TESTING bundle
/// ([`bundle::testing::TESTING_FILES`]) after the always-on routes —
/// the Jython framework + `testing/run`/`testing/tags` WebDev routes,
/// with every `__IGN_CLI_PROJECT__` marker substituted for
/// `project_title` (the scriptExec marker pattern, count-pinned).
///
/// Members ride fixed `SimpleFileOptions` + deflate (the 05-02
/// deterministic-zip convention) so identical inputs pack
/// identically.
pub fn build_deploy_zip(
    project_title: &str,
    with_script_exec: bool,
    secret: Option<&str>,
    with_testing: bool,
) -> Result<Vec<u8>, CoreError> {
    build_deploy_zip_with(project_title, with_script_exec, secret, with_testing, None)
}

/// The install values of the tagDelete route (26-17, D-13). `secret` is
/// CLI-minted and never output; `Debug` redacts it.
#[derive(Clone, PartialEq, Eq)]
pub struct TagDeleteInstall {
    /// The deploy-time secret: 64 lowercase hex characters.
    pub secret: String,
    /// The WebDev user source the route authenticates against.
    pub user_source: String,
    /// The role WebDev requires of the caller.
    pub role: String,
    /// The provider allowlist (the project's owned providers).
    pub providers: Vec<String>,
}

impl std::fmt::Debug for TagDeleteInstall {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TagDeleteInstall")
            .field("secret", &"<redacted>")
            .field("user_source", &self.user_source)
            .field("role", &self.role)
            .field("providers", &self.providers)
            .finish()
    }
}

/// The tagDelete route folder's zip root.
const TAG_DELETE_ROUTE_ROOT: &str = "com.inductiveautomation.webdev/resources/cli/tagDelete";

/// The prefix every tagDelete install marker shares; none may remain in a
/// packed member.
const TAG_DELETE_MARKER_PREFIX: &str = "__IGN_TAG_DELETE_";

/// Check a tagDelete install before it is packed: `invalid_input` naming
/// the field. The secret is 64 lowercase hex (its value is never echoed);
/// user source and role are 1 to 64 characters of ASCII letters, digits,
/// space, `_`, `-`, `.`; providers are non-empty, unique by ASCII case,
/// none `System`, none holding a quote, a backslash or a control character.
pub fn validate_tag_delete_install(install: &TagDeleteInstall) -> Result<(), CoreError> {
    let invalid = |reason: String| Err(CoreError::InvalidInput { reason });
    if install.secret.len() != 64
        || !install
            .secret
            .bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
    {
        return invalid("tag delete secret: must be 64 lowercase hex characters".into());
    }
    for (field, value) in [
        ("tag delete user source", &install.user_source),
        ("tag delete role", &install.role),
    ] {
        let len = value.chars().count();
        let charset_ok = value
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '_' | '-' | '.'));
        if !(1..=64).contains(&len) || !charset_ok {
            return invalid(format!(
                "{field} {value:?}: must be 1 to 64 characters of ASCII letters, digits, \
                 space, '_', '-' or '.'"
            ));
        }
    }
    if install.providers.is_empty() {
        return invalid(
            "tag delete providers: the allowlist must name at least one provider".into(),
        );
    }
    for (i, provider) in install.providers.iter().enumerate() {
        if provider.is_empty() {
            return invalid(format!(
                "tag delete providers[{i}]: the provider name is empty"
            ));
        }
        if provider.eq_ignore_ascii_case("System") {
            return invalid(format!(
                "tag delete providers[{i}]: the System provider is read-only and never allowlisted"
            ));
        }
        if provider
            .chars()
            .any(|c| matches!(c, '\'' | '"' | '\\') || c.is_control())
        {
            return invalid(format!(
                "tag delete providers[{i}] {provider:?}: the provider name holds a quote, a \
                 backslash or a control character"
            ));
        }
        if install.providers[..i]
            .iter()
            .any(|seen| seen.eq_ignore_ascii_case(provider))
        {
            return invalid(format!(
                "tag delete providers[{i}] {provider:?}: duplicate provider"
            ));
        }
    }
    Ok(())
}

/// JSON-encode the provider list with every non-ASCII character as a
/// `\uXXXX` escape, so the Jython byte-string literal it lands in stays
/// ASCII (the validated names hold no quote or backslash of their own).
fn ascii_json_list(providers: &[String]) -> Result<String, CoreError> {
    let encoded = serde_json::to_string(providers)
        .map_err(|err| CoreError::Internal(format!("cannot encode the provider list: {err}")))?;
    let mut out = String::with_capacity(encoded.len());
    for c in encoded.chars() {
        if c.is_ascii() {
            out.push(c);
        } else {
            let mut units = [0u16; 2];
            for unit in c.encode_utf16(&mut units) {
                out.push_str(&format!("\\u{unit:04x}"));
            }
        }
    }
    Ok(out)
}

/// The three tagDelete members with every install value substituted:
/// doPost with the secret and the provider list, config.json with the role
/// and user source set through serde_json and `require-auth` asserted on.
/// Refuses `Internal` when any member still holds a marker.
fn tag_delete_members(install: &TagDeleteInstall) -> Result<Vec<(String, String)>, CoreError> {
    validate_tag_delete_install(install)?;
    let do_post = bundle::TAG_DELETE_TEMPLATE
        .replacen("__IGN_TAG_DELETE_SECRET__", &install.secret, 1)
        .replacen(
            "__IGN_TAG_DELETE_PROVIDERS__",
            &ascii_json_list(&install.providers)?,
            1,
        );

    let mut config: Value =
        serde_json::from_str(bundle::TAG_DELETE_CONFIG_TEMPLATE).map_err(|err| {
            CoreError::Internal(format!("tagDelete config.json does not parse: {err}"))
        })?;
    let handler = config
        .get_mut("doPost")
        .and_then(Value::as_object_mut)
        .ok_or_else(|| CoreError::Internal("tagDelete config.json has no doPost object".into()))?;
    if handler.get("require-auth") != Some(&Value::Bool(true)) {
        return Err(CoreError::Internal(
            "tagDelete config.json must keep require-auth true".into(),
        ));
    }
    handler.insert("required-roles".into(), Value::String(install.role.clone()));
    handler.insert(
        "user-source".into(),
        Value::String(install.user_source.clone()),
    );
    let config = serde_json::to_string(&config)
        .map_err(|err| CoreError::Internal(format!("cannot re-serialize config.json: {err}")))?;

    let members = vec![
        (
            format!("{TAG_DELETE_ROUTE_ROOT}/resource.json"),
            bundle::TAG_DELETE_RESOURCE_JSON.to_string(),
        ),
        (format!("{TAG_DELETE_ROUTE_ROOT}/config.json"), config),
        (format!("{TAG_DELETE_ROUTE_ROOT}/doPost.py"), do_post),
    ];
    if let Some((name, _)) = members
        .iter()
        .find(|(_, body)| body.contains(TAG_DELETE_MARKER_PREFIX))
    {
        return Err(CoreError::Internal(format!(
            "{name} still holds a tagDelete install marker after substitution (fail-closed guard)"
        )));
    }
    Ok(members)
}

/// [`build_deploy_zip`] plus, when `tag_delete` is set, the tagDelete
/// route's three members with the install values substituted (26-17). The
/// install is validated first; any marker left in a member refuses
/// `Internal`.
pub fn build_deploy_zip_with(
    project_title: &str,
    with_script_exec: bool,
    secret: Option<&str>,
    with_testing: bool,
    tag_delete: Option<&TagDeleteInstall>,
) -> Result<Vec<u8>, CoreError> {
    let tag_delete_members = tag_delete.map(tag_delete_members).transpose()?;
    let script_exec_py = match (with_script_exec, secret) {
        (false, _) => None,
        (true, Some(secret)) => {
            Some(bundle::SCRIPT_EXEC_TEMPLATE.replace("__IGN_CLI_SECRET__", secret))
        }
        (true, None) => {
            return Err(CoreError::Internal(
                "scriptExec deploy requires a substituted secret — the deploy \
                 action generates the secret before packing (fail-closed guard)"
                    .into(),
            ));
        }
    };

    let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
    let options = zip::write::SimpleFileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated);

    for (name, contents) in bundle::ROUTE_FILES {
        let body = if *name == "project.json" && project_title != DEFAULT_PROJECT {
            retitle_project_json(contents, project_title)?
        } else {
            (*contents).to_string()
        };
        writer.start_file(*name, options).map_err(zip_write_err)?;
        writer.write_all(body.as_bytes()).map_err(|err| {
            CoreError::Internal(format!("cannot build the webdev deploy zip: {err}"))
        })?;
    }

    if let Some(script_exec_py) = script_exec_py {
        for (name, body) in [
            (
                format!("{SCRIPT_EXEC_ROUTE_ROOT}/resource.json"),
                SCRIPT_EXEC_RESOURCE_JSON.to_string(),
            ),
            (
                format!("{SCRIPT_EXEC_ROUTE_ROOT}/config.json"),
                SCRIPT_EXEC_CONFIG_JSON.to_string(),
            ),
            (
                format!("{SCRIPT_EXEC_ROUTE_ROOT}/doPost.py"),
                script_exec_py,
            ),
        ] {
            writer
                .start_file(name.as_str(), options)
                .map_err(zip_write_err)?;
            writer.write_all(body.as_bytes()).map_err(|err| {
                CoreError::Internal(format!("cannot build the webdev deploy zip: {err}"))
            })?;
        }
    }

    for (name, body) in tag_delete_members.into_iter().flatten() {
        writer
            .start_file(name.as_str(), options)
            .map_err(zip_write_err)?;
        writer.write_all(body.as_bytes()).map_err(|err| {
            CoreError::Internal(format!("cannot build the webdev deploy zip: {err}"))
        })?;
    }

    // The testing bundle (ADOPT-04): every member's marker substituted
    // with the deploy project — an unsubstituted marker on a gateway
    // is the bug the count-pin exists to catch before it ships.
    if with_testing {
        let marker_total: usize = bundle::testing::TESTING_FILES
            .iter()
            .map(|(_, contents)| contents.matches(bundle::testing::PROJECT_MARKER).count())
            .sum();
        if marker_total != bundle::testing::PROJECT_MARKER_COUNT {
            return Err(CoreError::Internal(format!(
                "testing bundle marker count drifted: found {marker_total}, pinned {} — \
                 a template edit changed the substitution contract",
                bundle::testing::PROJECT_MARKER_COUNT
            )));
        }
        for (name, contents) in bundle::testing::TESTING_FILES {
            let body = contents.replace(bundle::testing::PROJECT_MARKER, project_title);
            writer.start_file(*name, options).map_err(zip_write_err)?;
            writer.write_all(body.as_bytes()).map_err(|err| {
                CoreError::Internal(format!("cannot build the webdev deploy zip: {err}"))
            })?;
        }
    }

    writer
        .finish()
        .map_err(zip_write_err)
        .map(|cursor| cursor.into_inner())
}

fn zip_write_err(err: zip::result::ZipError) -> CoreError {
    CoreError::Internal(format!("cannot build the webdev deploy zip: {err}"))
}

/// Swap `project.json`'s `title` for a `--project` override — only
/// `title` moves (name/description/enabled/parent ride verbatim; the
/// import NAME is the URL's concern, not the manifest's).
fn retitle_project_json(project_json: &str, title: &str) -> Result<String, CoreError> {
    let mut value: Value = serde_json::from_str(project_json).map_err(|err| {
        CoreError::Internal(format!("embedded project.json does not parse: {err}"))
    })?;
    value["title"] = Value::String(title.to_string());
    serde_json::to_string(&value)
        .map_err(|err| CoreError::Internal(format!("cannot re-serialize project.json: {err}")))
}

#[cfg(test)]
mod tests {
    use super::{
        DEFAULT_PROJECT, RouteBody, TagDeleteInstall, always_on_routes, build_deploy_zip,
        build_deploy_zip_with, denial_to_error, parse_route_body, validate_tag_delete_install,
    };
    use crate::error::CoreError;

    /// The route list is DERIVED from the manifest — the four
    /// always-on folders, manifest order, no drift possible.
    #[test]
    fn always_on_routes_derive_from_the_manifest() {
        assert_eq!(
            always_on_routes(),
            vec![
                "tags".to_string(),
                "tagConfig".to_string(),
                "alarms".to_string(),
                "tagHistory".to_string(),
            ]
        );
    }

    /// Envelope parsing: ok:true yields data; ok:false yields the
    /// code+message; a non-envelope body is internal-class; missing
    /// error fields degrade to the generic contract code.
    #[test]
    fn parse_route_body_envelope_shapes() {
        match parse_route_body(r#"{"ok":true,"data":{"routeVersion":"1.0.0"}}"#)
            .expect("ok body parses")
        {
            RouteBody::Ok(data) => {
                assert_eq!(data["routeVersion"], "1.0.0");
            }
            other => panic!("wrong verdict: {other:?}"),
        }

        match parse_route_body(
            r#"{"ok":false,"error":{"code":"secret_mismatch","message":"nope"}}"#,
        )
        .expect("denial parses")
        {
            RouteBody::Denied {
                code,
                message,
                traceback,
            } => {
                assert_eq!(code, "secret_mismatch");
                assert_eq!(message, "nope");
                assert!(traceback.is_none(), "no traceback on the wire");
            }
            other => panic!("wrong verdict: {other:?}"),
        }

        // A denial carrying the optional traceback keeps it (the
        // black-box fix's parse half).
        match parse_route_body(
            r#"{"ok":false,"error":{"code":"route_error","message":"boom","traceback":"Traceback (most recent call last):\n  ValueError: nope"}}"#,
        )
        .expect("denial with traceback parses")
        {
            RouteBody::Denied { code, traceback, .. } => {
                assert_eq!(code, "route_error");
                assert_eq!(
                    traceback.as_deref(),
                    Some("Traceback (most recent call last):\n  ValueError: nope")
                );
            }
            other => panic!("wrong verdict: {other:?}"),
        }

        // ok:true without data → Null (routes may answer bare oks).
        match parse_route_body(r#"{"ok":true}"#).expect("bare ok parses") {
            RouteBody::Ok(data) => assert!(data.is_null()),
            other => panic!("wrong verdict: {other:?}"),
        }

        // ok:false without an error object → the generic code, never
        // a guess.
        match parse_route_body(r#"{"ok":false}"#).expect("bare denial parses") {
            RouteBody::Denied { code, .. } => assert_eq!(code, "route_error"),
            other => panic!("wrong verdict: {other:?}"),
        }

        let err = parse_route_body("<html>jetty</html>").expect_err("non-envelope fails");
        assert!(matches!(err, CoreError::Internal(_)), "{err}");
    }

    /// The taxonomy mapping: `not_found` reuses the existing slug;
    /// everything else (known secret codes included) rides
    /// `webdev_route_error` verbatim; a traceback appends to the
    /// message (`\nroute traceback: {tb}`) while its absence keeps
    /// the message byte-identical.
    #[test]
    fn denial_mapping_reuses_not_found_and_rides_the_rest() {
        let not_found = denial_to_error("not_found", "no such path", None, "/x".into());
        assert_eq!(not_found.code(), "not_found");
        assert_eq!(not_found.exit_code(), 6);

        let secret = denial_to_error("secret_required", "missing header", None, "/x".into());
        assert_eq!(secret.code(), "webdev_route_error");
        assert_eq!(secret.exit_code(), 6);
        assert!(secret.to_string().contains("secret_required"));
        assert!(
            secret.to_string().contains("missing header"),
            "no traceback → the message rides VERBATIM (no suffix)"
        );

        // THE black-box fix: a denial with a traceback shows it —
        // the "Invalid UUID string" class is diagnosable from CLI
        // output alone.
        let blown = denial_to_error(
            "route_error",
            "error processing action",
            Some("java.lang.IllegalArgumentException: Invalid UUID string: 3f2504e0"),
            "/x".into(),
        );
        assert_eq!(blown.code(), "webdev_route_error");
        let text = blown.to_string();
        assert!(
            text.contains("\nroute traceback: java.lang.IllegalArgumentException: Invalid UUID string: 3f2504e0"),
            "the traceback rides the message: {text}"
        );

        // The alarms route's journal-missing denial maps to the
        // actionable slug (default rigs ALWAYS hit it — the missing
        // journal chain is target state, not a route bug).
        let journal = denial_to_error(
            "no_alarm_journal",
            "No alarm journal profile specified",
            None,
            "/system/webdev/ign-cli/cli/alarms".into(),
        );
        assert_eq!(journal.code(), "alarm_journal_missing");
        assert_eq!(journal.exit_code(), 6);
        assert!(
            journal.hint().unwrap().contains("journal profile"),
            "hint names the chain: {journal}"
        );

        // The tagConfig route's provider-root denial (07-06): the
        // dedicated slug + exit 6, the message names the subtree
        // workaround (the fixed Display — the route's own message
        // stays consistent with it).
        let root = denial_to_error(
            "provider_root_unsupported",
            "provider-root tag paths are not supported on WebDev threads (no RpcContext) -- use a subtree path like [provider]folder",
            None,
            "/system/webdev/ign-cli/cli/tagConfig".into(),
        );
        assert_eq!(root.code(), "provider_root_unsupported");
        assert_eq!(root.exit_code(), 6);
        assert!(
            root.to_string().contains("subtree like [provider]folder"),
            "the fixed Display names the subtree workaround: {root}"
        );
    }

    /// THE fail-closed guard: scriptExec packing demands a secret —
    /// `None` + `with_script_exec` refuses BEFORE any zip is built.
    #[test]
    fn deploy_zip_fails_closed_without_a_script_exec_secret() {
        let err = build_deploy_zip(DEFAULT_PROJECT, true, None, false).expect_err("must refuse");
        assert!(matches!(err, CoreError::Internal(_)), "{err}");
        assert_eq!(err.exit_code(), 1);
    }

    const FAKE_SECRET: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
    const TAG_DELETE_ROOT: &str = "com.inductiveautomation.webdev/resources/cli/tagDelete";

    fn install() -> TagDeleteInstall {
        TagDeleteInstall {
            secret: FAKE_SECRET.to_string(),
            user_source: "default".to_string(),
            role: "Fake Deploy-Role_1.x".to_string(),
            providers: vec!["P26Del".to_string(), "Other".to_string()],
        }
    }

    fn members(zip_bytes: &[u8]) -> Vec<(String, String)> {
        let mut archive =
            zip::ZipArchive::new(std::io::Cursor::new(zip_bytes)).expect("built zip is readable");
        (0..archive.len())
            .map(|index| {
                let mut file = archive.by_index(index).expect("member");
                let mut body = String::new();
                std::io::Read::read_to_string(&mut file, &mut body).expect("member reads");
                (file.name().to_string(), body)
            })
            .collect()
    }

    fn invalid_reason(install: &TagDeleteInstall) -> String {
        match validate_tag_delete_install(install) {
            Err(CoreError::InvalidInput { reason }) => reason,
            other => panic!("expected invalid_input, got {other:?}"),
        }
    }

    /// The install values are checked field by field and refused as
    /// `invalid_input` naming the field (the secret value never echoed).
    #[test]
    fn tag_delete_install_validation() {
        validate_tag_delete_install(&install()).expect("a valid install passes");

        for secret in [
            "",
            "abc",
            &FAKE_SECRET.to_uppercase(),
            &format!("{}g", &FAKE_SECRET[..63]),
            &format!("{FAKE_SECRET}0"),
        ] {
            let mut bad = install();
            bad.secret = secret.to_string();
            let reason = invalid_reason(&bad);
            assert!(reason.contains("secret"), "{reason}");
            if !secret.is_empty() {
                assert!(!reason.contains(secret), "the secret is never echoed");
            }
        }

        for (field, value) in [
            ("user source", ""),
            ("user source", "a'b"),
            ("user source", "tab\tname"),
            ("user source", "naïve"),
            ("role", ""),
            ("role", "x\"y"),
            ("role", "back\\slash"),
            ("role", &"r".repeat(65)),
        ] {
            let mut bad = install();
            if field == "role" {
                bad.role = value.to_string();
            } else {
                bad.user_source = value.to_string();
            }
            let reason = invalid_reason(&bad);
            assert!(reason.contains(field), "{field} {value:?}: {reason}");
        }
        let mut edge = install();
        edge.role = "r".repeat(64);
        edge.user_source = "A b_c-d.9".to_string();
        validate_tag_delete_install(&edge).expect("64 chars and the full charset pass");

        for providers in [
            vec![],
            vec!["System".to_string()],
            vec!["P1".to_string(), "system".to_string()],
            vec!["P1".to_string(), "p1".to_string()],
            vec!["a'b".to_string()],
            vec!["a\"b".to_string()],
            vec!["a\\b".to_string()],
            vec!["a\nb".to_string()],
            vec![String::new()],
        ] {
            let mut bad = install();
            bad.providers = providers.clone();
            let reason = invalid_reason(&bad);
            assert!(reason.contains("provider"), "{providers:?}: {reason}");
        }
    }

    /// The pack adds the three tagDelete members with every marker
    /// substituted, sets the config fields through serde_json and keeps
    /// require-auth on; a deploy without the install packs none.
    #[test]
    fn tag_delete_pack_substitutes_every_marker() {
        let zip = build_deploy_zip_with(DEFAULT_PROJECT, false, None, false, Some(&install()))
            .expect("pack");
        let packed = members(&zip);
        let get = |name: &str| {
            packed
                .iter()
                .find(|(member, _)| member == &format!("{TAG_DELETE_ROOT}/{name}"))
                .map(|(_, body)| body.clone())
                .unwrap_or_else(|| panic!("{name} member"))
        };
        assert_eq!(
            packed
                .iter()
                .filter(|(name, _)| name.starts_with(TAG_DELETE_ROOT))
                .count(),
            3
        );
        assert_eq!(packed.len(), 16, "13 always-on members plus three");
        for (name, body) in &packed {
            assert!(!body.contains("__IGN_TAG_DELETE_"), "{name} keeps a marker");
        }
        let do_post = get("doPost.py");
        assert!(do_post.contains(&format!("SECRET = None or '{FAKE_SECRET}'")));
        assert!(do_post.contains(r#"PROVIDERS_JSON = None or '["P26Del","Other"]'"#));
        let config: serde_json::Value = serde_json::from_str(&get("config.json")).expect("json");
        assert_eq!(config["doPost"]["require-auth"], true);
        assert_eq!(config["doPost"]["required-roles"], "Fake Deploy-Role_1.x");
        assert_eq!(config["doPost"]["user-source"], "default");
        assert_eq!(
            get("resource.json"),
            crate::webdev::TAG_DELETE_RESOURCE_JSON
        );

        // Non-ASCII provider names ride as JSON \u escapes, so the Jython
        // byte-string literal stays ASCII.
        let mut wide = install();
        wide.providers = vec!["Prövider".to_string()];
        let zip =
            build_deploy_zip_with(DEFAULT_PROJECT, false, None, false, Some(&wide)).expect("pack");
        let do_post = members(&zip)
            .into_iter()
            .find(|(name, _)| name.ends_with("tagDelete/doPost.py"))
            .expect("doPost")
            .1;
        assert!(do_post.contains(r#"PROVIDERS_JSON = None or '["Pr\u00f6vider"]'"#));
        assert!(do_post.is_ascii());

        // The wrapper keeps its signature and packs no tagDelete member.
        let plain = build_deploy_zip(DEFAULT_PROJECT, true, Some(FAKE_SECRET), true).expect("pack");
        assert!(
            members(&plain)
                .iter()
                .all(|(name, _)| !name.contains("tagDelete"))
        );
        // tagDelete composes with scriptExec and testing in one zip.
        let all = build_deploy_zip_with(
            DEFAULT_PROJECT,
            true,
            Some(FAKE_SECRET),
            true,
            Some(&install()),
        )
        .expect("pack");
        let names: Vec<String> = members(&all).into_iter().map(|(name, _)| name).collect();
        assert!(names.iter().any(|name| name.contains("cli/scriptExec/")));
        assert!(names.iter().any(|name| name.contains("cli/tagDelete/")));
        assert!(names.iter().any(|name| name.contains("testing/")));
    }

    /// The pack refuses an invalid install, and refuses `Internal` when a
    /// value would leave a marker in a member.
    #[test]
    fn tag_delete_pack_refuses_bad_installs_and_left_markers() {
        let mut bad = install();
        bad.providers = vec!["System".to_string()];
        let err = build_deploy_zip_with(DEFAULT_PROJECT, false, None, false, Some(&bad))
            .expect_err("System refused");
        assert_eq!(err.code(), "invalid_input");

        let mut marker_provider = install();
        marker_provider.providers = vec!["__IGN_TAG_DELETE_SECRET__".to_string()];
        let err =
            build_deploy_zip_with(DEFAULT_PROJECT, false, None, false, Some(&marker_provider))
                .expect_err("a left marker refuses");
        assert!(matches!(err, CoreError::Internal(_)), "{err}");

        let mut marker_role = install();
        marker_role.role = "__IGN_TAG_DELETE_ROLE__".to_string();
        let err = build_deploy_zip_with(DEFAULT_PROJECT, false, None, false, Some(&marker_role))
            .expect_err("a left marker refuses");
        assert!(matches!(err, CoreError::Internal(_)), "{err}");
    }
}