Skip to main content

taskfast_cli/
envelope.rs

1// SPDX-License-Identifier: MIT
2//! JSON output envelope — uniform across success/error/dry-run.
3//!
4//! Shape (success):
5//! ```json
6//! { "ok": true, "environment": "production", "dry_run": false, "data": {...} }
7//! ```
8//!
9//! Shape (error):
10//! ```json
11//! {
12//!   "ok": false, "environment": "production", "dry_run": false,
13//!   "error": { "code": "rate_limited", "message": "...", "retry_after_seconds": 30 }
14//! }
15//! ```
16//!
17//! Orchestrators branch on `ok` + `error.code`; `retry_after_seconds` is
18//! populated only when the server supplied a sleep hint (HTTP 429) so callers
19//! don't have to regex-scrape the human message to schedule their next try.
20
21use serde::Serialize;
22
23use crate::cmd::CmdError;
24use crate::Environment;
25
26#[derive(Debug, Serialize)]
27pub struct Envelope {
28    pub ok: bool,
29    pub environment: &'static str,
30    pub dry_run: bool,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub data: Option<serde_json::Value>,
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub error: Option<ErrorPayload>,
35    /// F15: machine-readable non-fatal security signals. Always present
36    /// (possibly empty) so orchestrators can unconditionally `.jq`
37    /// `.security_warnings | length > 0` without needing a null check.
38    /// Populated by command code via [`Self::with_warnings`].
39    pub security_warnings: Vec<SecurityWarning>,
40}
41
42/// One non-fatal security observation surfaced on stderr + envelope.
43///
44/// `code` is a stable identifier orchestrators can gate on (e.g.
45/// `"custom_api_base"`, `"custom_tempo_rpc"`, `"password_env_var"`);
46/// `message` is the human-readable detail. Kept flat rather than nested
47/// so a JSON consumer can key on `.code` directly.
48#[derive(Debug, Clone, Serialize)]
49pub struct SecurityWarning {
50    pub code: &'static str,
51    pub message: String,
52}
53
54#[derive(Debug, Serialize)]
55pub struct ErrorPayload {
56    pub code: &'static str,
57    pub message: String,
58    /// Server-directed sleep hint in whole seconds. Present only for
59    /// rate-limited errors that carried a `Retry-After` header.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub retry_after_seconds: Option<u64>,
62}
63
64impl Envelope {
65    pub fn success(env: Environment, dry_run: bool, data: serde_json::Value) -> Self {
66        Self {
67            ok: true,
68            environment: env.as_str(),
69            dry_run,
70            data: Some(data),
71            error: None,
72            security_warnings: Vec::new(),
73        }
74    }
75
76    pub fn error(env: Environment, dry_run: bool, err: &CmdError) -> Self {
77        Self {
78            ok: false,
79            environment: env.as_str(),
80            dry_run,
81            data: None,
82            error: Some(ErrorPayload {
83                code: err.code(),
84                message: err.to_string(),
85                retry_after_seconds: err.retry_after().map(|d| d.as_secs()),
86            }),
87            security_warnings: Vec::new(),
88        }
89    }
90
91    /// Attach non-fatal security warnings to this envelope. Idempotent —
92    /// appends to whatever is already set; callers can accumulate across
93    /// the request pipeline.
94    pub fn with_warnings(mut self, warnings: Vec<SecurityWarning>) -> Self {
95        self.security_warnings.extend(warnings);
96        self
97    }
98
99    pub fn emit(&self) {
100        // Flush is implicit — stdout closes on process exit.
101        let _ = serde_json::to_writer(std::io::stdout().lock(), self);
102        println!();
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109    use std::time::Duration;
110
111    #[test]
112    fn success_envelope_omits_error_field() {
113        let env = Envelope::success(
114            Environment::Prod,
115            false,
116            serde_json::json!({"agent_id": "ag_1"}),
117        );
118        let v = serde_json::to_value(&env).unwrap();
119        assert_eq!(v["ok"], true);
120        assert_eq!(v["environment"], "production");
121        assert_eq!(v["dry_run"], false);
122        assert_eq!(v["data"]["agent_id"], "ag_1");
123        assert!(v.get("error").is_none(), "error must be omitted on success");
124        // F15: security_warnings is always present (possibly empty).
125        assert_eq!(
126            v["security_warnings"].as_array().map(Vec::len),
127            Some(0),
128            "security_warnings must be an empty array on healthy success"
129        );
130    }
131
132    #[test]
133    fn with_warnings_populates_the_array() {
134        let env =
135            Envelope::success(Environment::Prod, false, serde_json::json!({})).with_warnings(vec![
136                SecurityWarning {
137                    code: "custom_api_base",
138                    message: "api_base overridden via --allow-custom-endpoints".into(),
139                },
140            ]);
141        let v = serde_json::to_value(&env).unwrap();
142        let arr = v["security_warnings"].as_array().unwrap();
143        assert_eq!(arr.len(), 1);
144        assert_eq!(arr[0]["code"], "custom_api_base");
145    }
146
147    #[test]
148    fn error_envelope_omits_data_field_and_carries_code() {
149        let err = CmdError::Auth("401".into());
150        let env = Envelope::error(Environment::Staging, false, &err);
151        let v = serde_json::to_value(&env).unwrap();
152        assert_eq!(v["ok"], false);
153        assert_eq!(v["environment"], "staging");
154        assert_eq!(v["error"]["code"], "auth");
155        assert!(v["error"]["message"].as_str().unwrap().contains("401"));
156        assert!(v.get("data").is_none(), "data must be omitted on error");
157        assert!(
158            v["error"].get("retry_after_seconds").is_none(),
159            "retry_after_seconds must be omitted when absent"
160        );
161    }
162
163    #[test]
164    fn rate_limited_error_surfaces_retry_after_seconds() {
165        let err = CmdError::RateLimited {
166            retry_after: Duration::from_secs(30),
167        };
168        let env = Envelope::error(Environment::Prod, false, &err);
169        let v = serde_json::to_value(&env).unwrap();
170        assert_eq!(v["error"]["code"], "rate_limited");
171        assert_eq!(v["error"]["retry_after_seconds"], 30);
172    }
173
174    #[test]
175    fn dry_run_flag_is_serialized_verbatim() {
176        let env = Envelope::success(Environment::Local, true, serde_json::json!({}));
177        let v = serde_json::to_value(&env).unwrap();
178        assert_eq!(v["dry_run"], true);
179        assert_eq!(v["environment"], "local");
180    }
181}