stackless-stripe-projects 0.2.2

Stripe Projects CLI driver for stackless
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
//! The Stripe Projects CLI driver (ARCHITECTURE.md §4).
//!
//! Drives the `stripe projects` plugin non-interactively. The driver is
//! generic over a [`CommandRunner`] so tests inject canned CLI envelopes.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use async_trait::async_trait;
use serde::Deserialize;

use crate::error::ProjectsError;

const STRIPE_LOCK_BUDGET: Duration = Duration::from_secs(30 * 60);

/// Wire-format category filters matching [`crate::catalog::Category`] (excludes
/// `Unknown`). Used when unfiltered `catalog --json` returns an empty pipe.
const CATALOG_CATEGORY_FILTERS: &[&str] = &[
    "ai",
    "analytics",
    "auth",
    "browser",
    "cache",
    "cdn",
    "ci",
    "communications",
    "compute",
    "database",
    "domains",
    "ecommerce",
    "email",
    "feature_flags",
    "messaging",
    "notification",
    "observability",
    "payments",
    "queue",
    "sandbox",
    "search",
    "storage",
];

fn json_object_slice(stdout: &str) -> Option<&str> {
    stdout.find('{').map(|start| &stdout[start..])
}

fn envelope_service_count(json: &str) -> usize {
    serde_json::from_str::<serde_json::Value>(json)
        .ok()
        .map(|value| services_in_envelope(&value))
        .unwrap_or(0)
}

fn services_in_envelope(envelope: &serde_json::Value) -> usize {
    envelope
        .pointer("/data/services")
        .and_then(serde_json::Value::as_array)
        .map(Vec::len)
        .unwrap_or(0)
}

#[derive(Debug, Clone)]
pub struct CommandOutput {
    pub status: i32,
    pub stdout: String,
    pub stderr: String,
}

#[async_trait]
pub trait CommandRunner: Send + Sync {
    async fn run(&self, args: &[String], cwd: &Path) -> Result<CommandOutput, ProjectsError>;
}

#[async_trait]
impl<T: CommandRunner + ?Sized> CommandRunner for &T {
    async fn run(&self, args: &[String], cwd: &Path) -> Result<CommandOutput, ProjectsError> {
        (**self).run(args, cwd).await
    }
}

#[derive(Debug, Default)]
pub struct TokioRunner;

#[async_trait]
impl CommandRunner for TokioRunner {
    async fn run(&self, args: &[String], cwd: &Path) -> Result<CommandOutput, ProjectsError> {
        let args = args.to_vec();
        let cwd: PathBuf = cwd.to_path_buf();
        tokio::task::spawn_blocking(move || run_stripe_locked(&args, &cwd))
            .await
            .map_err(|err| ProjectsError::Unavailable {
                detail: format!("stripe task panicked: {err}"),
            })?
    }
}

fn run_stripe_locked(args: &[String], cwd: &Path) -> Result<CommandOutput, ProjectsError> {
    let lock_path = stackless_core::lockfile::FileLock::stripe_lock_path(cwd);
    let _guard =
        stackless_core::lockfile::FileLock::acquire_with_wait(&lock_path, STRIPE_LOCK_BUDGET)
            .map_err(|err| ProjectsError::LockHeld {
                definition_dir: cwd.display().to_string(),
                detail: err.to_string(),
            })?;
    let output = std::process::Command::new("stripe")
        .arg("projects")
        .args(args)
        .current_dir(cwd)
        .output()
        .map_err(|err| ProjectsError::Unavailable {
            detail: format!("could not run `stripe`: {err}"),
        })?;
    Ok(CommandOutput {
        status: output.status.code().unwrap_or(-1),
        stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
    })
}

#[derive(Debug, Deserialize)]
struct Envelope {
    ok: bool,
    #[serde(default)]
    error: Option<EnvelopeError>,
    #[serde(default)]
    data: Option<serde_json::Value>,
    #[serde(default)]
    meta: Option<EnvelopeMeta>,
}

