cli-engine 0.9.3

Rust CLI framework for consistent command modules
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
use std::{collections::HashMap, time::Duration};

use chrono::{SecondsFormat, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::error::DetailedError;

/// Top-level output envelope rendered for successful and failed commands.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Envelope {
    /// Successful command data.
    #[serde(skip_serializing_if = "is_absent_or_null")]
    pub data: Option<Value>,
    /// Client-side pagination facts, present whenever pagination was
    /// actually applied — an effective `--limit` or `--offset` greater than
    /// zero, not merely a command that opted into
    /// [`with_pagination`](crate::CommandSpec::with_pagination) — regardless
    /// of `--verbose`. A `default_limit` of `0` ("unlimited") with neither
    /// flag passed leaves this `None` even for a paginating command. Unlike
    /// [`metadata`](Envelope::metadata), this is not debugging output; a
    /// caller relies on it to know whether more data exists at all.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pagination: Option<PaginationMeta>,
    /// Optional execution metadata, controlled by `--verbose`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Metadata>,
    /// Structured error information for failed commands.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorEnvelope>,
    /// Non-fatal warnings.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub warnings: Vec<String>,
    /// Suggested follow-up actions for the caller (agent or human).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub next_actions: Vec<NextAction>,
    /// Optional recovery guidance for failed commands.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fix: Option<String>,
    #[serde(default, skip)]
    serialization_error: Option<String>,
}

/// A suggested follow-up command the caller can run next.
///
/// Construct with [`NextAction::new`], then chain `with_*` methods — never as
/// a struct literal. `#[non_exhaustive]` enforces this so the engine can add
/// fields without a breaking release.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct NextAction {
    /// Executable command template, e.g. `"application info --name <name>"`.
    /// A param's placeholder is its key wrapped in angle brackets (`<key>`);
    /// human output substitutes it when the param carries a known
    /// [`NextActionParam::value`].
    pub command: String,
    /// Human-readable description of what this action does.
    pub description: String,
    /// Optional parameter hints for agent-driven invocation.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub params: HashMap<String, NextActionParam>,
}

impl NextAction {
    /// Creates a next action with a command template and description.
    #[must_use]
    pub fn new(command: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            command: command.into(),
            description: description.into(),
            params: HashMap::new(),
        }
    }

    /// Adds a parameter hint.
    #[must_use]
    pub fn with_param(mut self, name: impl Into<String>, param: NextActionParam) -> Self {
        self.params.insert(name.into(), param);
        self
    }
}

/// Metadata hint for a parameter in a [`NextAction`] command template.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)]
pub struct NextActionParam {
    /// Concrete value to substitute, if known.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
    /// Allowed values for enumeration parameters.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub r#enum: Vec<String>,
    /// Whether the parameter is required.
    #[serde(default, skip_serializing_if = "is_false")]
    pub required: bool,
    /// Default value when none is supplied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    /// Human-readable description of this parameter.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl NextActionParam {
    /// Creates a parameter hint with a known concrete value.
    #[must_use]
    pub fn value(value: impl Into<String>) -> Self {
        Self {
            value: Some(value.into()),
            ..Self::default()
        }
    }

    /// Creates a required parameter hint.
    #[must_use]
    pub fn required() -> Self {
        Self {
            required: true,
            ..Self::default()
        }
    }
}

/// Execution metadata attached to an [`Envelope`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Metadata {
    /// Backend/system id.
    pub system: String,
    /// UTC timestamp in RFC3339 seconds format.
    pub timestamp: String,
    /// Optional backend request id.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub request_id: String,
    /// Whether the command was a dry-run response.
    #[serde(skip_serializing_if = "is_false")]
    pub dry_run: bool,
    /// Colon-separated command path.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub command: String,
    /// Rounded command duration.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub duration: String,
    /// Selected environment.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub env: String,
    /// Authenticated identity.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub identity: String,
    /// User-supplied args.
    #[serde(skip_serializing_if = "is_absent_null_or_empty_object")]
    pub args: Option<Value>,
    /// Effective args after defaults and middleware injection.
    #[serde(skip_serializing_if = "is_absent_null_or_empty_object")]
    pub effective_args: Option<Value>,
}

