greentic-deployer-dev 1.1.27501952916

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

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use qa_spec::spec::ListSpec;
use qa_spec::spec::question::QuestionPolicy;
use qa_spec::{AnswerSet, FormSpec, QuestionSpec, QuestionType};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::OpError;
use super::bundles::{RouteBindingPayload, TenantSelectorPayload};

/// Exact `schema` discriminator the manifest must carry.
pub const ENV_MANIFEST_SCHEMA_V1: &str = "greentic.env-manifest.v1";

/// Top-level manifest document. `deny_unknown_fields` everywhere so a typo
/// fails loudly at parse time instead of silently no-opping.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnvManifest {
    /// Must equal [`ENV_MANIFEST_SCHEMA_V1`].
    pub schema: String,
    pub environment: ManifestEnvironment,
    /// `"bootstrap"` seeds the env trust root with the local operator key
    /// (idempotent). Absent = skip the step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trust_root: Option<TrustRootDirective>,
    /// Dev-store secret entries — always-put (`op secrets get` is
    /// not-yet-implemented, so values cannot be diffed until A9).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secrets: Vec<ManifestSecret>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bundles: Vec<ManifestBundle>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub messaging_endpoints: Vec<ManifestEndpoint>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestEnvironment {
    /// Environment id. v1 apply can bootstrap only the `local` env (the
    /// `env init` path); any other id must already exist.
    pub id: String,
    /// When set, persisted via the `env set-public-url` path. Absent/`null`
    /// means "leave whatever is there" (upsert — apply never clears it).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub public_base_url: Option<String>,
}

/// v1 accepts only the string `"bootstrap"`. A future
/// `{ "additional_keys": [...] }` shape extends this enum without a schema
/// bump.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TrustRootDirective {
    Bootstrap,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestSecret {
    /// Dev-store path `<tenant>/<team>/<pack>/<name>` — exactly the
    /// `SecretsPutPayload.path` shape.
    pub path: String,
    /// Name of the environment variable holding the value. Secret VALUES
    /// never appear in the manifest.
    pub from_env: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestBundle {
    /// Natural key — unique within the manifest.
    pub bundle_id: String,
    /// Local `.gtbundle`. Relative paths resolve against the manifest
    /// file's directory (not the CWD), so manifests are relocatable.
    pub bundle_path: PathBuf,
    /// Billing principal (P6/B10): required for non-`local` environments.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// Forwarded verbatim with `op deploy`'s three-valued semantics:
    /// absent = leave untouched, `{}` = explicit clear, non-empty = replace.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_overrides: Option<BTreeMap<String, BTreeMap<String, Value>>>,
    /// Absent = same as `op deploy`: empty binding on fresh add, untouched
    /// on re-deploy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub route_binding: Option<RouteBindingPayload>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestEndpoint {
    /// Manifest-local handle AND the endpoint's `display_name` AND (on
    /// create) its `provider_id` instance identity. Upsert natural key:
    /// apply matches an existing endpoint by `(provider_type, name)`.
    pub name: String,
    /// Provider class, e.g. `messaging.telegram.bot`.
    pub provider_type: String,
    /// `bundle_id`s this endpoint admits. Each must be declared in this
    /// manifest's `bundles[]` or already exist in the environment.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub links: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub welcome_flow: Option<ManifestWelcomeFlow>,
    /// Forwarded to `EndpointAddPayload.secret_refs` on create. Drift on an
    /// existing endpoint is reported as a warning (no update verb exists).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub secret_refs: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ManifestWelcomeFlow {
    pub bundle_id: String,
    pub pack_id: String,
    pub flow_id: String,
}

impl EnvManifest {
    /// Manifest-shape validation: everything checkable without the store or
    /// the filesystem. Runs before any artifact digesting or env read so a
    /// malformed manifest fails fast with no side effects.
    pub fn validate_shape(&self) -> Result<(), OpError> {
        if self.schema != ENV_MANIFEST_SCHEMA_V1 {
            return Err(OpError::InvalidArgument(format!(
                "manifest schema `{}` is not the expected `{ENV_MANIFEST_SCHEMA_V1}`",
                self.schema
            )));
        }
        if self.environment.id.trim().is_empty() {
            return Err(OpError::InvalidArgument(
                "environment.id must not be empty".to_string(),
            ));
        }
        // Secrets: path shape + canonicality via the same checks
        // `secrets.rs::put` applies (shared helper — the two surfaces cannot
        // drift), so a bad path fails the whole apply here instead of
        // mid-run. `from_env` *resolution* (var set + non-empty) needs
        // process context and lives in `env_apply`'s validation.
        let mut secret_paths = BTreeSet::new();
        for s in &self.secrets {
            let rel_path = s.path.trim_start_matches('/');
            super::secrets::validate_dev_store_secret_path(rel_path)?;
            if !secret_paths.insert(rel_path) {
                return Err(OpError::InvalidArgument(format!(
                    "duplicate secret path `{rel_path}` in manifest secrets[] \
                     (order-dependent last-write-wins is never what you want)"
                )));
            }
            if s.from_env.trim().is_empty() {
                return Err(OpError::InvalidArgument(format!(
                    "secret `{rel_path}`: from_env must name an environment variable"
                )));
            }
        }

        let mut bundle_ids = BTreeSet::new();
        for b in &self.bundles {
            if b.bundle_id.trim().is_empty() {
                return Err(OpError::InvalidArgument(
                    "bundles[].bundle_id must not be empty".to_string(),
                ));
            }
            if !bundle_ids.insert(b.bundle_id.as_str()) {
                return Err(OpError::InvalidArgument(format!(
                    "duplicate bundle_id `{}` in manifest bundles[]",
                    b.bundle_id
                )));
            }
            if let Some(rb) = &b.route_binding {
                rb.validate()?;
                for prefix in &rb.path_prefixes {
                    if !prefix.starts_with('/') {
                        return Err(OpError::InvalidArgument(format!(
                            "bundle `{}` route_binding.path_prefixes entry `{prefix}` \
                             must start with `/`",
                            b.bundle_id
                        )));
                    }
                }
            }
        }

        let mut endpoint_names = BTreeSet::new();
        for ep in &self.messaging_endpoints {
            if ep.name.trim().is_empty() {
                return Err(OpError::InvalidArgument(
                    "messaging_endpoints[].name must not be empty".to_string(),
                ));
            }
            if ep.provider_type.trim().is_empty() {
                return Err(OpError::InvalidArgument(format!(
                    "endpoint `{}`: provider_type must not be empty",
                    ep.name
                )));
            }
            if !endpoint_names.insert(ep.name.as_str()) {
                return Err(OpError::InvalidArgument(format!(
                    "duplicate endpoint name `{}` in manifest messaging_endpoints[]",
                    ep.name
                )));
            }
            let mut link_set = BTreeSet::new();
            for link in &ep.links {
                if !link_set.insert(link.as_str()) {
                    return Err(OpError::InvalidArgument(format!(
                        "endpoint `{}`: duplicate link `{link}` in links[]",
                        ep.name
                    )));
                }
            }
        }
        Ok(())
    }
}

/// Skeleton manifest for `op env apply --emit-answers-template`: one worked
/// example entry per section, ready to edit. Secret entries name an
/// environment VARIABLE (`from_env`) — values never appear in a manifest.
///
/// A verbatim literal (not a serialized [`EnvManifest`]) so the emitted
/// file keeps the authoring order (`schema` first) instead of serde_json's
/// alphabetical keys. Guarded by a round-trip test: the template must
/// deserialize through [`EnvManifest`] (`deny_unknown_fields`) and pass
/// [`EnvManifest::validate_shape`], so template and types cannot drift.
pub const MANIFEST_TEMPLATE_JSON: &str = r#"{
  "schema": "greentic.env-manifest.v1",
  "environment": {
    "id": "local",
    "public_base_url": null
  },
  "trust_root": "bootstrap",
  "secrets": [
    {
      "path": "default/_/messaging-telegram/telegram_bot_token",
      "from_env": "TELEGRAM_BOT_TOKEN"
    }
  ],
  "bundles": [
    {
      "bundle_id": "example-bundle",
      "bundle_path": "example-bundle.gtbundle",
      "route_binding": {
        "path_prefixes": ["/example"],
        "tenant_selector": { "tenant": "default", "team": "default" }
      }
    }
  ],
  "messaging_endpoints": [
    {
      "name": "example-endpoint",
      "provider_type": "messaging.telegram.bot",
      "links": ["example-bundle"],
      "welcome_flow": {
        "bundle_id": "example-bundle",
        "pack_id": "example-pack",
        "flow_id": "main"
      }
    }
  ]
}
"#;

