greentic-bundle 1.1.0

Greentic bundle authoring CLI scaffold with embedded i18n and answer-document contracts.
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
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::process::Command;

use serde_json::{Value, json};
use tempfile::TempDir;

fn bundle_bin() -> &'static str {
    env!("CARGO_BIN_EXE_greentic-bundle")
}

#[test]
fn legacy_setup_spec_converts_deterministically() {
    let raw = r#"
title: Telegram Setup
questions:
  - name: enabled
    kind: boolean
    required: true
  - name: bot_token
    kind: string
    required: true
    secret: true
"#;
    let spec = greentic_bundle::setup::legacy_formspec::parse_setup_spec_str(raw)
        .expect("parse legacy spec");
    let form = greentic_bundle::setup::legacy_formspec::setup_spec_to_form_spec(
        &spec,
        "messaging-telegram",
    );
    assert_eq!(form.id, "messaging-telegram-setup");
    assert_eq!(form.title, "Telegram Setup");
    assert_eq!(
        form.questions[0].kind,
        greentic_bundle::setup::QuestionKind::Boolean
    );
    assert!(form.questions[1].secret);
}

#[test]
fn provider_qa_bridge_output_is_stable() {
    let qa_output = json!({
        "mode": "setup",
        "title": {"key": "telegram.qa.setup.title"},
        "questions": [
            {"id": "enabled", "label": {"key": "telegram.qa.setup.enabled"}, "required": true},
            {"id": "bot_token", "label": {"key": "telegram.qa.setup.bot_token"}, "required": true}
        ]
    });
    let i18n = BTreeMap::from([
        ("telegram.qa.setup.title".to_string(), "Setup".to_string()),
        (
            "telegram.qa.setup.enabled".to_string(),
            "Enable".to_string(),
        ),
        (
            "telegram.qa.setup.bot_token".to_string(),
            "Bot token".to_string(),
        ),
    ]);

    let form = greentic_bundle::setup::qa_bridge::provider_qa_to_form_spec(
        &qa_output,
        &i18n,
        "messaging-telegram",
    );
    assert_eq!(form.id, "messaging-telegram-setup");
    assert_eq!(form.questions.len(), 2);
    assert_eq!(form.questions[0].title, "Enable");
    assert!(form.questions[1].secret);
}

#[test]
fn dry_run_setup_does_not_persist_side_effects() {
    let temp = TempDir::new().expect("tempdir");
    let root = temp.path().join("bundle");
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([(
            "provider-a".to_string(),
            json!({
                "type": "legacy",
                "spec": {
                    "title": "Provider A Setup",
                    "questions": [
                        {"name": "enabled", "kind": "boolean", "required": true}
                    ]
                }
            }),
        )]),
        &BTreeMap::from([("provider-a".to_string(), json!({"enabled": true}))]),
    )
    .expect("instructions");

    let result = greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::NoopSetupBackend,
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect("persist");
    assert_eq!(
        result.writes,
        vec!["state/setup/provider-a.json".to_string()]
    );
    assert!(!root.exists());
}