/// Client-side pagination metadata.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PaginationMeta {
    /// Total list items before pagination.
    pub total: i64,
    /// Applied offset.
    pub offset: i64,
    /// Applied limit.
    pub limit: i64,
    /// Item count after pagination.
    pub count: i64,
    /// Whether items beyond this page remain (`offset + count < total`).
    pub has_more: bool,
}

/// Structured error payload in an [`Envelope`].
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct ErrorEnvelope {
    /// Stable error code.
    pub code: String,
    /// Human-readable error message.
    pub message: String,
    /// Optional backend/system id.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub system: String,
    /// Optional backend request id.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub request_id: String,
}

impl Envelope {
    /// Creates a success envelope from serializable data.
    #[must_use]
    pub fn success(data: impl Serialize, system: impl Into<String>) -> Self {
        let (data, serialization_error) = match serde_json::to_value(data) {
            Ok(data) => (Some(data), None),
            Err(err) => (None, Some(err.to_string())),
        };
        Self {
            data,
            pagination: None,
            metadata: Some(Metadata::new(system)),
            error: None,
            warnings: Vec::new(),
            next_actions: Vec::new(),
            fix: None,
            serialization_error,
        }
    }

    /// Creates a generic error envelope.
    #[must_use]
    pub fn error(
        code: impl Into<String>,
        message: impl Into<String>,
        system: impl Into<String>,
    ) -> Self {
        let system = system.into();
        Self {
            data: None,
            pagination: None,
            metadata: Some(Metadata::new(system.clone())),
            error: Some(ErrorEnvelope {
                code: code.into(),
                message: message.into(),
                system,
                request_id: String::new(),
            }),
            warnings: Vec::new(),
            next_actions: Vec::new(),
            fix: None,
            serialization_error: None,
        }
    }

    /// Creates a structured error envelope with request id.
    #[must_use]
    pub fn error_detail(
        code: impl Into<String>,
        message: impl Into<String>,
        system: impl Into<String>,
        request_id: impl Into<String>,
    ) -> Self {
        let system = system.into();
        let request_id = request_id.into();
        Self {
            data: None,
            pagination: None,
            metadata: Some(Metadata {
                request_id: request_id.clone(),
                ..Metadata::new(system.clone())
            }),
            error: Some(ErrorEnvelope {
                code: code.into(),
                message: message.into(),
                system,
                request_id,
            }),
            warnings: Vec::new(),
            next_actions: Vec::new(),
            fix: None,
            serialization_error: None,
        }
    }

    /// Attaches suggested follow-up actions.
    #[must_use]
    pub fn with_next_actions(mut self, actions: Vec<NextAction>) -> Self {
        self.next_actions = actions;
        self
    }

    /// Attaches recovery guidance for a failed command (no-op on success envelopes).
    #[must_use]
    pub fn with_fix(mut self, fix: impl Into<String>) -> Self {
        if self.error.is_some() {
            let fix = fix.into();
            self.fix = (!fix.is_empty()).then_some(fix);
        }
        self
    }

    /// Marks the envelope as a dry-run response.
    #[must_use]
    pub fn with_dry_run(mut self) -> Self {
        if let Some(metadata) = &mut self.metadata {
            metadata.dry_run = true;
        }
        self
    }

    /// Adds command execution context to envelope metadata.
    pub fn with_context(
        &mut self,
        command: &str,
        env: &str,
        identity: &str,
        duration: Duration,
        user_args: Option<Value>,
        effective_args: Option<Value>,
    ) {
        if let Some(metadata) = &mut self.metadata {
            metadata.command = command.to_owned();
            metadata.env = env.to_owned();
            metadata.identity = identity.to_owned();
            metadata.duration = format_duration(duration);
            metadata.args = user_args;
            metadata.effective_args = effective_args;
        }
    }