#[derive(Debug, Deserialize)]
struct EnvelopeError {
    #[serde(default)]
    code: Option<String>,
    #[serde(default)]
    message: Option<String>,
    #[serde(default)]
    details: Option<serde_json::Value>,
}

#[derive(Debug, Deserialize)]
struct EnvelopeMeta {
    #[serde(default)]
    authenticated: Option<bool>,
}

#[derive(Debug, Clone)]
pub struct StripeResult {
    pub ok: bool,
    pub error_code: Option<String>,
    pub error_message: Option<String>,
    pub error_details: Option<serde_json::Value>,
    pub authenticated: bool,
    pub data: serde_json::Value,
}

const PLAIN_FALLBACK_CODES: &[&str] = &[
    "JSON_REQUIRES_CONFIRMATION",
    "JSON_REQUIRES_AUTH",
    "DIRECTORY_SELECTION_REQUIRED",
];

pub struct StripeProjects<R: CommandRunner> {
    runner: R,
    dir: PathBuf,
}

impl<R: CommandRunner> std::fmt::Debug for StripeProjects<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StripeProjects")
            .field("dir", &self.dir)
            .finish_non_exhaustive()
    }
}

impl<R: CommandRunner> StripeProjects<R> {
    pub fn new(runner: R, dir: impl Into<PathBuf>) -> Self {
        Self {
            runner,
            dir: dir.into(),
        }
    }

    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Borrow as a `StripeProjects<&dyn CommandRunner>` so callers holding a
    /// `dyn` dispatch target can run commands without being generic over `R`
    /// (`impl CommandRunner for &T` makes the erased runner a valid runner).
    pub fn as_dyn(&self) -> StripeProjects<&'_ dyn CommandRunner> {
        StripeProjects {
            runner: &self.runner as &dyn CommandRunner,
            dir: self.dir.clone(),
        }
    }

    #[cfg(test)]
    fn runner(&self) -> &R {
        &self.runner
    }

    pub async fn json(&self, args: &[&str]) -> Result<StripeResult, ProjectsError> {
        let mut argv: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
        argv.push("--json".into());
        let out = self.runner.run(&argv, &self.dir).await?;
        let Some(start) = out.stdout.find('{') else {
            let stderr = out.stderr.trim();
            return Err(ProjectsError::Unavailable {
                detail: format!(
                    "`stripe projects {}` exited without delivering a JSON envelope{}",
                    args.join(" "),
                    if stderr.is_empty() {
                        String::new()
                    } else {
                        format!(" (stderr: {stderr})")
                    }
                ),
            });
        };
        let envelope: Envelope = serde_json::from_str(&out.stdout[start..]).map_err(|err| {
            ProjectsError::Unavailable {
                detail: format!(
                    "`stripe projects {}` exited without delivering a parseable JSON envelope: {err}",
                    args.join(" ")
                ),
            }
        })?;
        Ok(StripeResult {
            ok: envelope.ok,
            error_code: envelope.error.as_ref().and_then(|e| e.code.clone()),
            error_message: envelope.error.as_ref().and_then(|e| e.message.clone()),
            error_details: envelope.error.as_ref().and_then(|e| e.details.clone()),
            authenticated: envelope
                .meta
                .as_ref()
                .and_then(|m| m.authenticated)
                .unwrap_or(true),
            data: envelope.data.unwrap_or(serde_json::Value::Null),
        })
    }

    /// Unfiltered catalog (`stripe projects catalog --json`).
    ///
    /// For live drift / full-model tooling only. Provisioning must use
    /// [`Self::catalog_for_reference`].
    pub async fn catalog(&self) -> Result<crate::catalog::Catalog, ProjectsError> {
        let json = self.catalog_envelope_json().await?;
        crate::catalog::Catalog::from_json_envelope(&json).map_err(|err| {
            ProjectsError::Unavailable {
                detail: format!("`stripe projects catalog` returned an unmodeled catalog: {err}"),
            }
        })
    }

    /// Full `{ok, data, …}` envelope text for `catalog --json`.
    ///
    /// Plugin 0.29.0 (and possibly later) often emits an empty stdout for the
    /// unfiltered catalog when stdout is a pipe. Filtered
    /// `catalog <category> --json` still works, so we fall back to merging every
    /// known [`crate::catalog::Category`] filter when the unfiltered call is
    /// empty or non-JSON. Auth / `ok: false` envelopes are classified and
    /// returned as faults — they must not trigger the empty-pipe fallback.
    pub async fn catalog_envelope_json(&self) -> Result<String, ProjectsError> {
        let raw = self.plain(&["catalog", "--json"]).await?;
        let Some(json) = json_object_slice(&raw.stdout) else {
            return self.catalog_envelope_json_by_categories().await;
        };
        if let Some(fault) = self.catalog_envelope_fault(json) {
            return Err(fault);
        }
        if envelope_service_count(json) > 0 {
            return Ok(json.to_owned());
        }
        // Authenticated ok:true with an empty services list is a real empty
        // catalog, not the empty-pipe bug. Return it as-is.
        Ok(json.to_owned())
    }

    /// Classify a parsed catalog envelope that is not a successful service list.
    /// Returns `None` when the JSON is `ok: true` (caller decides empty vs full).
    fn catalog_envelope_fault(&self, json: &str) -> Option<ProjectsError> {
        let envelope: Envelope = serde_json::from_str(json).ok()?;
        if envelope.ok {
            return None;
        }
        let result = StripeResult {
            ok: envelope.ok,
            error_code: envelope.error.as_ref().and_then(|e| e.code.clone()),
            error_message: envelope.error.as_ref().and_then(|e| e.message.clone()),
            error_details: envelope.error.as_ref().and_then(|e| e.details.clone()),
            authenticated: envelope
                .meta
                .as_ref()
                .and_then(|m| m.authenticated)
                .unwrap_or(true),
            data: envelope.data.unwrap_or(serde_json::Value::Null),
        };
        Some(self.classify_failure("catalog", &result))
    }

    async fn catalog_envelope_json_by_categories(&self) -> Result<String, ProjectsError> {
        let mut services: BTreeMap<String, serde_json::Value> = BTreeMap::new();
        let mut template: Option<serde_json::Value> = None;
        for filter in CATALOG_CATEGORY_FILTERS {
            let raw = self.plain(&["catalog", filter, "--json"]).await?;
            let Some(json) = json_object_slice(&raw.stdout) else {
                continue;
            };
            if let Some(fault) = self.catalog_envelope_fault(json) {
                return Err(fault);
            }
            let mut envelope: serde_json::Value =
                serde_json::from_str(json).map_err(|err| ProjectsError::Unavailable {
                    detail: format!(
                        "`stripe projects catalog {filter} --json` emitted malformed JSON: {err}"
                    ),
                })?;
            if let Some(list) = envelope
                .pointer_mut("/data/services")
                .and_then(serde_json::Value::as_array_mut)
            {
                for service in list.drain(..) {
                    let id = service
                        .get("id")
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or_default()
                        .to_owned();
                    if !id.is_empty() {
                        services.insert(id, service);
                    }
                }
            }
            if template.is_none() {
                template = Some(envelope);
            }
        }
        let mut envelope = template.ok_or_else(|| ProjectsError::Unavailable {
            detail: "`stripe projects catalog --json` produced no JSON, and every category filter was empty"
                .into(),
        })?;
        if let Some(data) = envelope
            .get_mut("data")
            .and_then(serde_json::Value::as_object_mut)
        {
            data.insert("provider".into(), serde_json::Value::Null);
            data.insert("category_filter".into(), serde_json::Value::Null);
            data.insert("provider_filter".into(), serde_json::Value::Null);
            data.insert(
                "services".into(),
                serde_json::Value::Array(services.into_values().collect()),
            );
        }
        if services_in_envelope(&envelope) == 0 {
            return Err(ProjectsError::Unavailable {
                detail: "`stripe projects catalog` returned no services via unfiltered or category filters"
                    .into(),
            });
        }
        Ok(envelope.to_string())
    }

    /// Provider-scoped catalog for a `provider/service` reference.
    ///
    /// Runs `stripe projects catalog <provider> --json` once. The CLI filter
    /// accepts a category or provider name; we pass the provider slug from the
    /// reference (everything before the first `/`).
    pub async fn catalog_for_reference(
        &self,
        reference: &str,
    ) -> Result<crate::catalog::Catalog, ProjectsError> {
        let provider = provider_from_reference(reference);
        let data = self.run_ok("catalog", &["catalog", provider], &[]).await?;
        let catalog: crate::catalog::Catalog =
            serde_json::from_value(data).map_err(|err| ProjectsError::Unavailable {
                detail: format!(
                    "`stripe projects catalog {provider}` returned an unmodeled catalog: {err}"
                ),
            })?;
        if catalog.lookup(reference).is_none() {
            return Err(ProjectsError::CatalogMissing {
                reference: reference.to_owned(),
            });
        }
        Ok(catalog)
    }

    /// Provider-scoped catalog for a [`crate::catalog::verify::CatalogService`].
    pub async fn catalog_for<C: crate::catalog::verify::CatalogService>(
        &self,
    ) -> Result<crate::catalog::Catalog, ProjectsError> {
        self.catalog_for_reference(C::REFERENCE).await
    }

    pub async fn plain(&self, args: &[&str]) -> Result<CommandOutput, ProjectsError> {
        let argv: Vec<String> = args.iter().map(|a| (*a).to_owned()).collect();
        self.runner.run(&argv, &self.dir).await
    }

    pub fn classify_failure(&self, command: &str, result: &StripeResult) -> ProjectsError {
        let message = result
            .error_message
            .clone()
            .unwrap_or_else(|| "unknown error".into());
        let code = result.error_code.as_deref().unwrap_or("");
        let auth_like = !result.authenticated
            || code == "JSON_REQUIRES_AUTH"
            || message.to_ascii_lowercase().contains("not authenticated")
            || message.to_ascii_lowercase().contains("log in");
        if auth_like {
            ProjectsError::Auth { detail: message }
        } else {
            ProjectsError::Failed {
                command: command.to_owned(),
                detail: format!(
                    "{message}{}",
                    if code.is_empty() {
                        String::new()
                    } else {
                        format!(" ({code})")
                    }
                ),
            }
        }
    }

    pub async fn run_ok(
        &self,
        command: &str,
        args: &[&str],
        plain_extra: &[&str],
    ) -> Result<serde_json::Value, ProjectsError> {
        let result = self.json(args).await?;
        if result.ok {
            return Ok(result.data);
        }
        let code = result.error_code.as_deref().unwrap_or("");
        let message = result.error_message.clone().unwrap_or_default();
        let live_mode = message.to_ascii_lowercase().contains("live mode");
        if PLAIN_FALLBACK_CODES.contains(&code) || live_mode {
            let mut plain_args: Vec<&str> = args.to_vec();
            plain_args.extend_from_slice(plain_extra);
            let out = self.plain(&plain_args).await?;
            if out.status != 0 || out.stdout.contains('') || out.stderr.contains('') {
                return Err(ProjectsError::Failed {
                    command: command.to_owned(),
                    detail: merge_output(&out),
                });
            }
            return Ok(serde_json::Value::Null);
        }
        Err(self.classify_failure(command, &result))
    }
}