#[test]
fn replayed_setup_answers_produce_same_normalized_persisted_output() {
    let temp = TempDir::new().expect("tempdir");
    let root_one = temp.path().join("bundle-one");
    let root_two = temp.path().join("bundle-two");
    let answers_path = temp.path().join("answers.json");
    fs::write(
        &answers_path,
        format!(
            r#"{{
  "wizard_id":"greentic-bundle.wizard.run",
  "schema_id":"greentic-bundle.wizard.answers",
  "schema_version":"1.0.0",
  "locale":"en",
  "answers":{{
    "mode":"create",
    "bundle_name":"Demo Bundle",
    "bundle_id":"demo-bundle",
    "output_dir":"{}",
    "advanced_setup":true,
    "app_packs":[],
    "extension_providers":["provider-a"],
    "remote_catalogs":[],
    "setup_specs":{{
      "provider-a": {{
        "type":"legacy",
        "spec": {{
          "title":"Provider A Setup",
          "questions":[
            {{"name":"enabled","kind":"boolean","required":true}},
            {{"name":"api_token","kind":"string","required":true,"secret":true}}
          ]
        }}
      }}
    }},
    "setup_answers":{{
      "provider-a": {{"enabled":"true","api_token":"secret123"}}
    }},
    "setup_execution_intent":true,
    "export_intent":false
  }},
  "locks":{{}}
}}"#,
            root_one.display()
        ),
    )
    .expect("answers");

    let output_one = Command::new(bundle_bin())
        .args(["wizard", "apply", "--answers"])
        .arg(&answers_path)
        .output()
        .expect("apply one");
    assert!(
        output_one.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&output_one.stderr)
    );

    let state_one = read_json(&root_one.join("state/setup/provider-a.json"));
    assert!(root_one.join("state/setup/provider-a.json").exists());
    assert_eq!(
        state_one.get("source_kind").and_then(Value::as_str),
        Some("legacy")
    );
    assert!(state_one.get("non_secret_config").is_some());
    // B12: secret answers persist only as `secret://` refs — no plaintext in
    // `secret_values` (gone) or `normalized_answers`. The ref path includes
    // `provider_id` to disambiguate same-named secrets across providers.
    assert!(state_one.get("secret_values").is_none());
    assert_eq!(
        state_one
            .pointer("/secret_refs/api_token")
            .and_then(Value::as_str),
        Some("secret://local/demo-bundle/provider-a/api_token")
    );
    assert!(state_one.pointer("/normalized_answers/api_token").is_none());

    let rewritten = fs::read_to_string(&answers_path).expect("original answers");
    let rewritten = rewritten.replace(
        &root_one.display().to_string(),
        &root_two.display().to_string(),
    );
    fs::write(&answers_path, rewritten).expect("rewrite answers");

    let output_two = Command::new(bundle_bin())
        .args(["wizard", "apply", "--answers"])
        .arg(&answers_path)
        .output()
        .expect("apply two");
    assert!(
        output_two.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&output_two.stderr)
    );

    let state_two = read_json(&root_two.join("state/setup/provider-a.json"));
    assert_eq!(state_one, state_two);

    let lock = read_json(&root_one.join("bundle.lock.json"));
    assert_eq!(
        lock.pointer("/setup_state_files/0").and_then(Value::as_str),
        Some("state/setup/provider-a.json")
    );
}

#[test]
fn setup_persistence_applies_defaults_and_records_secret_refs() {
    let temp = TempDir::new().expect("tempdir");
    let root = temp.path().join("bundle");
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([(
            "provider-a".to_string(),
            json!({
                "type": "legacy",
                "spec": {
                    "title": "Provider A Setup",
                    "questions": [
                        {"name": "enabled", "kind": "boolean", "required": true},
                        {"name": "region", "kind": "string", "required": false, "default": "eu-west-1"},
                        {"name": "api_token", "kind": "string", "required": true, "secret": true}
                    ]
                }
            }),
        )]),
        &BTreeMap::from([(
            "provider-a".to_string(),
            json!({"enabled": "true", "api_token": "secret123"}),
        )]),
    )
    .expect("instructions");

    let result = greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::FileSetupBackend::new(&root),
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect("persist");

    assert_eq!(
        result.writes,
        vec!["state/setup/provider-a.json".to_string()]
    );
    let state = &result.states[0];
    assert_eq!(state.normalized_answers.get("enabled"), Some(&json!(true)));
    assert_eq!(
        state.normalized_answers.get("region"),
        Some(&json!("eu-west-1"))
    );
    assert_eq!(
        state.non_secret_config.get("region"),
        Some(&json!("eu-west-1"))
    );
    // The secret answer is recorded as a
    // `secret://<env>/<bundle>/<provider_id>/<question_id>` ref, never as
    // plaintext — and is dropped from normalized_answers too (B12).
    assert_eq!(
        state.secret_refs.get("api_token").map(|r| r.as_str()),
        Some("secret://local/test-bundle/provider-a/api_token")
    );
    assert!(!state.normalized_answers.contains_key("api_token"));
    assert!(!state.non_secret_config.contains_key("api_token"));
    assert!(root.join("state/setup/provider-a.json").exists());
}