/// Hand-written JSON Schema for the manifest (`op env apply --schema`),
/// following the existing convention (A1 schemars wiring is still deferred).
pub fn manifest_schema() -> Value {
    serde_json::json!({
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "title": "EnvManifest",
        "description": "greentic.env-manifest.v1 — declarative environment wiring for `gtc op env apply`",
        "type": "object",
        "required": ["schema", "environment"],
        "additionalProperties": false,
        "properties": {
            "schema": {"const": ENV_MANIFEST_SCHEMA_V1},
            "environment": {
                "type": "object",
                "required": ["id"],
                "additionalProperties": false,
                "properties": {
                    "id": {"type": "string", "description": "Environment id; v1 bootstraps only `local`"},
                    "public_base_url": {"type": ["string", "null"], "description": "origin-only URL; absent = leave untouched"}
                }
            },
            "trust_root": {"enum": ["bootstrap", null], "description": "`bootstrap` seeds the operator key (idempotent)"},
            "secrets": {
                "type": "array",
                "description": "dev-store secret entries; always-put (values cannot be diffed until A9)",
                "items": {
                    "type": "object",
                    "required": ["path", "from_env"],
                    "additionalProperties": false,
                    "properties": {
                        "path": {"type": "string", "description": "<tenant>/<team>/<pack>/<name>"},
                        "from_env": {"type": "string", "description": "env var holding the value; values never appear in the manifest"}
                    }
                }
            },
            "bundles": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["bundle_id", "bundle_path"],
                    "additionalProperties": false,
                    "properties": {
                        "bundle_id": {"type": "string"},
                        "bundle_path": {"type": "string", "description": "local .gtbundle; relative to the manifest file"},
                        "customer_id": {"type": ["string", "null"], "description": "required for non-local envs (B10)"},
                        "config_overrides": {"type": ["object", "null"], "description": "<pack_id> -> <key> -> <json>; absent=untouched, {}=clear, map=replace"},
                        "route_binding": {
                            "type": ["object", "null"],
                            "properties": {
                                "hosts": {"type": "array", "items": {"type": "string"}},
                                "path_prefixes": {"type": "array", "items": {"type": "string"}},
                                "tenant_selector": {
                                    "type": ["object", "null"],
                                    "required": ["tenant", "team"],
                                    "properties": {"tenant": {"type": "string"}, "team": {"type": "string"}}
                                }
                            }
                        }
                    }
                }
            },
            "messaging_endpoints": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["name", "provider_type"],
                    "additionalProperties": false,
                    "properties": {
                        "name": {"type": "string", "description": "natural key: matches existing endpoints by (provider_type, display_name)"},
                        "provider_type": {"type": "string"},
                        "links": {"type": "array", "items": {"type": "string"}},
                        "welcome_flow": {
                            "type": ["object", "null"],
                            "required": ["bundle_id", "pack_id", "flow_id"],
                            "additionalProperties": false,
                            "properties": {
                                "bundle_id": {"type": "string"},
                                "pack_id": {"type": "string"},
                                "flow_id": {"type": "string"}
                            }
                        },
                        "secret_refs": {"type": "array", "items": {"type": "string"}}
                    }
                }
            }
        }
    })
}

/// Form id of the env-manifest authoring form ([`manifest_form_spec`]).
pub const ENV_MANIFEST_FORM_ID: &str = "greentic.env-manifest";

/// Version paired with [`ENV_MANIFEST_FORM_ID`]. Answer sets carry it and
/// [`answers_to_manifest`] rejects a mismatch — bump it whenever the
/// question set changes shape, so stale answer files fail loudly instead of
/// converting wrong.
pub const ENV_MANIFEST_FORM_VERSION: &str = "1";