fn merge_output(out: &CommandOutput) -> String {
    let merged = format!("{}{}", out.stdout.trim(), out.stderr.trim());
    merged.trim().to_owned()
}

/// Provider filter token for `stripe projects catalog <provider>`.
pub fn provider_from_reference(reference: &str) -> &str {
    reference
        .split_once('/')
        .map(|(p, _)| p)
        .unwrap_or(reference)
}

#[cfg(test)]
mod tests {
    use super::*;
    use stackless_core::fault::{Fault, codes};
    use std::sync::Mutex;

    struct ScriptRunner {
        outputs: Mutex<std::collections::VecDeque<CommandOutput>>,
        calls: Mutex<Vec<Vec<String>>>,
    }

    impl ScriptRunner {
        fn new(outputs: Vec<CommandOutput>) -> Self {
            Self {
                outputs: Mutex::new(outputs.into()),
                calls: Mutex::new(Vec::new()),
            }
        }

        fn calls(&self) -> Vec<Vec<String>> {
            self.calls.lock().unwrap().clone()
        }
    }

    #[async_trait]
    impl CommandRunner for ScriptRunner {
        async fn run(&self, args: &[String], _cwd: &Path) -> Result<CommandOutput, ProjectsError> {
            self.calls.lock().unwrap().push(args.to_vec());
            self.outputs
                .lock()
                .unwrap()
                .pop_front()
                .ok_or_else(|| ProjectsError::Unavailable {
                    detail: "ScriptRunner exhausted".into(),
                })
        }
    }