/// Regression for the multi-provider collision flagged by Codex review:
/// two providers in the same bundle commonly share a secret key like
/// `api_token`, so the ref path must include `provider_id` or both refs alias
/// the same backend slot. Asserts the two refs are distinct and provider-scoped.
#[test]
fn secret_refs_disambiguate_same_question_id_across_providers() {
    let temp = TempDir::new().expect("tempdir");
    let root = temp.path().join("bundle");
    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "api_token", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([
            ("provider-a".to_string(), spec.clone()),
            ("provider-b".to_string(), spec),
        ]),
        &BTreeMap::from([
            ("provider-a".to_string(), json!({"api_token": "a-secret"})),
            ("provider-b".to_string(), json!({"api_token": "b-secret"})),
        ]),
    )
    .expect("instructions");

    let result = greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::FileSetupBackend::new(&root),
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect("persist");

    let by_provider: BTreeMap<&str, &greentic_bundle::setup::PersistedSetupState> = result
        .states
        .iter()
        .map(|s| (s.provider_id.as_str(), s))
        .collect();
    let a = by_provider.get("provider-a").expect("provider-a state");
    let b = by_provider.get("provider-b").expect("provider-b state");
    assert_eq!(
        a.secret_refs.get("api_token").map(|r| r.as_str()),
        Some("secret://local/test-bundle/provider-a/api_token")
    );
    assert_eq!(
        b.secret_refs.get("api_token").map(|r| r.as_str()),
        Some("secret://local/test-bundle/provider-b/api_token")
    );
    assert_ne!(
        a.secret_refs.get("api_token"),
        b.secret_refs.get("api_token"),
        "same question id across providers must mint distinct refs"
    );
}

/// Same answers + spec, different `env_id` on the scope → distinct refs.
/// Closes the env-scoping coverage gap in the replay-determinism test.
#[test]
fn secret_refs_discriminate_on_env_id() {
    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "api_token", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("provider-a".to_string(), spec)]),
        &BTreeMap::from([("provider-a".to_string(), json!({"api_token": "sec"}))]),
    )
    .expect("instructions");

    let mk = |env_id: &str| {
        let tmp = TempDir::new().expect("tempdir");
        let root = tmp.path().join("bundle");
        let r = greentic_bundle::setup::persist::persist_setup(
            &root,
            &instructions,
            &greentic_bundle::setup::backend::NoopSetupBackend,
            &greentic_bundle::setup::persist::SetupScope {
                env_id,
                bundle_id: "test-bundle",
            },
        )
        .expect("persist");
        r.states
            .into_iter()
            .next()
            .expect("one state")
            .secret_refs
            .get("api_token")
            .map(|r| r.as_str().to_string())
            .expect("ref")
    };
    let local = mk("local");
    let staging = mk("staging");
    assert_eq!(local, "secret://local/test-bundle/provider-a/api_token");
    assert_eq!(staging, "secret://staging/test-bundle/provider-a/api_token");
    assert_ne!(
        local, staging,
        "different env_id must produce different refs"
    );
}

/// Reject empty or `/`-bearing identifiers at mint time — these would
/// silently corrupt the 4-segment URI structure (SecretRef::try_new only
/// validates scheme + non-empty env segment).
#[test]
fn ref_segment_validation_rejects_slashes_and_empties() {
    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "tok", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("p".to_string(), spec.clone())]),
        &BTreeMap::from([("p".to_string(), json!({"tok": "sec"}))]),
    )
    .expect("instructions");
    let mk = |env_id, bundle_id| {
        let tmp = TempDir::new().expect("tempdir");
        let root = tmp.path().join("bundle");
        greentic_bundle::setup::persist::persist_setup(
            &root,
            &instructions,
            &greentic_bundle::setup::backend::NoopSetupBackend,
            &greentic_bundle::setup::persist::SetupScope { env_id, bundle_id },
        )
    };
    assert!(mk("", "test-bundle").is_err(), "empty env_id must error");
    assert!(
        mk("staging/eu", "test-bundle").is_err(),
        "env_id with `/` must error"
    );
    assert!(mk("local", "").is_err(), "empty bundle_id must error");
    assert!(
        mk("local", "test/bundle").is_err(),
        "bundle_id with `/` must error"
    );

    // provider_id with `/` (from a malformed `setup_specs` key)
    let bad_provider = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("my/provider".to_string(), spec.clone())]),
        &BTreeMap::from([("my/provider".to_string(), json!({"tok": "sec"}))]),
    )
    .expect("instructions");
    let tmp = TempDir::new().expect("tempdir");
    assert!(
        greentic_bundle::setup::persist::persist_setup(
            &tmp.path().join("bundle"),
            &bad_provider,
            &greentic_bundle::setup::backend::NoopSetupBackend,
            &greentic_bundle::setup::persist::SetupScope {
                env_id: "local",
                bundle_id: "test-bundle",
            },
        )
        .is_err(),
        "provider_id with `/` must error"
    );
}