/// The one `qa_spec::FormSpec` for authoring a manifest. The greentic-setup
/// terminal wizard, the future web UI, and Adaptive-Card front-ends all
/// render these same questions; [`answers_to_manifest`] converts the
/// resulting [`AnswerSet`] into a typed [`EnvManifest`] — the manifest stays
/// the durable artifact, answers are an input mechanism.
///
/// Conventions (each pinned by a test):
/// - Repeating manifest sections (`secrets[]`, `bundles[]`,
///   `messaging_endpoints[]`) are `List` questions; an answer is an array of
///   objects keyed by the row field ids.
/// - Secret-adjacent questions ask for the env-var NAME (`from_env`), never
///   a value — no question carries `secret: true`. Unset variables are the
///   apply engine's concern (missing-inputs contract + TTY fill-in).
/// - `required` is the manifest's validation truth, and doubles as the
///   normal-mode marker under greentic-setup's `advanced || required`
///   wizard filter: fields the manifest allows to be absent
///   (`public_base_url`, `customer_id`, `config_overrides`, route binding,
///   welcome flow, …) are `required: false` and surface in advanced mode.
///   The three `List` sections are `required: false` — an empty section is
///   a valid manifest, so absence must pass [`qa_spec::validate()`], and the
///   qa prompt loop walks `List` questions regardless of `required` (its
///   normal-mode filter exempts tables). `trust_root_bootstrap` stays
///   `required` (a `false` answer is valid; the prompt fills the default).
/// - Nested string arrays (`links`, `route_path_prefixes`, …) are
///   comma-separated `String` questions — qa-spec `List` rows cannot nest
///   lists. [`answers_to_manifest`] owns the split.
pub fn manifest_form_spec() -> FormSpec {
    let mut environment_id = question(
        "environment_id",
        QuestionType::String,
        "Environment id",
        "Environment to apply to. v1 apply can bootstrap only `local`; any \
         other id must already exist.",
        true,
    );
    environment_id.default_value = Some("local".to_string());

    let public_base_url = question(
        "public_base_url",
        QuestionType::String,
        "Public base URL",
        "Origin-only URL persisted on the environment (e.g. \
         https://bots.example.com). Leave empty to keep the current value.",
        false,
    );

    let mut trust_root_bootstrap = question(
        "trust_root_bootstrap",
        QuestionType::Boolean,
        "Bootstrap the trust root?",
        "Seed the environment trust root with the local operator key \
         (idempotent; required once before bundles can be staged).",
        true,
    );
    trust_root_bootstrap.default_value = Some("true".to_string());

    let mut secrets = question(
        "secrets",
        QuestionType::List,
        "Secrets",
        "Dev-store secret entries. Each names the environment VARIABLE \
         holding the value — values never go into a manifest.",
        false,
    );
    secrets.list = Some(ListSpec {
        min_items: None,
        max_items: None,
        fields: vec![
            question(
                "path",
                QuestionType::String,
                "Secret path",
                "`<tenant>/<team>/<pack>/<name>`, e.g. \
                 default/_/messaging-telegram/telegram_bot_token",
                true,
            ),
            question(
                "from_env",
                QuestionType::String,
                "Environment variable name",
                "Name of the variable holding the secret value (e.g. \
                 TELEGRAM_BOT_TOKEN) — the name, never the value.",
                true,
            ),
        ],
    });

    let mut bundles = question(
        "bundles",
        QuestionType::List,
        "Bundles",
        "Bundle deployments for this environment.",
        false,
    );
    bundles.list = Some(ListSpec {
        min_items: None,
        max_items: None,
        fields: vec![
            question(
                "bundle_id",
                QuestionType::String,
                "Bundle id",
                "Natural key — unique within the manifest.",
                true,
            ),
            question(
                "bundle_path",
                QuestionType::String,
                "Bundle path",
                "Local `.gtbundle`. Relative paths resolve against the \
                 manifest file's directory.",
                true,
            ),
            question(
                "customer_id",
                QuestionType::String,
                "Customer id",
                "Billing principal — required by apply for non-`local` \
                 environments.",
                false,
            ),
            question(
                "config_overrides",
                QuestionType::String,
                "Config overrides (JSON)",
                "JSON object `{\"<pack_id>\": {\"<key>\": <value>}}`. Empty \
                 = leave untouched; `{}` = explicit clear.",
                false,
            ),
            question(
                "route_hosts",
                QuestionType::String,
                "Route hosts",
                "Comma-separated host names for the route binding.",
                false,
            ),
            question(
                "route_path_prefixes",
                QuestionType::String,
                "Route path prefixes",
                "Comma-separated HTTP path prefixes, each starting with `/` \
                 (e.g. /legal).",
                false,
            ),
            question(
                "route_tenant",
                QuestionType::String,
                "Route tenant",
                "Tenant for the route binding's tenant selector — set \
                 together with `route_team`.",
                false,
            ),
            question(
                "route_team",
                QuestionType::String,
                "Route team",
                "Team for the route binding's tenant selector — set \
                 together with `route_tenant`.",
                false,
            ),
        ],
    });

    let mut messaging_endpoints = question(
        "messaging_endpoints",
        QuestionType::List,
        "Messaging endpoints",
        "Messaging endpoints and their bundle links.",
        false,
    );
    messaging_endpoints.list = Some(ListSpec {
        min_items: None,
        max_items: None,
        fields: vec![
            question(
                "name",
                QuestionType::String,
                "Endpoint name",
                "Manifest-local handle and display name. Upsert key \
                 together with the provider type.",
                true,
            ),
            question(
                "provider_type",
                QuestionType::String,
                "Provider type",
                "Provider class, e.g. messaging.telegram.bot.",
                true,
            ),
            question(
                "links",
                QuestionType::String,
                "Linked bundle ids",
                "Comma-separated `bundle_id`s this endpoint admits.",
                false,
            ),
            question(
                "welcome_bundle_id",
                QuestionType::String,
                "Welcome flow: bundle id",
                "Set the three welcome_* fields together (or none).",
                false,
            ),
            question(
                "welcome_pack_id",
                QuestionType::String,
                "Welcome flow: pack id",
                "Set the three welcome_* fields together (or none).",
                false,
            ),
            question(
                "welcome_flow_id",
                QuestionType::String,
                "Welcome flow: flow id",
                "Set the three welcome_* fields together (or none).",
                false,
            ),
            question(
                "secret_refs",
                QuestionType::String,
                "Secret refs",
                "Comma-separated secret refs forwarded on endpoint create.",
                false,
            ),
        ],
    });

    FormSpec {
        id: ENV_MANIFEST_FORM_ID.to_string(),
        title: "Environment setup".to_string(),
        version: ENV_MANIFEST_FORM_VERSION.to_string(),
        description: Some(format!(
            "Authors a `{ENV_MANIFEST_SCHEMA_V1}` manifest — the durable, \
             re-appliable desired-state document for one environment."
        )),
        presentation: None,
        progress_policy: None,
        secrets_policy: None,
        store: Vec::new(),
        validations: Vec::new(),
        includes: Vec::new(),
        // Secrets come LAST: the terminal wizard derives the required
        // secret paths from the bundles/endpoints just authored and asks
        // only for the env-var name, so the section is most useful after
        // those are known. Other front-ends render the same order.
        questions: vec![
            environment_id,
            public_base_url,
            trust_root_bootstrap,
            bundles,
            messaging_endpoints,
            secrets,
        ],
    }
}