    fn out(status: i32, stdout: &str, stderr: &str) -> CommandOutput {
        CommandOutput {
            status,
            stdout: stdout.to_owned(),
            stderr: stderr.to_owned(),
        }
    }

    fn driver(outputs: Vec<CommandOutput>) -> StripeProjects<ScriptRunner> {
        StripeProjects::new(ScriptRunner::new(outputs), std::env::temp_dir())
    }

    #[tokio::test]
    async fn parses_ok_envelope() {
        let d = driver(vec![out(
            0,
            r#"{"ok":true,"command":"status","version":"0.19.0","data":{"project":{"id":"proj_1"}}}"#,
            "",
        )]);
        let result = d.json(&["status"]).await.unwrap();
        assert!(result.ok);
        assert_eq!(result.data["project"]["id"], "proj_1");
    }

    #[tokio::test]
    async fn no_json_is_unavailable() {
        let d = driver(vec![out(127, "", "command not found: stripe")]);
        let err = d.json(&["status"]).await.unwrap_err();
        assert_eq!(err.code(), codes::STRIPE_PROJECTS_UNAVAILABLE);
        assert!(
            err.to_string()
                .contains("exited without delivering a JSON envelope"),
            "detail should name the missing envelope, got: {err}"
        );
    }

    #[test]
    fn provider_from_reference_splits_on_first_slash() {
        assert_eq!(provider_from_reference("clerk/auth"), "clerk");
        assert_eq!(
            provider_from_reference("wordpress.com/site"),
            "wordpress.com"
        );
        assert_eq!(
            provider_from_reference("cloudflare/r2:bucket"),
            "cloudflare"
        );
        assert_eq!(
            provider_from_reference("laravel_cloud/mysql"),
            "laravel_cloud"
        );
        assert_eq!(provider_from_reference("bare"), "bare");
    }