    /// Returns a copy with metadata stripped or filtered according to `--verbose`.
    #[must_use]
    pub fn prepare_for_render(&self, verbose: &str) -> Self {
        let mut copy = self.clone();
        if verbose.is_empty() {
            copy.metadata = None;
            return copy;
        }
        if verbose == "all" {
            return copy;
        }
        if let Some(metadata) = &self.metadata {
            copy.metadata = Some(metadata.filter_fields(verbose));
        }
        copy
    }

    /// Appends a non-fatal warning.
    pub fn add_warning(&mut self, message: impl Into<String>) {
        self.warnings.push(message.into());
    }

    pub(crate) fn serialization_result(&self) -> crate::Result<()> {
        if let Some(error) = &self.serialization_error {
            return Err(crate::CliCoreError::message(error.clone()));
        }
        Ok(())
    }
}

impl Metadata {
    /// Creates metadata with system and timestamp.
    #[must_use]
    pub fn new(system: impl Into<String>) -> Self {
        Self {
            system: system.into(),
            timestamp: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
            request_id: String::new(),
            dry_run: false,
            command: String::new(),
            duration: String::new(),
            env: String::new(),
            identity: String::new(),
            args: None,
            effective_args: None,
        }
    }

    fn filter_fields(&self, verbose: &str) -> Self {
        let wanted = verbose
            .split(',')
            .map(str::trim)
            .filter(|field| !field.is_empty())
            .collect::<Vec<_>>();
        Self {
            system: keep_string(&wanted, "system", &self.system),
            timestamp: keep_string(&wanted, "timestamp", &self.timestamp),
            request_id: keep_string(&wanted, "request_id", &self.request_id),
            dry_run: wanted.contains(&"dry_run") && self.dry_run,
            command: keep_string(&wanted, "command", &self.command),
            duration: keep_string(&wanted, "duration", &self.duration),
            env: keep_string(&wanted, "env", &self.env),
            identity: keep_string(&wanted, "identity", &self.identity),
            args: wanted
                .contains(&"args")
                .then(|| self.args.clone())
                .flatten(),
            effective_args: wanted
                .contains(&"effective_args")
                .then(|| self.effective_args.clone())
                .flatten(),
        }
    }
}