/// [`QuestionSpec`] constructor. Spells out every field (no
/// `..Default::default()`) on purpose: a field added to qa-spec's
/// `QuestionSpec` becomes a compile error here, forcing a deliberate
/// default instead of silently inheriting one.
fn question(
    id: &str,
    kind: QuestionType,
    title: &str,
    description: &str,
    required: bool,
) -> QuestionSpec {
    QuestionSpec {
        id: id.to_string(),
        kind,
        title: title.to_string(),
        title_i18n: None,
        description: Some(description.to_string()),
        description_i18n: None,
        required,
        choices: None,
        default_value: None,
        secret: false,
        visible_if: None,
        constraint: None,
        list: None,
        computed: None,
        policy: QuestionPolicy::default(),
        computed_overridable: false,
    }
}

/// Convert a [`manifest_form_spec`] answer set into a typed [`EnvManifest`].
///
/// Pure conversion: errors only on values that cannot map onto the manifest
/// types (wrong JSON type, half-set field pairs, unparseable
/// `config_overrides`). Callers run `qa_spec::validate` on the answers
/// first for required/constraint enforcement, and the apply engine runs
/// [`EnvManifest::validate_shape`] on the result — this function does not
/// duplicate either. Lenient on absence (missing sections → empty) so a
/// minimal hand-written answers file converts.
///
/// Convention reminder for new fields: every `Vec<String>` manifest field
/// (`links`, `route_hosts`, `route_path_prefixes`, `secret_refs`) is a
/// comma-separated `String` question and MUST come through
/// [`split_csv`] — a plain `req_row_string` would smuggle the commas into
/// a single entry.
pub fn answers_to_manifest(answers: &AnswerSet) -> Result<EnvManifest, OpError> {
    if answers.form_id != ENV_MANIFEST_FORM_ID {
        return Err(OpError::InvalidArgument(format!(
            "answers form_id `{}` is not `{ENV_MANIFEST_FORM_ID}`",
            answers.form_id
        )));
    }
    if answers.spec_version != ENV_MANIFEST_FORM_VERSION {
        return Err(OpError::InvalidArgument(format!(
            "answers spec_version `{}` is not `{ENV_MANIFEST_FORM_VERSION}` \
             — re-run the wizard against the current form",
            answers.spec_version
        )));
    }
    let map = answers
        .answers
        .as_object()
        .ok_or_else(|| OpError::InvalidArgument("answers must be a JSON object".to_string()))?;

    let environment_id = opt_string(map, "environment_id")?.ok_or_else(|| {
        OpError::InvalidArgument("answers: environment_id must be a non-empty string".to_string())
    })?;
    let public_base_url = opt_string(map, "public_base_url")?;
    let trust_root = match map.get("trust_root_bootstrap") {
        None | Some(Value::Null) | Some(Value::Bool(false)) => None,
        Some(Value::Bool(true)) => Some(TrustRootDirective::Bootstrap),
        Some(other) => {
            return Err(OpError::InvalidArgument(format!(
                "answers: trust_root_bootstrap must be a boolean, got {other}"
            )));
        }
    };

    let mut secrets = Vec::new();
    for (idx, row) in rows(map, "secrets")?.iter().enumerate() {
        let row = row_object("secrets", idx, row)?;
        secrets.push(ManifestSecret {
            path: req_row_string("secrets", idx, row, "path")?,
            from_env: req_row_string("secrets", idx, row, "from_env")?,
        });
    }

    let mut bundles = Vec::new();
    for (idx, row) in rows(map, "bundles")?.iter().enumerate() {
        let row = row_object("bundles", idx, row)?;
        let bundle_id = req_row_string("bundles", idx, row, "bundle_id")?;
        let config_overrides = match opt_row_string("bundles", idx, row, "config_overrides")? {
            None => None,
            Some(raw) => Some(
                serde_json::from_str::<BTreeMap<String, BTreeMap<String, Value>>>(&raw).map_err(
                    |err| {
                        OpError::InvalidArgument(format!(
                            "answers: bundles[{idx}] (`{bundle_id}`): config_overrides is \
                             not a `<pack_id> -> <key> -> <value>` JSON object: {err}"
                        ))
                    },
                )?,
            ),
        };
        let hosts = split_csv(opt_row_string("bundles", idx, row, "route_hosts")?);
        let path_prefixes = split_csv(opt_row_string("bundles", idx, row, "route_path_prefixes")?);
        let tenant_selector = match (
            opt_row_string("bundles", idx, row, "route_tenant")?,
            opt_row_string("bundles", idx, row, "route_team")?,
        ) {
            (Some(tenant), Some(team)) => Some(TenantSelectorPayload { tenant, team }),
            (None, None) => None,
            _ => {
                return Err(OpError::InvalidArgument(format!(
                    "answers: bundles[{idx}] (`{bundle_id}`): set route_tenant and \
                     route_team together (or neither)"
                )));
            }
        };
        let route_binding =
            if hosts.is_empty() && path_prefixes.is_empty() && tenant_selector.is_none() {
                None
            } else {
                Some(RouteBindingPayload {
                    hosts,
                    path_prefixes,
                    tenant_selector,
                })
            };
        bundles.push(ManifestBundle {
            bundle_id,
            bundle_path: PathBuf::from(req_row_string("bundles", idx, row, "bundle_path")?),
            customer_id: opt_row_string("bundles", idx, row, "customer_id")?,
            config_overrides,
            route_binding,
        });
    }

    let mut messaging_endpoints = Vec::new();
    for (idx, row) in rows(map, "messaging_endpoints")?.iter().enumerate() {
        let row = row_object("messaging_endpoints", idx, row)?;
        let name = req_row_string("messaging_endpoints", idx, row, "name")?;
        let welcome_flow = match (
            opt_row_string("messaging_endpoints", idx, row, "welcome_bundle_id")?,
            opt_row_string("messaging_endpoints", idx, row, "welcome_pack_id")?,
            opt_row_string("messaging_endpoints", idx, row, "welcome_flow_id")?,
        ) {
            (Some(bundle_id), Some(pack_id), Some(flow_id)) => Some(ManifestWelcomeFlow {
                bundle_id,
                pack_id,
                flow_id,
            }),
            (None, None, None) => None,
            _ => {
                return Err(OpError::InvalidArgument(format!(
                    "answers: messaging_endpoints[{idx}] (`{name}`): set \
                     welcome_bundle_id, welcome_pack_id and welcome_flow_id \
                     together (or none)"
                )));
            }
        };
        messaging_endpoints.push(ManifestEndpoint {
            name,
            provider_type: req_row_string("messaging_endpoints", idx, row, "provider_type")?,
            links: split_csv(opt_row_string("messaging_endpoints", idx, row, "links")?),
            welcome_flow,
            secret_refs: split_csv(opt_row_string(
                "messaging_endpoints",
                idx,
                row,
                "secret_refs",
            )?),
        });
    }

    Ok(EnvManifest {
        schema: ENV_MANIFEST_SCHEMA_V1.to_string(),
        environment: ManifestEnvironment {
            id: environment_id,
            public_base_url,
        },
        trust_root,
        secrets,
        bundles,
        messaging_endpoints,
    })
}