    fn clerk_auth_catalog_envelope() -> String {
        // Filtered live responses may set `provider` / `provider_filter` to an
        // object rather than a string (observed on vercel/render smokes).
        serde_json::json!({
            "ok": true,
            "command": "catalog",
            "data": {
                "last_updated": "1970-01-01T00:00:00.000Z",
                "provider": { "id": "prvdr_clerk", "name": "Clerk" },
                "provider_filter": { "name": "clerk" },
                "source": "cache",
                "services": [{
                    "id": "clerk_auth",
                    "object": "service",
                    "provider_id": "clerk",
                    "provider_name": "Clerk",
                    "service_id": "auth",
                    "kind": "saas",
                    "scope": "account",
                    "availability": "available",
                    "development": true,
                    "livemode": true,
                    "pricing": { "type": "free" }
                }]
            }
        })
        .to_string()
    }

    #[tokio::test]
    async fn catalog_for_reference_passes_provider_filter() {
        let d = driver(vec![out(0, &clerk_auth_catalog_envelope(), "")]);
        let catalog = d
            .catalog_for_reference("clerk/auth")
            .await
            .expect("scoped catalog");
        assert!(catalog.lookup("clerk/auth").is_some());
        assert_eq!(
            d.runner().calls(),
            vec![vec![
                "catalog".to_owned(),
                "clerk".to_owned(),
                "--json".to_owned()
            ]]
        );
    }