/// Duplicate question id in a form spec must fail loudly — the previous
/// behavior would silently drop the second iteration after the first
/// removed the answer from `normalized_answers`.
#[test]
fn duplicate_question_id_in_form_spec_is_rejected() {
    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "api_token", "kind": "string", "required": true, "secret": true},
                {"name": "api_token", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("p".to_string(), spec)]),
        &BTreeMap::from([("p".to_string(), json!({"api_token": "sec"}))]),
    )
    .expect("instructions");
    let tmp = TempDir::new().expect("tempdir");
    let err = greentic_bundle::setup::persist::persist_setup(
        &tmp.path().join("bundle"),
        &instructions,
        &greentic_bundle::setup::backend::NoopSetupBackend,
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect_err("duplicate question id must error");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("duplicate question id") && msg.contains("api_token"),
        "error message must name the duplicate id, got: {msg}"
    );
}

#[test]
fn provider_qa_bridge_falls_back_to_ids_and_description_keys() {
    let qa_output = json!({
        "questions": [
            {
                "id": "api_token",
                "label": {"key": "provider.qa.setup.api_token"},
                "required": true,
                "default": "seed"
            }
        ]
    });
    let i18n = BTreeMap::from([(
        "provider.schema.config.api_token.description".to_string(),
        "API token for outbound calls".to_string(),
    )]);

    let form = greentic_bundle::setup::qa_bridge::provider_qa_to_form_spec(
        &qa_output,
        &i18n,
        "provider-a",
    );

    assert_eq!(form.id, "provider-a-setup");
    assert_eq!(form.title, "provider-a setup");
    assert_eq!(form.questions.len(), 1);
    assert_eq!(form.questions[0].title, "api_token");
    assert_eq!(
        form.questions[0].description.as_deref(),
        Some("API token for outbound calls")
    );
    assert_eq!(
        form.questions[0].default_value.as_ref(),
        Some(&json!("seed"))
    );
    assert!(form.questions[0].secret);
}

fn read_json(path: &Path) -> Value {
    serde_json::from_slice(&fs::read(path).expect("read json")).expect("parse json")
}

/// C7: persisted state records the active scope's `env_id`. Same provider,
/// same answers, two different scopes → two states whose `env_id` matches the
/// scope that built them.
#[test]
fn persisted_setup_state_records_env_id_from_scope() {
    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "api_token", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("provider-a".to_string(), spec)]),
        &BTreeMap::from([("provider-a".to_string(), json!({"api_token": "sec"}))]),
    )
    .expect("instructions");

    let mk = |env_id: &str| {
        let tmp = TempDir::new().expect("tempdir");
        let root = tmp.path().join("bundle");
        let r = greentic_bundle::setup::persist::persist_setup(
            &root,
            &instructions,
            &greentic_bundle::setup::backend::NoopSetupBackend,
            &greentic_bundle::setup::persist::SetupScope {
                env_id,
                bundle_id: "test-bundle",
            },
        )
        .expect("persist");
        r.states.into_iter().next().expect("one state").env_id
    };
    assert_eq!(mk("local"), "local");
    assert_eq!(mk("staging"), "staging");
}