/// A `List` answer: absent/null → empty, anything but an array → error.
fn rows<'a>(map: &'a serde_json::Map<String, Value>, key: &str) -> Result<&'a [Value], OpError> {
    const EMPTY: &[Value] = &[];
    match map.get(key) {
        None | Some(Value::Null) => Ok(EMPTY),
        Some(Value::Array(items)) => Ok(items.as_slice()),
        Some(other) => Err(OpError::InvalidArgument(format!(
            "answers: {key} must be an array, got {other}"
        ))),
    }
}

fn row_object<'a>(
    section: &str,
    idx: usize,
    row: &'a Value,
) -> Result<&'a serde_json::Map<String, Value>, OpError> {
    row.as_object().ok_or_else(|| {
        OpError::InvalidArgument(format!(
            "answers: {section}[{idx}] must be an object, got {row}"
        ))
    })
}

/// Optional string answer: absent/null/blank → `None`; non-string → error.
fn opt_string(map: &serde_json::Map<String, Value>, key: &str) -> Result<Option<String>, OpError> {
    opt_string_at(map, key, key)
}

/// [`opt_string`] with a caller-supplied error label (`section[idx].key`
/// for row fields), so every type error keeps the offending value.
fn opt_string_at(
    map: &serde_json::Map<String, Value>,
    key: &str,
    label: &str,
) -> Result<Option<String>, OpError> {
    match map.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(s)) => {
            let trimmed = s.trim();
            Ok((!trimmed.is_empty()).then(|| trimmed.to_string()))
        }
        Some(other) => Err(OpError::InvalidArgument(format!(
            "answers: {label} must be a string, got {other}"
        ))),
    }
}

fn opt_row_string(
    section: &str,
    idx: usize,
    row: &serde_json::Map<String, Value>,
    key: &str,
) -> Result<Option<String>, OpError> {
    opt_string_at(row, key, &format!("{section}[{idx}].{key}"))
}

fn req_row_string(
    section: &str,
    idx: usize,
    row: &serde_json::Map<String, Value>,
    key: &str,
) -> Result<String, OpError> {
    opt_row_string(section, idx, row, key)?.ok_or_else(|| {
        OpError::InvalidArgument(format!(
            "answers: {section}[{idx}].{key} must be a non-empty string"
        ))
    })
}