    #[tokio::test]
    async fn catalog_for_reference_missing_service_is_catalog_missing() {
        let empty = serde_json::json!({
            "ok": true,
            "command": "catalog",
            "data": {
                "last_updated": "1970-01-01T00:00:00.000Z",
                "provider_filter": "clerk",
                "services": []
            }
        })
        .to_string();
        let d = driver(vec![out(0, &empty, "")]);
        let err = d.catalog_for_reference("clerk/auth").await.unwrap_err();
        assert_eq!(err.code(), codes::STRIPE_PROJECTS_CATALOG_MISSING);
    }

    #[tokio::test]
    async fn catalog_envelope_falls_back_to_category_filters() {
        let service = r#"{"id":"prvsvc_1","object":"v2.provisioning.provider_service_detail","provider_id":"prvdr_1","provider_name":"Neon","service_id":"postgres","categories":["database"],"kind":"deployable","scope":"project","availability":"available","development":false,"livemode":true,"pricing":{"type":"free"}}"#;
        let filtered = format!(
            r#"{{"ok":true,"command":"projects catalog","version":"0.1","data":{{"last_updated":"t","provider":null,"category_filter":"database","provider_filter":null,"services":[{service}],"source":null}}}}"#
        );
        // Unfiltered empty, then one hit on the database filter; remaining
        // category probes return empty objects so the merge still completes.
        let mut outputs = vec![out(0, "", "")];
        for filter in CATALOG_CATEGORY_FILTERS {
            if *filter == "database" {
                outputs.push(out(0, &filtered, ""));
            } else {
                outputs.push(out(
                    0,
                    r#"{"ok":true,"command":"projects catalog","version":"0.1","data":{"last_updated":"t","provider":null,"category_filter":null,"provider_filter":null,"services":[],"source":null}}"#,
                    "",
                ));
            }
        }
        let d = driver(outputs);
        let json = d.catalog_envelope_json().await.unwrap();
        let catalog = crate::catalog::Catalog::from_json_envelope(&json).unwrap();
        assert_eq!(catalog.services.len(), 1);
        assert_eq!(catalog.services[0].reference(), "neon/postgres");
        assert!(catalog.category_filter.is_none());
    }

    #[tokio::test]
    async fn unauthenticated_envelope_is_auth_fault() {
        let d = driver(vec![out(
            0,
            r#"{"ok":false,"error":{"code":"SOMETHING","message":"please log in"},"meta":{"authenticated":false}}"#,
            "",
        )]);
        let err = d.run_ok("status", &["status"], &[]).await.unwrap_err();
        assert_eq!(err.code(), codes::STRIPE_PROJECTS_AUTH);
    }

    #[tokio::test]
    async fn unauthenticated_catalog_envelope_is_auth_fault_not_empty_pipe_fallback() {
        let d = driver(vec![out(
            0,
            r#"{"ok":false,"error":{"code":"SOMETHING","message":"please log in"},"meta":{"authenticated":false}}"#,
            "",
        )]);
        let err = d.catalog_envelope_json().await.unwrap_err();
        assert_eq!(err.code(), codes::STRIPE_PROJECTS_AUTH);
        // Only the unfiltered call — must not probe category filters.
        assert_eq!(d.runner().calls().len(), 1);
        assert_eq!(
            d.runner().calls()[0],
            vec!["catalog".to_owned(), "--json".to_owned()]
        );
    }

    /// Opt-in live check (`STRIPE_CATALOG_LIVE=1`): run the real
    /// `stripe projects catalog --json` and assert the typed model still fully
    /// covers it. No-op in CI; the canonical way to catch a stale fixture.
    #[tokio::test]
    async fn live_catalog_matches_model() {
        if std::env::var("STRIPE_CATALOG_LIVE").as_deref() != Ok("1") {
            return;
        }
        let dir = std::env::current_dir().unwrap();
        let stripe = StripeProjects::new(TokioRunner, dir);
        let catalog = stripe.catalog().await.expect("live catalog should fetch");
        let report = catalog.drift_report();
        assert!(
            report.is_empty(),
            "LIVE catalog drift — refresh tests/fixtures/catalog.json and update the model:\n{}",
            report.join("\n")
        );
    }