/// Builds an error envelope, preserving structured details from known error types.
#[must_use]
pub fn build_error_envelope(err: &(dyn std::error::Error + 'static), system: &str) -> Envelope {
    let fix = find_error_fix(err);
    if let Some((code, mut sys, request_id, next_actions)) = find_detailed_error(err) {
        if sys.is_empty() {
            sys = system.to_owned();
        }
        return Envelope {
            data: None,
            pagination: None,
            metadata: Some(Metadata {
                request_id: request_id.clone(),
                ..Metadata::new(sys.clone())
            }),
            error: Some(ErrorEnvelope {
                code: if code.is_empty() {
                    "ERROR".to_owned()
                } else {
                    code
                },
                message: err.to_string(),
                system: sys,
                request_id,
            }),
            warnings: Vec::new(),
            next_actions,
            fix,
            serialization_error: None,
        };
    }
    Envelope::error("ERROR", err.to_string(), system).with_fix(fix.unwrap_or_default())
}

fn find_error_fix(err: &(dyn std::error::Error + 'static)) -> Option<String> {
    let mut current = Some(err);
    while let Some(error) = current {
        if let Some(crate::CliCoreError::Fix { fix, .. }) =
            error.downcast_ref::<crate::CliCoreError>()
            && !fix.is_empty()
        {
            return Some(fix.clone());
        }
        current = error.source();
    }
    None
}

fn find_detailed_error(
    err: &(dyn std::error::Error + 'static),
) -> Option<(String, String, String, Vec<NextAction>)> {
    let mut current = Some(err);
    let mut fallback_system = None::<String>;
    while let Some(error) = current {
        if let Some(crate::CliCoreError::SystemMessage {
            system,
            code,
            request_id,
            ..
        }) = error.downcast_ref::<crate::CliCoreError>()
        {
            return Some((code.clone(), system.clone(), request_id.clone(), Vec::new()));
        }
        if let Some(crate::CliCoreError::System { system, .. }) =
            error.downcast_ref::<crate::CliCoreError>()
            && !system.is_empty()
            && fallback_system.is_none()
        {
            fallback_system = Some(system.clone());
        }
        if let Some(crate::CliCoreError::Detailed {
            code,
            system,
            request_id,
            next_actions,
            ..
        }) = error.downcast_ref::<crate::CliCoreError>()
        {
            return Some((
                code.clone(),
                fallback_system
                    .clone()
                    .filter(|_| system.is_empty())
                    .unwrap_or_else(|| system.clone()),
                request_id.clone(),
                next_actions.clone(),
            ));
        }
        let detailed_transport = error.downcast_ref::<crate::transport::Error>().or_else(|| {
            match error.downcast_ref::<crate::CliCoreError>() {
                Some(crate::CliCoreError::Transport(transport)) => Some(transport),
                Some(
                    crate::CliCoreError::MissingAuthProvider(_)
                    | crate::CliCoreError::AuthProvider { .. }
                    | crate::CliCoreError::InvalidOutputFormat(_)
                    | crate::CliCoreError::Message(_)
                    | crate::CliCoreError::SystemMessage { .. }
                    | crate::CliCoreError::System { .. }
                    | crate::CliCoreError::Detailed { .. }
                    | crate::CliCoreError::ExitCode { .. }
                    | crate::CliCoreError::Fix { .. }
                    | crate::CliCoreError::Io(_)
                    | crate::CliCoreError::Json(_)
                    | crate::CliCoreError::EnvConfig(_),
                )
                | None => None,
            }
        });
        if let Some(detailed) = detailed_transport {
            let system = detailed
                .error_system()
                .map_or_else(String::new, std::borrow::Cow::into_owned);
            return Some((
                detailed.error_code().into_owned(),
                fallback_system
                    .clone()
                    .filter(|_| system.is_empty())
                    .unwrap_or(system),
                detailed
                    .error_request_id()
                    .map_or_else(String::new, std::borrow::Cow::into_owned),
                detailed.error_next_actions(),
            ));
        }
        current = error.source();
    }
    fallback_system.map(|system| ("ERROR".to_owned(), system, String::new(), Vec::new()))
}

/// Builds an error envelope from a [`DetailedError`].
#[must_use]
pub fn build_detailed_error_envelope(err: &dyn DetailedError, system: &str) -> Envelope {
    let code = err.error_code().into_owned();
    let sys = err
        .error_system()
        .map_or_else(|| system.to_owned(), std::borrow::Cow::into_owned);
    let request_id = err
        .error_request_id()
        .map_or_else(String::new, std::borrow::Cow::into_owned);
    Envelope {
        data: None,
        pagination: None,
        metadata: Some(Metadata {
            request_id: request_id.clone(),
            ..Metadata::new(sys.clone())
        }),
        error: Some(ErrorEnvelope {
            code: if code.is_empty() {
                "ERROR".to_owned()
            } else {
                code
            },
            message: err.to_string(),
            system: sys,
            request_id,
        }),
        warnings: Vec::new(),
        next_actions: err.error_next_actions(),
        fix: err
            .error_fix()
            .map(std::borrow::Cow::into_owned)
            .filter(|fix| !fix.is_empty()),
        serialization_error: None,
    }
}

fn keep_string(wanted: &[&str], field: &str, value: &str) -> String {
    if wanted.contains(&field) {
        value.to_owned()
    } else {
        String::new()
    }
}

fn format_duration(duration: Duration) -> String {
    let nanos = duration.as_nanos();
    let millis = (nanos + 500_000) / 1_000_000;
    if millis == 0 {
        return "0s".to_owned();
    }
    if millis >= 1000 {
        let secs = millis / 1000;
        let rem = millis % 1000;
        if rem == 0 {
            format!("{secs}s")
        } else {
            let mut fraction = format!("{rem:03}");
            while fraction.ends_with('0') {
                fraction.pop();
            }
            format!("{secs}.{fraction}s")
        }
    } else {
        format!("{millis}ms")
    }
}

const fn is_false(value: &bool) -> bool {
    !*value
}

fn is_absent_or_null(value: &Option<Value>) -> bool {
    value.as_ref().is_none_or(Value::is_null)
}

fn is_absent_null_or_empty_object(value: &Option<Value>) -> bool {
    match value {
        None | Some(Value::Null) => true,
        Some(Value::Object(map)) => map.is_empty(),
        Some(Value::Array(_) | Value::Bool(_) | Value::Number(_) | Value::String(_)) => false,
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn next_actions_appear_in_serialized_envelope() {
        let envelope =
            Envelope::success(json!({"id": "p1"}), "projects-api").with_next_actions(vec![
                NextAction::new("project get --id <id>", "Get project details"),
            ]);

        let serialized = serde_json::to_string(&envelope).expect("envelope serializes to JSON");
        let parsed: Value =
            serde_json::from_str(&serialized).expect("serialized envelope is valid JSON");

        assert_eq!(
            parsed["next_actions"][0]["command"],
            "project get --id <id>"
        );
        assert_eq!(
            parsed["next_actions"][0]["description"],
            "Get project details"
        );
    }

    #[test]
    fn next_actions_omitted_from_json_when_empty() {
        let envelope = Envelope::success(json!({"id": "p1"}), "projects-api");

        let serialized = serde_json::to_string(&envelope).expect("envelope serializes to JSON");
        let parsed: Value =
            serde_json::from_str(&serialized).expect("serialized envelope is valid JSON");

        assert!(
            parsed.get("next_actions").is_none(),
            "empty next_actions must not appear in JSON output"
        );
    }

    #[test]
    fn next_action_params_serialize_when_present() {
        let action = NextAction::new("deploy run --app <app>", "Deploy the app").with_param(
            "app",
            NextActionParam {
                description: Some("Application name".to_owned()),
                required: true,
                value: None,
                r#enum: Vec::new(),
                default: None,
            },
        );
        let envelope = Envelope::success(json!(null), "deploy-api").with_next_actions(vec![action]);

        let serialized = serde_json::to_string(&envelope).expect("envelope serializes to JSON");
        let parsed: Value =
            serde_json::from_str(&serialized).expect("serialized envelope is valid JSON");

        assert_eq!(
            parsed["next_actions"][0]["params"]["app"]["description"],
            "Application name"
        );
        assert_eq!(parsed["next_actions"][0]["params"]["app"]["required"], true);
    }

    #[test]
    fn fix_appears_in_serialized_error_envelope() {
        let envelope = Envelope::error("AUTH_REQUIRED", "not logged in", "auth")
            .with_fix("Run `auth login` and retry.");

        let serialized = serde_json::to_string(&envelope).expect("envelope serializes to JSON");
        let parsed: Value =
            serde_json::from_str(&serialized).expect("serialized envelope is valid JSON");

        assert_eq!(parsed["error"]["code"], "AUTH_REQUIRED");
        assert_eq!(parsed["fix"], "Run `auth login` and retry.");
    }

    #[test]
    fn fix_omitted_from_json_when_empty() {
        let envelope = Envelope::error("ERROR", "boom", "domain");

        let serialized = serde_json::to_string(&envelope).expect("envelope serializes to JSON");
        let parsed: Value =
            serde_json::from_str(&serialized).expect("serialized envelope is valid JSON");

        assert!(
            parsed.get("fix").is_none(),
            "empty fix must not appear in JSON output"
        );
    }

    #[test]
    fn build_error_envelope_preserves_fix_wrapper() {
        let err = crate::CliCoreError::with_fix(
            "Run `auth login` and retry.",
            crate::CliCoreError::message("not logged in"),
        );
        let envelope = build_error_envelope(&err, "auth");

        assert_eq!(envelope.fix.as_deref(), Some("Run `auth login` and retry."));
        assert_eq!(
            envelope.error.as_ref().map(|e| e.message.as_str()),
            Some("not logged in")
        );
    }

    #[test]
    fn build_error_envelope_surfaces_next_actions_from_a_detailed_error() {
        use crate::error::DetailedError;

        #[derive(Debug, thiserror::Error)]
        #[error("'/businesses' matches 2 operations")]
        struct Ambiguous;

        impl DetailedError for Ambiguous {
            fn error_code(&self) -> std::borrow::Cow<'static, str> {
                std::borrow::Cow::Borrowed("AMBIGUOUS_MATCH")
            }

            fn error_system(&self) -> Option<std::borrow::Cow<'static, str>> {
                None
            }

            fn error_request_id(&self) -> Option<std::borrow::Cow<'static, str>> {
                None
            }

            fn error_next_actions(&self) -> Vec<NextAction> {
                vec![
                    NextAction::new(
                        "api operation get /businesses --method GET",
                        "Get all businesses",
                    ),
                    NextAction::new(
                        "api operation get /businesses --method POST",
                        "Create a new business",
                    ),
                ]
            }
        }

        // Mirrors the real path: a handler converts its `DetailedError` into a
        // `CliCoreError` (type-erasing it), then the middleware renders that
        // through `build_error_envelope` — never `build_detailed_error_envelope`.
        let err = crate::CliCoreError::with_detailed_error(Ambiguous);
        let envelope = build_error_envelope(&err, "api");

        assert_eq!(
            envelope.error.as_ref().map(|e| e.code.as_str()),
            Some("AMBIGUOUS_MATCH")
        );
        assert_eq!(envelope.next_actions.len(), 2);
        assert_eq!(
            envelope.next_actions[0].command,
            "api operation get /businesses --method GET"
        );
        assert_eq!(
            envelope.next_actions[1].command,
            "api operation get /businesses --method POST"
        );
    }

    #[test]
    fn build_detailed_error_envelope_surfaces_next_actions() {
        use crate::error::DetailedError;

        #[derive(Debug, thiserror::Error)]
        #[error("not found")]
        struct NotFound;

        impl DetailedError for NotFound {
            fn error_code(&self) -> std::borrow::Cow<'static, str> {
                std::borrow::Cow::Borrowed("NOT_FOUND")
            }

            fn error_system(&self) -> Option<std::borrow::Cow<'static, str>> {
                None
            }

            fn error_request_id(&self) -> Option<std::borrow::Cow<'static, str>> {
                None
            }

            fn error_next_actions(&self) -> Vec<NextAction> {
                vec![NextAction::new("app list", "List applications")]
            }
        }

        let err = NotFound;
        let envelope = build_detailed_error_envelope(&err, "applications");

        assert_eq!(envelope.next_actions.len(), 1);
        assert_eq!(envelope.next_actions[0].command, "app list");
    }

    #[test]
    fn success_envelope_ignores_with_fix() {
        let envelope = Envelope::success(json!({"ok": true}), "api").with_fix("should not stick");

        assert!(
            envelope.fix.is_none(),
            "fix is error-only and must not attach to success"
        );
        let serialized = serde_json::to_string(&envelope).expect("envelope serializes to JSON");
        let parsed: Value =
            serde_json::from_str(&serialized).expect("serialized envelope is valid JSON");
        assert!(
            parsed.get("fix").is_none(),
            "fix must not appear on success"
        );
    }
}