/// Split a comma-separated answer into trimmed, non-empty entries.
fn split_csv(value: Option<String>) -> Vec<String> {
    value
        .map(|raw| {
            raw.split(',')
                .map(str::trim)
                .filter(|entry| !entry.is_empty())
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn minimal(schema: &str) -> EnvManifest {
        serde_json::from_value(serde_json::json!({
            "schema": schema,
            "environment": {"id": "local"}
        }))
        .expect("minimal manifest parses")
    }

    #[test]
    fn schema_mismatch_rejected() {
        let err = minimal("greentic.env-manifest.v2")
            .validate_shape()
            .unwrap_err();
        assert!(matches!(err, OpError::InvalidArgument(_)), "{err}");
    }

    #[test]
    fn unknown_top_level_field_rejected_at_parse() {
        let err = serde_json::from_value::<EnvManifest>(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "bundlez": []
        }))
        .unwrap_err();
        assert!(err.to_string().contains("bundlez"), "{err}");
    }

    #[test]
    fn valid_secrets_pass_shape_validation() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "secrets": [
                {"path": "legal/_/messaging-telegram/telegram_bot_token", "from_env": "A"},
                {"path": "accounting/_/messaging-telegram/telegram_bot_token", "from_env": "B"}
            ]
        }))
        .unwrap();
        manifest.validate_shape().expect("valid");
    }

    #[test]
    fn non_canonical_secret_path_rejected_at_shape() {
        // Same checks as `op secrets put` (shared helper): wrong depth,
        // non-canonical team, non-canonical name.
        for path in [
            "credentials/aws",
            "legal/default/messaging-telegram/telegram_bot_token",
            "legal/_/messaging-telegram/BOT-TOKEN",
        ] {
            let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
                "schema": ENV_MANIFEST_SCHEMA_V1,
                "environment": {"id": "local"},
                "secrets": [{"path": path, "from_env": "X"}]
            }))
            .unwrap();
            let err = manifest.validate_shape().unwrap_err();
            assert!(
                matches!(err, OpError::InvalidArgument(_)),
                "path `{path}` got {err}"
            );
        }
    }

    #[test]
    fn duplicate_secret_path_rejected() {
        // The dup check runs on the trimmed path, so a leading `/` cannot
        // smuggle in a duplicate.
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "secrets": [
                {"path": "legal/_/p/tok", "from_env": "A"},
                {"path": "/legal/_/p/tok", "from_env": "B"}
            ]
        }))
        .unwrap();
        let err = manifest.validate_shape().unwrap_err();
        assert!(err.to_string().contains("duplicate secret path"), "{err}");
    }

    #[test]
    fn empty_from_env_rejected() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "secrets": [{"path": "legal/_/p/tok", "from_env": "  "}]
        }))
        .unwrap();
        let err = manifest.validate_shape().unwrap_err();
        assert!(err.to_string().contains("from_env"), "{err}");
    }

    #[test]
    fn duplicate_bundle_id_rejected() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "bundles": [
                {"bundle_id": "a", "bundle_path": "a.gtbundle"},
                {"bundle_id": "a", "bundle_path": "b.gtbundle"}
            ]
        }))
        .unwrap();
        let err = manifest.validate_shape().unwrap_err();
        assert!(err.to_string().contains("duplicate bundle_id"), "{err}");
    }

    #[test]
    fn duplicate_endpoint_name_rejected() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "messaging_endpoints": [
                {"name": "n", "provider_type": "messaging.telegram.bot"},
                {"name": "n", "provider_type": "messaging.telegram.bot"}
            ]
        }))
        .unwrap();
        let err = manifest.validate_shape().unwrap_err();
        assert!(err.to_string().contains("duplicate endpoint name"), "{err}");
    }

    #[test]
    fn tenant_selector_without_matcher_rejected() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "bundles": [{
                "bundle_id": "a",
                "bundle_path": "a.gtbundle",
                "route_binding": {"tenant_selector": {"tenant": "t", "team": "d"}}
            }]
        }))
        .unwrap();
        let err = manifest.validate_shape().unwrap_err();
        assert!(err.to_string().contains("tenant_selector"), "{err}");
    }

    #[test]
    fn path_prefix_must_start_with_slash() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "bundles": [{
                "bundle_id": "a",
                "bundle_path": "a.gtbundle",
                "route_binding": {"path_prefixes": ["legal"]}
            }]
        }))
        .unwrap();
        let err = manifest.validate_shape().unwrap_err();
        assert!(err.to_string().contains("must start with `/`"), "{err}");
    }

    #[test]
    fn duplicate_link_in_endpoint_rejected() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "messaging_endpoints": [{
                "name": "n",
                "provider_type": "messaging.telegram.bot",
                "links": ["bundle-a", "bundle-a"]
            }]
        }))
        .unwrap();
        let err = manifest.validate_shape().unwrap_err();
        assert!(err.to_string().contains("duplicate link"), "{err}");
        assert!(err.to_string().contains("bundle-a"), "{err}");
    }

    #[test]
    fn trust_root_bootstrap_parses() {
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local"},
            "trust_root": "bootstrap"
        }))
        .unwrap();
        assert_eq!(manifest.trust_root, Some(TrustRootDirective::Bootstrap));
        manifest.validate_shape().expect("valid");
    }

    #[test]
    fn template_round_trips_through_manifest_and_shape_validation() {
        // The `--emit-answers-template` skeleton and the serde types must
        // never drift: the template parses under `deny_unknown_fields` AND
        // passes shape validation (canonical secret path, route binding
        // rules, ...) as-is.
        let manifest: EnvManifest =
            serde_json::from_str(MANIFEST_TEMPLATE_JSON).expect("template parses as EnvManifest");
        manifest
            .validate_shape()
            .expect("template passes validate_shape");
        assert_eq!(manifest.schema, ENV_MANIFEST_SCHEMA_V1);
        // Every section carries a worked example.
        assert_eq!(manifest.trust_root, Some(TrustRootDirective::Bootstrap));
        assert!(!manifest.secrets.is_empty());
        assert!(!manifest.bundles.is_empty());
        assert!(!manifest.messaging_endpoints.is_empty());
    }

    #[test]
    fn two_dept_worked_example_parses() {
        // The full §3 worked example from the design doc.
        let manifest: EnvManifest = serde_json::from_value(serde_json::json!({
            "schema": ENV_MANIFEST_SCHEMA_V1,
            "environment": {"id": "local", "public_base_url": null},
            "trust_root": "bootstrap",
            "secrets": [
                {
                    "path": "legal/_/messaging-telegram/telegram_bot_token",
                    "from_env": "TELEGRAM_LEGAL_BOT_TOKEN"
                },
                {
                    "path": "accounting/_/messaging-telegram/telegram_bot_token",
                    "from_env": "TELEGRAM_ACCOUNTING_BOT_TOKEN"
                }
            ],
            "bundles": [
                {
                    "bundle_id": "realbot-legal",
                    "bundle_path": "bundle-workspace-legal/realbot-legal.gtbundle",
                    "route_binding": {
                        "hosts": [],
                        "path_prefixes": ["/legal"],
                        "tenant_selector": {"tenant": "legal", "team": "default"}
                    }
                },
                {
                    "bundle_id": "realbot-accounting",
                    "bundle_path": "bundle-workspace-accounting/realbot-accounting.gtbundle",
                    "route_binding": {
                        "hosts": [],
                        "path_prefixes": ["/accounting"],
                        "tenant_selector": {"tenant": "accounting", "team": "default"}
                    }
                }
            ],
            "messaging_endpoints": [
                {
                    "name": "realbot-legal",
                    "provider_type": "messaging.telegram.bot",
                    "links": ["realbot-legal"]
                },
                {
                    "name": "realbot-accounting",
                    "provider_type": "messaging.telegram.bot",
                    "links": ["realbot-accounting"]
                }
            ]
        }))
        .unwrap();
        manifest.validate_shape().expect("worked example is valid");
        assert_eq!(manifest.secrets.len(), 2);
        assert_eq!(manifest.bundles.len(), 2);
        assert_eq!(manifest.messaging_endpoints.len(), 2);
    }

    /// Composite id (`list.field`) for every question, the same notation the
    /// coverage table uses.
    fn question_ids(spec: &FormSpec) -> BTreeSet<String> {
        let mut ids = BTreeSet::new();
        for q in &spec.questions {
            match &q.list {
                Some(list) => {
                    for field in &list.fields {
                        assert!(
                            ids.insert(format!("{}.{}", q.id, field.id)),
                            "duplicate question id {}.{}",
                            q.id,
                            field.id
                        );
                    }
                }
                None => {
                    assert!(ids.insert(q.id.clone()), "duplicate question id {}", q.id);
                }
            }
        }
        ids
    }

    fn answers(value: Value) -> AnswerSet {
        AnswerSet {
            form_id: ENV_MANIFEST_FORM_ID.to_string(),
            spec_version: ENV_MANIFEST_FORM_VERSION.to_string(),
            answers: value,
            meta: None,
        }
    }

    #[test]
    fn form_spec_never_asks_for_secret_values() {
        // The design rule: secret questions ask for env-var NAMES, so no
        // question is secret-flagged and every List question carries its row
        // definition.
        let spec = manifest_form_spec();
        for q in &spec.questions {
            assert!(!q.secret, "`{}` must not be a secret question", q.id);
            match q.kind {
                QuestionType::List => {
                    let list = q.list.as_ref().unwrap_or_else(|| {
                        panic!("List question `{}` is missing its row definition", q.id)
                    });
                    assert!(!list.fields.is_empty(), "`{}` has no row fields", q.id);
                    for field in &list.fields {
                        assert!(!field.secret, "`{}.{}` must not be secret", q.id, field.id);
                    }
                }
                _ => assert!(q.list.is_none(), "`{}` is not a List but has rows", q.id),
            }
        }
    }

    #[test]
    fn required_marks_the_normal_mode_surface() {
        // `required` is validation truth AND the normal-mode marker under
        // greentic-setup's `advanced || required` wizard filter. Everything
        // the manifest allows to be absent must stay non-required.
        let spec = manifest_form_spec();
        let mut required = BTreeSet::new();
        for q in &spec.questions {
            if q.required {
                required.insert(q.id.clone());
            }
            for field in q.list.iter().flat_map(|l| &l.fields) {
                if field.required {
                    required.insert(format!("{}.{}", q.id, field.id));
                }
            }
        }
        let expected: BTreeSet<String> = [
            "environment_id",
            "trust_root_bootstrap",
            "secrets.path",
            "secrets.from_env",
            "bundles.bundle_id",
            "bundles.bundle_path",
            "messaging_endpoints.name",
            "messaging_endpoints.provider_type",
        ]
        .into_iter()
        .map(str::to_string)
        .collect();
        assert_eq!(required, expected);
    }

    #[test]
    fn form_questions_and_manifest_fields_cover_each_other() {
        // Bidirectional drift guard: every manifest field (leaf of
        // `manifest_schema()`) maps to a question, and every question maps
        // to a manifest field. Adding a field to the manifest or a question
        // to the form fails this test until the mapping (and the
        // counterpart) exists. `""` marks fields `answers_to_manifest`
        // produces as constants.
        const FIELD_TO_QUESTION: &[(&str, &str)] = &[
            ("schema", ""),
            ("environment.id", "environment_id"),
            ("environment.public_base_url", "public_base_url"),
            ("trust_root", "trust_root_bootstrap"),
            ("secrets[].path", "secrets.path"),
            ("secrets[].from_env", "secrets.from_env"),
            ("bundles[].bundle_id", "bundles.bundle_id"),
            ("bundles[].bundle_path", "bundles.bundle_path"),
            ("bundles[].customer_id", "bundles.customer_id"),
            ("bundles[].config_overrides", "bundles.config_overrides"),
            ("bundles[].route_binding.hosts", "bundles.route_hosts"),
            (
                "bundles[].route_binding.path_prefixes",
                "bundles.route_path_prefixes",
            ),
            (
                "bundles[].route_binding.tenant_selector.tenant",
                "bundles.route_tenant",
            ),
            (
                "bundles[].route_binding.tenant_selector.team",
                "bundles.route_team",
            ),
            ("messaging_endpoints[].name", "messaging_endpoints.name"),
            (
                "messaging_endpoints[].provider_type",
                "messaging_endpoints.provider_type",
            ),
            ("messaging_endpoints[].links", "messaging_endpoints.links"),
            (
                "messaging_endpoints[].welcome_flow.bundle_id",
                "messaging_endpoints.welcome_bundle_id",
            ),
            (
                "messaging_endpoints[].welcome_flow.pack_id",
                "messaging_endpoints.welcome_pack_id",
            ),
            (
                "messaging_endpoints[].welcome_flow.flow_id",
                "messaging_endpoints.welcome_flow_id",
            ),
            (
                "messaging_endpoints[].secret_refs",
                "messaging_endpoints.secret_refs",
            ),
        ];

        fn collect_leaves(node: &Value, prefix: &str, out: &mut BTreeSet<String>) {
            if let Some(items) = node.get("items") {
                if items.get("properties").is_some() {
                    collect_leaves(items, &format!("{prefix}[]"), out);
                } else {
                    out.insert(prefix.to_string());
                }
                return;
            }
            if let Some(props) = node.get("properties").and_then(Value::as_object) {
                for (key, sub) in props {
                    let path = if prefix.is_empty() {
                        key.clone()
                    } else {
                        format!("{prefix}.{key}")
                    };
                    collect_leaves(sub, &path, out);
                }
                return;
            }
            out.insert(prefix.to_string());
        }

        let mut schema_leaves = BTreeSet::new();
        collect_leaves(&manifest_schema(), "", &mut schema_leaves);
        let mapped_fields: BTreeSet<String> = FIELD_TO_QUESTION
            .iter()
            .map(|(field, _)| field.to_string())
            .collect();
        assert_eq!(
            schema_leaves, mapped_fields,
            "manifest fields and the coverage table drifted — map every \
             schema leaf to a question (or `\"\"` for constants)"
        );

        let mapped_questions: BTreeSet<String> = FIELD_TO_QUESTION
            .iter()
            .filter(|(_, q)| !q.is_empty())
            .map(|(_, q)| q.to_string())
            .collect();
        assert_eq!(
            question_ids(&manifest_form_spec()),
            mapped_questions,
            "form questions and the coverage table drifted — every question \
             must map to a manifest field"
        );
    }

    #[test]
    fn answers_round_trip_to_valid_manifest() {
        let spec = manifest_form_spec();
        let set = answers(serde_json::json!({
            "environment_id": "local",
            "public_base_url": "https://bots.example.com",
            "trust_root_bootstrap": true,
            "secrets": [
                {
                    "path": "legal/_/messaging-telegram/telegram_bot_token",
                    "from_env": "TELEGRAM_LEGAL_BOT_TOKEN"
                }
            ],
            "bundles": [
                {
                    "bundle_id": "realbot-legal",
                    "bundle_path": "bundle-workspace-legal/realbot-legal.gtbundle",
                    "customer_id": "acme",
                    "config_overrides": "{\"realbot\": {\"mode\": \"prod\"}}",
                    "route_path_prefixes": "/legal, /legal-archive",
                    "route_tenant": "legal",
                    "route_team": "default"
                }
            ],
            "messaging_endpoints": [
                {
                    "name": "realbot-legal",
                    "provider_type": "messaging.telegram.bot",
                    "links": "realbot-legal, realbot-audit",
                    "welcome_bundle_id": "realbot-legal",
                    "welcome_pack_id": "realbot",
                    "welcome_flow_id": "main"
                }
            ]
        }));

        let report = qa_spec::validate(&spec, &set.answers);
        assert!(report.valid, "answers must pass the form spec: {report:?}");

        let manifest = answers_to_manifest(&set).expect("converts");
        manifest.validate_shape().expect("round-trip passes shape");

        assert_eq!(manifest.environment.id, "local");
        assert_eq!(
            manifest.environment.public_base_url.as_deref(),
            Some("https://bots.example.com")
        );
        assert_eq!(manifest.trust_root, Some(TrustRootDirective::Bootstrap));
        assert_eq!(manifest.secrets.len(), 1);
        assert_eq!(
            manifest.secrets[0].from_env, "TELEGRAM_LEGAL_BOT_TOKEN",
            "from_env carries the variable NAME"
        );
        let bundle = &manifest.bundles[0];
        assert_eq!(bundle.customer_id.as_deref(), Some("acme"));
        assert_eq!(
            bundle.config_overrides.as_ref().unwrap()["realbot"]["mode"],
            serde_json::json!("prod")
        );
        let rb = bundle.route_binding.as_ref().expect("route binding built");
        assert_eq!(rb.path_prefixes, ["/legal", "/legal-archive"]);
        assert!(rb.hosts.is_empty());
        let selector = rb.tenant_selector.as_ref().expect("selector built");
        assert_eq!(
            (selector.tenant.as_str(), selector.team.as_str()),
            ("legal", "default")
        );
        let ep = &manifest.messaging_endpoints[0];
        assert_eq!(ep.links, ["realbot-legal", "realbot-audit"]);
        assert_eq!(
            ep.welcome_flow,
            Some(ManifestWelcomeFlow {
                bundle_id: "realbot-legal".to_string(),
                pack_id: "realbot".to_string(),
                flow_id: "main".to_string(),
            })
        );
        assert!(ep.secret_refs.is_empty());
    }

    #[test]
    fn minimal_answers_convert_leniently() {
        // Conversion is lenient on absence (qa_spec::validate owns
        // required-ness): a bare environment_id yields a valid empty
        // manifest with no trust-root directive.
        let manifest = answers_to_manifest(&answers(serde_json::json!({
            "environment_id": "demo",
            "trust_root_bootstrap": false
        })))
        .expect("converts");
        manifest.validate_shape().expect("valid shape");
        assert_eq!(manifest.environment.id, "demo");
        assert_eq!(manifest.environment.public_base_url, None);
        assert_eq!(manifest.trust_root, None);
        assert!(manifest.secrets.is_empty());
        assert!(manifest.bundles.is_empty());
        assert!(manifest.messaging_endpoints.is_empty());
    }

    #[test]
    fn minimal_answers_pass_form_validation() {
        // An empty section is a valid manifest, so the `List` sections must
        // be `required: false`: minimal answers (no lists at all) pass
        // qa_spec::validate — the wizard's declined tables don't trip a
        // bogus required nag, and headless validation stays honest.
        let result = qa_spec::validate(
            &manifest_form_spec(),
            &serde_json::json!({
                "environment_id": "local",
                "trust_root_bootstrap": true
            }),
        );
        assert!(
            result.valid,
            "errors: {:?}, missing: {:?}, unknown: {:?}",
            result.errors, result.missing_required, result.unknown_fields
        );
    }

    #[test]
    fn answers_conversion_errors_name_the_gap() {
        for (label, value, needle) in [
            (
                "missing environment_id",
                serde_json::json!({}),
                "environment_id",
            ),
            (
                "tenant without team",
                serde_json::json!({
                    "environment_id": "local",
                    "bundles": [{
                        "bundle_id": "b", "bundle_path": "b.gtbundle",
                        "route_tenant": "legal"
                    }]
                }),
                "route_team",
            ),
            (
                "partial welcome flow",
                serde_json::json!({
                    "environment_id": "local",
                    "messaging_endpoints": [{
                        "name": "n", "provider_type": "messaging.telegram.bot",
                        "welcome_bundle_id": "b"
                    }]
                }),
                "welcome_pack_id",
            ),
            (
                "config_overrides not an object",
                serde_json::json!({
                    "environment_id": "local",
                    "bundles": [{
                        "bundle_id": "b", "bundle_path": "b.gtbundle",
                        "config_overrides": "[1, 2]"
                    }]
                }),
                "config_overrides",
            ),
            (
                "row field of the wrong type",
                serde_json::json!({
                    "environment_id": "local",
                    "secrets": [{"path": "a/_/p/tok", "from_env": 7}]
                }),
                "secrets[0].from_env",
            ),
        ] {
            let err = answers_to_manifest(&answers(value)).unwrap_err();
            assert!(
                err.to_string().contains(needle),
                "{label}: expected `{needle}` in `{err}`"
            );
        }
    }

    #[test]
    fn answers_form_identity_is_checked() {
        let mut set = answers(serde_json::json!({"environment_id": "local"}));
        set.form_id = "something.else".to_string();
        let err = answers_to_manifest(&set).unwrap_err();
        assert!(err.to_string().contains(ENV_MANIFEST_FORM_ID), "{err}");

        let mut set = answers(serde_json::json!({"environment_id": "local"}));
        set.spec_version = "0".to_string();
        let err = answers_to_manifest(&set).unwrap_err();
        assert!(err.to_string().contains("spec_version"), "{err}");
    }

    #[test]
    fn form_spec_enforces_required_row_fields() {
        // Guards the row field ids against typos: a secrets row without
        // `from_env` must fail qa-spec validation (not slide through as an
        // unknown field).
        let spec = manifest_form_spec();
        let report = qa_spec::validate(
            &spec,
            &serde_json::json!({
                "environment_id": "local",
                "trust_root_bootstrap": false,
                "secrets": [{"path": "default/_/p/tok"}],
                "bundles": [],
                "messaging_endpoints": []
            }),
        );
        assert!(!report.valid);
        assert!(
            report
                .errors
                .iter()
                .any(|e| format!("{e:?}").contains("from_env")),
            "missing row field must be reported: {report:?}"
        );
    }
}