    /// The per-catalog-state content version (`data.last_updated`) is stable
    /// across requests but bumps whenever Stripe republishes the catalog —
    /// noise unrelated to a real service/schema change. Normalize it so the
    /// committed `catalog.json` only diffs on content we actually model.
    const NORMALIZED_TIMESTAMP: &str = "1970-01-01T00:00:00.000Z";

    /// Bless mode (`STRIPE_PROJECTS_REFRESH=1`): regenerate the three committed
    /// snapshots — `plugin-version.txt`, `catalog.json`, `command-surface.txt` —
    /// from the LOCALLY INSTALLED plugin. The only path that writes fixtures;
    /// invoked by `mise run stripe-refresh` and the CI watcher. A no-op (and
    /// needs no `stripe`) otherwise, so it stays inert in the hermetic gate.
    #[tokio::test]
    async fn refresh_blesses_snapshots() {
        if std::env::var("STRIPE_PROJECTS_REFRESH").as_deref() != Ok("1") {
            return;
        }
        let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
        let stripe = StripeProjects::new(TokioRunner, std::env::current_dir().unwrap());

        // 1. Pinned plugin version.
        let version = crate::surface::plugin_version(&stripe)
            .await
            .expect("probe `stripe projects --version`");

        // 2. Catalog envelope — refuse to bless anything the typed model can't
        //    fully represent (forces a src/catalog.rs update first). Uses
        //    [`StripeProjects::catalog_envelope_json`] so an empty unfiltered
        //    pipe (plugin 0.29.0) still blesses via category filters.
        let json = stripe
            .catalog_envelope_json()
            .await
            .expect("run `stripe projects catalog --json`");
        let report = crate::catalog::Catalog::from_json_envelope(&json)
            .expect("catalog envelope parses")
            .drift_report();
        assert!(
            report.is_empty(),
            "live catalog has unmodeled drift — update src/catalog.rs before blessing:\n{}",
            report.join("\n")
        );
        let mut envelope: serde_json::Value =
            serde_json::from_str(&json).expect("catalog envelope is JSON");
        if let Some(data) = envelope
            .get_mut("data")
            .and_then(serde_json::Value::as_object_mut)
            && data.contains_key("last_updated")
        {
            data.insert(
                "last_updated".into(),
                serde_json::Value::String(NORMALIZED_TIMESTAMP.into()),
            );
        }
        let catalog_pretty = format!(
            "{}\n",
            serde_json::to_string_pretty(&envelope).expect("serialize catalog")
        );

        // 3. Command surface (header carries the pinned version).
        let body = crate::surface::command_surface(&stripe)
            .await
            .expect("capture command surface");
        let surface = crate::surface::render_surface(&version, &body);

        std::fs::write(fixtures.join("catalog.json"), catalog_pretty).unwrap();
        std::fs::write(fixtures.join("command-surface.txt"), surface).unwrap();
        std::fs::write(fixtures.join("plugin-version.txt"), format!("{version}\n")).unwrap();
        eprintln!("blessed snapshots for stripe projects plugin v{version}");
    }

    #[tokio::test]
    async fn confirmation_code_falls_back_to_plain_mode() {
        let d = driver(vec![
            out(
                0,
                r#"{"ok":false,"error":{"code":"JSON_REQUIRES_CONFIRMATION","message":"needs confirmation"}}"#,
                "",
            ),
            out(0, "✓ created project", ""),
        ]);
        d.run_ok(
            "init",
            &["init", "atto", "--skip-skills", "--accept-tos"],
            &["--accept-tos", "--yes"],
        )
        .await
        .unwrap();
        let calls = d.runner().calls();
        assert_eq!(calls.len(), 2);
        assert!(calls[0].contains(&"--json".to_owned()));
        assert!(!calls[1].contains(&"--json".to_owned()));
        assert!(calls[1].contains(&"--yes".to_owned()));
    }
}