/// C7: refuse to overwrite a state that was minted under a different env.
/// Aliases the same provider's `secret://` ref across two envs otherwise.
#[test]
fn persist_rejects_remint_under_different_env_id() {
    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "api_token", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("provider-a".to_string(), spec)]),
        &BTreeMap::from([("provider-a".to_string(), json!({"api_token": "sec"}))]),
    )
    .expect("instructions");

    let tmp = TempDir::new().expect("tempdir");
    let root = tmp.path().join("bundle");
    // Mint under `local`.
    greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::FileSetupBackend::new(&root),
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect("first persist");

    // Re-running the wizard under `staging` for the same (bundle, provider) must fail.
    let err = greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::FileSetupBackend::new(&root),
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "staging",
            bundle_id: "test-bundle",
        },
    )
    .expect_err("env_id remint must error");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("minted under env `local`") && msg.contains("env `staging`"),
        "error must name both envs, got: {msg}"
    );

    // Same env is allowed (overwrite is the happy path).
    greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::FileSetupBackend::new(&root),
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect("same-env remint must succeed");
}

/// C7: pre-C7 on-disk state files (schema_version <= 2, no `env_id`) are
/// rejected at remint time. Operator must delete the file and re-run the
/// wizard so the new state is bound to an env from the start.
#[test]
fn persist_rejects_pre_c7_state_without_env_id() {
    let tmp = TempDir::new().expect("tempdir");
    let root = tmp.path().join("bundle");
    fs::create_dir_all(root.join("state/setup")).expect("mkdir");
    fs::write(
        root.join("state/setup/provider-a.json"),
        r#"{"schema_version":2,"provider_id":"provider-a","source_kind":"legacy","form":{"id":"provider-a-setup","title":"x","version":"1.0.0","questions":[]},"normalized_answers":{},"non_secret_config":{},"secret_refs":{}}"#,
    )
    .expect("seed pre-C7 state");

    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "api_token", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("provider-a".to_string(), spec)]),
        &BTreeMap::from([("provider-a".to_string(), json!({"api_token": "sec"}))]),
    )
    .expect("instructions");

    let err = greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::FileSetupBackend::new(&root),
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect_err("pre-C7 state must be rejected");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("no env_id") && msg.contains("pre-C7"),
        "error must name the pre-C7 condition, got: {msg}"
    );
}

/// C7: corrupt (non-JSON) on-disk state files are rejected at remint time
/// rather than silently overwritten. Fail-closed: operator must delete the
/// file before re-running the wizard.
#[test]
fn persist_rejects_corrupt_state_file() {
    let tmp = TempDir::new().expect("tempdir");
    let root = tmp.path().join("bundle");
    fs::create_dir_all(root.join("state/setup")).expect("mkdir");
    fs::write(root.join("state/setup/provider-a.json"), b"NOT JSON").expect("seed corrupt state");

    let spec = json!({
        "type": "legacy",
        "spec": {
            "title": "Provider Setup",
            "questions": [
                {"name": "api_token", "kind": "string", "required": true, "secret": true}
            ]
        }
    });
    let instructions = greentic_bundle::setup::persist::collect_setup_instructions(
        &BTreeMap::from([("provider-a".to_string(), spec)]),
        &BTreeMap::from([("provider-a".to_string(), json!({"api_token": "sec"}))]),
    )
    .expect("instructions");

    let err = greentic_bundle::setup::persist::persist_setup(
        &root,
        &instructions,
        &greentic_bundle::setup::backend::FileSetupBackend::new(&root),
        &greentic_bundle::setup::persist::SetupScope {
            env_id: "local",
            bundle_id: "test-bundle",
        },
    )
    .expect_err("corrupt state must be rejected");
    let msg = format!("{err:#}");
    assert!(
        msg.contains("corrupt JSON"),
        "error must mention corrupt JSON, got: {msg}"
    );
}

/// C7: the bumped `SETUP_STATE_SCHEMA_VERSION` is what new states report.
/// Pinning the constant prevents an accidental rollback.
#[test]
fn persisted_state_advertises_c7_schema_version() {
    assert_eq!(greentic_bundle::setup::SETUP_STATE_SCHEMA_VERSION, 3);
}