Skip to main content

kaish_types/
result.rs

1//! ExecResult — the structured result of every command execution.
2//!
3//! After every command in kaish, the special variable `$?` contains an ExecResult.
4
5use std::borrow::Cow;
6use std::collections::BTreeMap;
7
8use crate::output::OutputData;
9use crate::value::Value;
10
11/// A command's stdout payload: text, or raw bytes.
12///
13/// `Text` xor `Bytes` — the enum makes the invalid both-set state
14/// unrepresentable (an earlier draft used two sibling fields; see
15/// `docs/binary-data.md`). Serializes wire-compatibly: `Text` is a bare JSON
16/// string (unchanged from when `out` was a `String`), `Bytes` is the base64
17/// envelope from [`crate::bytes`].
18#[derive(Debug, Clone, PartialEq)]
19pub enum OutputPayload {
20    /// UTF-8 text — the common case, canonical for pipes.
21    Text(String),
22    /// Raw bytes — binary output (set by binary-aware builtins). Until the
23    /// Phase-2 pipe/consumption rework, no builtin produces this in practice.
24    Bytes(Vec<u8>),
25}
26
27impl Default for OutputPayload {
28    fn default() -> Self {
29        OutputPayload::Text(String::new())
30    }
31}
32
33impl serde::Serialize for OutputPayload {
34    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
35        match self {
36            // Bare string keeps the historical `"out":"…"` wire shape.
37            OutputPayload::Text(t) => serializer.serialize_str(t),
38            OutputPayload::Bytes(b) => crate::bytes::bytes_to_envelope(b).serialize(serializer),
39        }
40    }
41}
42
43impl<'de> serde::Deserialize<'de> for OutputPayload {
44    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
45        let v = serde_json::Value::deserialize(deserializer)?;
46        match v {
47            serde_json::Value::String(s) => Ok(OutputPayload::Text(s)),
48            other => match crate::bytes::envelope_to_bytes(&other) {
49                Some(b) => Ok(OutputPayload::Bytes(b)),
50                None => Err(serde::de::Error::custom(
51                    "ExecResult.out: expected a string or a base64 bytes envelope",
52                )),
53            },
54        }
55    }
56}
57
58/// A pending confirmation-latch request, decoded from a latched [`ExecResult`].
59///
60/// When the confirmation latch (`set -o latch`) gates a destructive operation,
61/// the kernel returns exit code 2 with this typed payload on the dedicated
62/// [`ExecResult::latch`] field. Embedders read it via
63/// [`ExecResult::latch_request`] — the seam to apply preapproval policy or a
64/// model review before approving the operation. It is deliberately *not* the
65/// data-plane [`ExecResult::data`]: a stdout redirect clears `.data` but never
66/// this control-plane signal, and it survives `--json` formatting (surfaced
67/// under a `latch` key in the error envelope).
68///
69/// To approve, re-run the *same argv* with `--confirm=<nonce>` (the `hint`
70/// shows the exact form). The nonce is command- and path-scoped, so it cannot
71/// authorize a different command or a path outside `paths`.
72#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct LatchRequest {
75    /// Confirmation nonce — pass back as `--confirm=<nonce>` on the same command.
76    pub nonce: String,
77    /// The canonical command being gated (e.g. `"rm"`, `"kaish-trash empty"`).
78    /// A human/display label — for a precise machine replay use `tool` + `argv`.
79    pub command: String,
80    /// The resolved paths the operation would touch. Empty for command-only ops.
81    pub paths: Vec<String>,
82    /// A ready-to-run confirmation command string (informational, for humans).
83    /// Machine fulfillment should prefer `Kernel::confirm` (which replays the
84    /// captured `tool`/`argv`); the hint is a display string and does not
85    /// robustly quote paths with spaces or glob characters.
86    pub hint: String,
87    /// The dispatch name of the gated tool (e.g. `"rm"`, `"kaish-trash"`), as
88    /// resolved at the dispatch seam — the argv0 for a replay via
89    /// `Kernel::execute_argv`. Empty only when the latch was produced outside a
90    /// dispatch (a direct `tool.execute` in a unit test).
91    #[serde(default)]
92    pub tool: String,
93    /// The exact captured argv (`ToolArgs::to_argv`) of the gated invocation,
94    /// minus the tool name and the `--confirm` nonce. `Kernel::confirm` prepends
95    /// `--confirm=<nonce>` and replays `execute_argv(tool, argv)` — the
96    /// highest-fidelity fulfillment, with no re-parsing of the `hint`.
97    #[serde(default)]
98    pub argv: Vec<String>,
99    /// Seconds until the nonce expires.
100    pub ttl: u64,
101    /// The id of the *backgrounded* job that raised this latch, if any —
102    /// `Some` only when the gate came from a job the `JobManager` is tracking
103    /// (`rm x &` reaching its gate), `None` for a foreground latch (the common
104    /// case: `rm x` gated directly at the dispatch seam, no job involved).
105    ///
106    /// Deliberately a bare `u64`, not a `JobId`: this crate (`kaish-types`) is
107    /// a dependency-light leaf with no notion of `JobId` — that type lives in
108    /// `kaish-kernel`'s scheduler module, which depends on `kaish-types`, not
109    /// the other way around. `kaish-kernel` re-wraps this as `JobId(id)` at
110    /// the two call sites that care ([`JobManager`]'s `Job::latch()` stamps
111    /// it; `Kernel::confirm` reads it back to retire the originating job
112    /// after a successful replay). Skipped on the wire when absent, so a
113    /// foreground latch's `--json` shape is unchanged.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub job_id: Option<u64>,
116}
117
118/// Returned when a binary result is asked to behave as text.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct BinaryNotText {
121    /// Number of binary bytes that could not be coerced.
122    pub len: usize,
123}
124
125impl std::fmt::Display for BinaryNotText {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        write!(
128            f,
129            "output is binary ({} bytes), not text — pipe through base64/xxd or redirect to a file",
130            self.len
131        )
132    }
133}
134
135impl std::error::Error for BinaryNotText {}
136
137/// The result of executing a command or pipeline.
138///
139/// `$?` in script syntax is the POSIX exit code (an integer). To read the
140/// previous command's structured `.data` (or its captured stdout) from
141/// inside a script, use the `kaish-last` builtin and pipe / capture its
142/// output. Inside Rust callers, read `.data`, `.text_out()`, etc. directly.
143///
144/// Notes on the fields:
145/// - `code` — exit code (0 = success)
146/// - `err` — error message if failed
147/// - `out` — raw stdout as string
148/// - `data` — structured data; only set by builtins/tools that opt in
149///   (e.g. `seq`, `jq`, `cut`, `find`, `glob`, `split`). External commands
150///   never populate this — pipe their stdout through `jq` to get it.
151#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
152#[non_exhaustive]
153pub struct ExecResult {
154    /// Exit code. 0 means success.
155    pub code: i64,
156    /// Standard output payload — text (canonical for pipes) or raw bytes.
157    out: OutputPayload,
158    /// Raw standard error as a string.
159    pub err: String,
160    /// Structured data — only populated when a builtin/tool sets it explicitly.
161    /// Stdout is *never* sniffed; this stays `None` for external commands.
162    pub data: Option<Value>,
163    /// Structured output data for rendering.
164    ///
165    /// Boxed like [`Self::latch`]: `OutputData` is ~120 B and `ExecResult` (and
166    /// the `ControlFlow` that wraps it) is returned up every level of deep
167    /// `$()`/pipeline recursion, so an inline `Option<OutputData>` fattened every
168    /// frame. The box is allocated only when a builtin sets structured output,
169    /// and it serializes identically (Box is transparent to serde). Private —
170    /// the public accessors below hand back plain `OutputData`/`&OutputData`, so
171    /// the boxing never leaks (GH #48, item 5).
172    output: Option<Box<OutputData>>,
173    /// True if the output limiter capped this result. Either the overflow was
174    /// written to a disk spill file (the `out` message carries the path) or it
175    /// was truncated in memory (Memory spill mode — head+tail only, no
176    /// recoverable file). Both cases remap the exit code to 3.
177    pub did_spill: bool,
178    /// The command's original exit code before spill logic overwrote it with 2 or 3.
179    /// Present only when `did_spill` is true and `code` was changed.
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub original_code: Option<i64>,
182    /// MIME content type hint (e.g., "text/markdown", "image/svg+xml").
183    /// When set, downstream consumers can use this instead of sniffing content.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub content_type: Option<String>,
186    /// Opaque key-value context propagated from tools through execution.
187    /// Intermediaries (kaish) carry but don't interpret. Consumers read known keys.
188    /// Follows W3C Baggage semantics — useful for OTel trace propagation,
189    /// application-level hints, etc.
190    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
191    pub baggage: BTreeMap<String, String>,
192    /// A pending confirmation-latch request — the *control-plane* signal a
193    /// gated destructive op (`rm`/`kaish-trash`/an overwrite under `set -o
194    /// latch`) raises alongside exit code 2. First-class and typed, distinct
195    /// from the data-plane `.data`: a stdout redirect clears `.data` but never
196    /// this. Read it via [`Self::latch_request`]; set it via
197    /// `ToolCtx::latch_result`.
198    ///
199    /// Boxed: `ExecResult` is returned up every level of deep `$()`/pipeline
200    /// recursion, and `LatchRequest` is ~150 bytes — inline it would fatten
201    /// every stack frame and cost interpreter stack headroom (GH #46/#47). The
202    /// box is allocated only when a latch actually fires. Serializes identically
203    /// to an unboxed `Option` (Box is transparent to serde).
204    #[serde(default, skip_serializing_if = "Option::is_none")]
205    pub latch: Option<Box<LatchRequest>>,
206}
207
208impl ExecResult {
209    /// Create a successful result with output.
210    pub fn success(out: impl Into<String>) -> Self {
211        Self {
212            code: 0,
213            out: OutputPayload::Text(out.into()),
214            err: String::new(),
215            data: None,
216            output: None,
217            did_spill: false,
218            original_code: None,
219            content_type: None,
220            baggage: BTreeMap::new(),
221            latch: None,
222        }
223    }
224
225    /// Create a successful result with structured output data.
226    ///
227    /// The `OutputData` is the source of truth. Text is materialized lazily
228    /// via `text_out()` when needed (pipes, redirects, command substitution).
229    pub fn with_output(output: OutputData) -> Self {
230        // Simple text: move string into .out directly for efficient Cow::Borrowed.
231        // Structured output: store in .output, materialize lazily.
232        match output.into_text() {
233            Ok(text) => Self::success(text),
234            Err(output) => Self {
235                code: 0,
236                out: OutputPayload::Text(String::new()),
237                err: String::new(),
238                data: None,
239                output: Some(Box::new(output)),
240                did_spill: false,
241                original_code: None,
242                content_type: None,
243                baggage: BTreeMap::new(),
244                latch: None,
245            },
246        }
247    }
248
249    /// Create a successful result whose stdout is raw bytes (binary payload).
250    pub fn success_bytes(bytes: Vec<u8>) -> Self {
251        let mut r = Self::success("");
252        r.out = OutputPayload::Bytes(bytes);
253        r
254    }
255
256    /// Create a successful result from bytes, applying the coercion rule at the
257    /// producer: valid UTF-8 becomes a text result, anything else a binary
258    /// `Bytes` result. This is the single place pass-through/decoder builtins
259    /// (`cat`, `head -c`, `base64 -d`, `xxd -r`, `tee`, …) decide text-vs-binary,
260    /// so text workflows stay text and only real binary flows as bytes.
261    pub fn success_text_or_bytes(bytes: Vec<u8>) -> Self {
262        match String::from_utf8(bytes) {
263            Ok(text) => Self::success(text),
264            Err(e) => Self::success_bytes(e.into_bytes()),
265        }
266    }
267
268    /// Create a successful result with structured data.
269    pub fn success_data(data: Value) -> Self {
270        let out = value_to_json(&data).to_string();
271        Self {
272            code: 0,
273            out: OutputPayload::Text(out),
274            err: String::new(),
275            data: Some(data),
276            output: None,
277            did_spill: false,
278            original_code: None,
279            content_type: None,
280            baggage: BTreeMap::new(),
281            latch: None,
282        }
283    }
284
285    /// Create a successful result with both text output and structured data.
286    ///
287    /// Use this when a command should have:
288    /// - Text output for pipes and traditional shell usage
289    /// - Structured data for iteration and programmatic access
290    ///
291    /// The data field takes precedence for command substitution in contexts
292    /// like `for i in $(cmd)` where the structured data can be iterated.
293    pub fn success_with_data(out: impl Into<String>, data: Value) -> Self {
294        Self {
295            code: 0,
296            out: OutputPayload::Text(out.into()),
297            err: String::new(),
298            data: Some(data),
299            output: None,
300            did_spill: false,
301            original_code: None,
302            content_type: None,
303            baggage: BTreeMap::new(),
304            latch: None,
305        }
306    }
307
308    /// Create a failed result with an error message.
309    pub fn failure(code: i64, err: impl Into<String>) -> Self {
310        Self {
311            code,
312            out: OutputPayload::Text(String::new()),
313            err: err.into(),
314            data: None,
315            output: None,
316            did_spill: false,
317            original_code: None,
318            content_type: None,
319            baggage: BTreeMap::new(),
320            latch: None,
321        }
322    }
323
324    /// Create a result from raw output streams.
325    ///
326    /// `data` is left empty — kaish does not sniff stdout for JSON. To get
327    /// structured iteration from an external command, pipe through `jq`:
328    /// `for i in $(curl ... | jq .); do ...`.
329    pub fn from_output(code: i64, stdout: impl Into<String>, stderr: impl Into<String>) -> Self {
330        Self {
331            code,
332            out: OutputPayload::Text(stdout.into()),
333            err: stderr.into(),
334            data: None,
335            output: None,
336            did_spill: false,
337            original_code: None,
338            content_type: None,
339            baggage: BTreeMap::new(),
340            latch: None,
341        }
342    }
343
344    /// Create a successful result with structured output and explicit pipe text.
345    ///
346    /// Use this when a builtin needs custom text formatting that differs from
347    /// the canonical `OutputData::to_canonical_string()` representation.
348    pub fn with_output_and_text(output: OutputData, text: impl Into<String>) -> Self {
349        Self {
350            code: 0,
351            out: OutputPayload::Text(text.into()),
352            err: String::new(),
353            data: None,
354            output: Some(Box::new(output)),
355            did_spill: false,
356            original_code: None,
357            content_type: None,
358            baggage: BTreeMap::new(),
359            latch: None,
360        }
361    }
362
363    /// Create a result from parts — for kernel struct literal sites.
364    pub fn from_parts(
365        code: i64,
366        out: String,
367        err: String,
368        data: Option<Value>,
369    ) -> Self {
370        Self {
371            code,
372            out: OutputPayload::Text(out),
373            err,
374            data,
375            output: None,
376            did_spill: false,
377            original_code: None,
378            content_type: None,
379            baggage: BTreeMap::new(),
380            latch: None,
381        }
382    }
383
384    /// Builder: set the exit code, returning self for chaining.
385    pub fn with_code(mut self, code: i64) -> Self {
386        self.code = code;
387        self
388    }
389
390    // ── Read accessors ──
391
392    /// Get text output, materializing from OutputData on demand.
393    ///
394    /// Returns the text payload if non-empty, otherwise falls back to
395    /// `OutputData::to_canonical_string()`. This is the canonical way to
396    /// get text for pipes, command substitution, and file redirects.
397    ///
398    /// **Binary payloads** decode lossily here (`U+FFFD` for invalid UTF-8).
399    /// Several builtins already produce a `Bytes` payload (`cat`/`head`/`tail`/
400    /// `base64 -d`/`xxd -r`/`dd`/`tee`/external commands), so this lossy path
401    /// IS reachable — callers that need to catch binary rather than silently
402    /// mangle it should use [`Self::try_text_out`] instead, which loud-errors
403    /// with [`BinaryNotText`] on invalid UTF-8. See `docs/binary-data.md`.
404    pub fn text_out(&self) -> Cow<'_, str> {
405        match &self.out {
406            OutputPayload::Text(s) if !s.is_empty() => Cow::Borrowed(s),
407            OutputPayload::Bytes(b) => match std::str::from_utf8(b) {
408                Ok(s) => Cow::Borrowed(s),
409                Err(_) => Cow::Owned(String::from_utf8_lossy(b).into_owned()),
410            },
411            // Empty text → fall back to structured output's canonical string.
412            _ => match self.output {
413                Some(ref output) => Cow::Owned(output.to_canonical_string()),
414                None => Cow::Borrowed(""),
415            },
416        }
417    }
418
419    /// Get text output, or a [`BinaryNotText`] error if the payload is binary
420    /// and not valid UTF-8. This is the boundary guard for text sinks (`echo`,
421    /// interpolation, `$()` capture) — adopted as those paths grow byte
422    /// awareness (Phase 2). Valid-UTF-8 bytes coerce; everything else is loud.
423    pub fn try_text_out(&self) -> Result<Cow<'_, str>, BinaryNotText> {
424        match &self.out {
425            OutputPayload::Bytes(b) => std::str::from_utf8(b)
426                .map(Cow::Borrowed)
427                .map_err(|_| BinaryNotText { len: b.len() }),
428            _ => Ok(self.text_out()),
429        }
430    }
431
432    /// Raw bytes if this result carries a binary payload, else `None`.
433    pub fn out_bytes(&self) -> Option<&[u8]> {
434        match &self.out {
435            OutputPayload::Bytes(b) => Some(b),
436            OutputPayload::Text(_) => None,
437        }
438    }
439
440    /// True if the stdout payload is raw bytes rather than text.
441    pub fn is_bytes(&self) -> bool {
442        matches!(self.out, OutputPayload::Bytes(_))
443    }
444
445    /// Get a reference to structured output data.
446    pub fn output(&self) -> Option<&OutputData> {
447        self.output.as_deref()
448    }
449
450    /// True if structured output data is present.
451    pub fn has_output(&self) -> bool {
452        self.output.is_some()
453    }
454
455    // ── Mutation accessors ──
456
457    /// Replace `.out` with text.
458    pub fn set_out(&mut self, s: String) {
459        self.out = OutputPayload::Text(s);
460    }
461
462    /// Replace `.out` with raw bytes (binary payload).
463    pub fn set_out_bytes(&mut self, b: Vec<u8>) {
464        self.out = OutputPayload::Bytes(b);
465    }
466
467    /// Append text to `.out`. A binary payload is appended to as raw UTF-8 bytes.
468    pub fn push_out(&mut self, s: &str) {
469        match &mut self.out {
470            OutputPayload::Text(t) => t.push_str(s),
471            OutputPayload::Bytes(b) => b.extend_from_slice(s.as_bytes()),
472        }
473    }
474
475    /// Clear `.out` back to empty text.
476    pub fn clear_out(&mut self) {
477        self.out = OutputPayload::Text(String::new());
478    }
479
480    /// Drop every representation of stdout: the text `.out`, the structured
481    /// `.output`, and the data-plane `.data` sideband. Used when a stdout
482    /// redirect (`> file`, `>> file`, `&> file`, `1>&2`) has consumed the
483    /// command's output — the bytes went to the file (or stderr), so nothing
484    /// flows onward to a pipe, a `$(...)` capture, or the `.data` sideband.
485    /// Clearing all three together keeps them from drifting: a redirect that
486    /// cleared `.out`/`.output` but left `.data` would leak structured data past
487    /// its own redirect (`x=$(fromjson … > file)` capturing the value instead
488    /// of `""`).
489    ///
490    /// The confirmation-latch request is untouched by design: it is a
491    /// *control-plane* signal on the dedicated `.latch` field, not stdout, so a
492    /// redirect can't drop it — `rm precious > log` still gates.
493    pub fn clear_stdout(&mut self) {
494        self.out = OutputPayload::Text(String::new());
495        self.output = None;
496        self.data = None;
497    }
498
499    /// Replace `.output`.
500    pub fn set_output(&mut self, o: Option<OutputData>) {
501        self.output = o.map(Box::new);
502    }
503
504    /// Take `.output`, leaving None.
505    pub fn take_output(&mut self) -> Option<OutputData> {
506        self.output.take().map(|o| *o)
507    }
508
509    /// Materialize: if `.out` is empty and `.output` is present,
510    /// populate `.out` from canonical string and clear `.output`.
511    pub fn materialize(&mut self) {
512        if matches!(&self.out, OutputPayload::Text(s) if s.is_empty()) {
513            if let Some(ref output) = self.output {
514                self.out = OutputPayload::Text(output.to_canonical_string());
515            }
516        }
517        self.output = None;
518    }
519
520    /// Take `.output` only if `.out` is empty (no custom text),
521    /// so caller can stream directly without materializing.
522    pub fn take_output_for_stream(&mut self) -> Option<OutputData> {
523        if matches!(&self.out, OutputPayload::Text(s) if s.is_empty()) {
524            self.output.take().map(|o| *o)
525        } else {
526            None
527        }
528    }
529
530    /// True if the command succeeded (exit code 0).
531    pub fn ok(&self) -> bool {
532        self.code == 0
533    }
534
535    /// The pending confirmation-latch request, if this result is a latch gate.
536    ///
537    /// A gated destructive op (`rm`/`kaish-trash`/an overwrite under `set -o
538    /// latch`) returns exit code 2 with the typed request on the `.latch` field.
539    /// This is the seam an embedder hooks to apply preapproval policy or a model
540    /// review before re-running the command with `--confirm=<nonce>`, instead of
541    /// string-matching the error. A plain usage error (also exit 2, but no
542    /// latch) returns `None`. Unlike the data-plane `.data`, `.latch` survives
543    /// `--json` formatting, so this is safe to call before or after it.
544    pub fn latch_request(&self) -> Option<LatchRequest> {
545        self.latch.as_deref().cloned()
546    }
547
548    /// Set content type hint, returning self for chaining.
549    pub fn with_content_type(mut self, ct: impl Into<String>) -> Self {
550        self.content_type = Some(ct.into());
551        self
552    }
553
554}
555
556/// Convert serde_json::Value to our AST Value.
557///
558/// Primitives are mapped to their corresponding Value variants.
559/// Arrays and objects are preserved as `Value::Json` - use `jq` to query them.
560pub fn json_to_value(json: serde_json::Value) -> Value {
561    match json {
562        serde_json::Value::Null => Value::Null,
563        serde_json::Value::Bool(b) => Value::Bool(b),
564        serde_json::Value::Number(n) => {
565            if let Some(i) = n.as_i64() {
566                Value::Int(i)
567            } else if let Some(f) = n.as_f64() {
568                Value::Float(f)
569            } else {
570                Value::String(n.to_string())
571            }
572        }
573        serde_json::Value::String(s) => Value::String(s),
574        // A base64 byte envelope round-trips back to inline Bytes; any other
575        // object/array stays structured Json.
576        serde_json::Value::Object(_) => match crate::bytes::envelope_to_bytes(&json) {
577            Some(bytes) => Value::Bytes(bytes),
578            None => Value::Json(json),
579        },
580        serde_json::Value::Array(_) => Value::Json(json),
581    }
582}
583
584/// Convert serde_json::Value to our AST Value **without** bytes-envelope sniffing.
585///
586/// External JSON (from `fromjson`, or native access traversal) must never
587/// silently become a `Value::Bytes` just because an object happens to match the
588/// base64 envelope shape (`{"_type":"bytes",…}`). That auto-decode is a feature
589/// of *internal* round-tripping only — it would be a silent, surprising
590/// conversion on untrusted input. Otherwise this is the same unwrap law as
591/// [`json_to_value`]: JSON scalars unwrap to native `Value` variants, and only
592/// objects/arrays stay `Value::Json`.
593pub fn json_to_value_no_envelope(json: serde_json::Value) -> Value {
594    match json {
595        serde_json::Value::Null => Value::Null,
596        serde_json::Value::Bool(b) => Value::Bool(b),
597        serde_json::Value::Number(n) => {
598            if let Some(i) = n.as_i64() {
599                Value::Int(i)
600            } else if let Some(f) = n.as_f64() {
601                Value::Float(f)
602            } else {
603                Value::String(n.to_string())
604            }
605        }
606        serde_json::Value::String(s) => Value::String(s),
607        // Objects and arrays stay structured — an envelope-shaped object is a
608        // plain record here, not decoded to bytes.
609        serde_json::Value::Object(_) | serde_json::Value::Array(_) => Value::Json(json),
610    }
611}
612
613/// Convert our AST Value to serde_json::Value for serialization.
614pub fn value_to_json(value: &Value) -> serde_json::Value {
615    match value {
616        Value::Null => serde_json::Value::Null,
617        Value::Bool(b) => serde_json::Value::Bool(*b),
618        Value::Int(i) => serde_json::Value::Number((*i).into()),
619        Value::Float(f) => {
620            // JSON has no NaN/Infinity. Rather than silently collapse them to
621            // null (data loss), serialize the non-finite value to its string
622            // form ("NaN", "inf", "-inf") so the information survives the trip.
623            serde_json::Number::from_f64(*f)
624                .map(serde_json::Value::Number)
625                .unwrap_or_else(|| serde_json::Value::String(f.to_string()))
626        }
627        Value::String(s) => serde_json::Value::String(s.clone()),
628        Value::Json(json) => json.clone(),
629        Value::Bytes(data) => crate::bytes::bytes_to_envelope(data),
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    #[test]
638    fn success_creates_ok_result() {
639        let result = ExecResult::success("hello world");
640        assert!(result.ok());
641        assert_eq!(result.code, 0);
642        assert_eq!(&*result.text_out(),"hello world");
643        assert!(result.err.is_empty());
644    }
645
646    #[test]
647    fn value_to_json_finite_float_is_number() {
648        assert_eq!(value_to_json(&Value::Float(3.5)), serde_json::json!(3.5));
649    }
650
651    #[test]
652    fn value_to_json_non_finite_float_serializes_to_string() {
653        // JSON has no NaN/Infinity — preserve the info as a string, never null.
654        assert_eq!(value_to_json(&Value::Float(f64::NAN)), serde_json::json!("NaN"));
655        assert_eq!(value_to_json(&Value::Float(f64::INFINITY)), serde_json::json!("inf"));
656        assert_eq!(
657            value_to_json(&Value::Float(f64::NEG_INFINITY)),
658            serde_json::json!("-inf")
659        );
660        // Crucially: not null (the old data-losing behavior).
661        assert_ne!(value_to_json(&Value::Float(f64::NAN)), serde_json::Value::Null);
662    }
663
664    #[test]
665    fn failure_creates_non_ok_result() {
666        let result = ExecResult::failure(1, "command not found");
667        assert!(!result.ok());
668        assert_eq!(result.code, 1);
669        assert_eq!(result.err, "command not found");
670    }
671
672    #[test]
673    fn success_does_not_sniff_json_stdout() {
674        // External-command stdout is never sniffed for JSON. Tools that want
675        // structured data must call success_with_data() / success_data().
676        let result = ExecResult::success(r#"{"count": 42, "items": ["a", "b"]}"#);
677        assert!(result.data.is_none());
678        assert_eq!(&*result.text_out(),r#"{"count": 42, "items": ["a", "b"]}"#);
679    }
680
681    #[test]
682    fn from_output_does_not_sniff_json_stdout() {
683        let result = ExecResult::from_output(0, r#"[1, 2, 3]"#, "");
684        assert!(result.data.is_none());
685        assert_eq!(&*result.text_out(),"[1, 2, 3]");
686    }
687
688    #[test]
689    fn non_json_stdout_has_no_data() {
690        let result = ExecResult::success("just plain text");
691        assert!(result.data.is_none());
692    }
693
694    #[test]
695    fn success_data_creates_result_with_value() {
696        let value = Value::String("test data".into());
697        let result = ExecResult::success_data(value.clone());
698        assert!(result.ok());
699        assert_eq!(result.data, Some(value));
700    }
701
702    #[test]
703    fn did_spill_defaults_to_false() {
704        assert!(!ExecResult::success("hi").did_spill);
705        assert!(!ExecResult::failure(1, "err").did_spill);
706        assert!(!ExecResult::from_output(0, "out", "err").did_spill);
707    }
708
709    #[test]
710    fn did_spill_is_serialized() {
711        let mut result = ExecResult::success("hi");
712        result.did_spill = true;
713        let json = serde_json::to_string(&result).unwrap();
714        assert!(json.contains("\"did_spill\":true"));
715    }
716
717    #[test]
718    fn original_code_omitted_when_none() {
719        let result = ExecResult::success("hi");
720        let json = serde_json::to_string(&result).unwrap();
721        assert!(!json.contains("original_code"));
722    }
723
724    #[test]
725    fn original_code_present_when_set() {
726        let mut result = ExecResult::success("hi");
727        result.original_code = Some(0);
728        let json = serde_json::to_string(&result).unwrap();
729        assert!(json.contains("\"original_code\":0"));
730    }
731
732    #[test]
733    fn default_is_empty_success() {
734        let result = ExecResult::default();
735        assert!(result.ok());
736        assert!(result.text_out().is_empty());
737        assert!(result.data.is_none());
738        assert!(result.content_type.is_none());
739        assert!(result.baggage.is_empty());
740    }
741
742    #[test]
743    fn from_parts_creates_result() {
744        let result = ExecResult::from_parts(42, "out".into(), "err".into(), None);
745        assert_eq!(result.code, 42);
746        assert_eq!(&*result.text_out(),"out");
747        assert_eq!(result.err, "err");
748        assert!(result.data.is_none());
749        assert!(result.output.is_none());
750    }
751
752    #[test]
753    fn with_code_sets_code() {
754        let result = ExecResult::success("hi").with_code(42);
755        assert_eq!(result.code, 42);
756        assert_eq!(&*result.text_out(),"hi");
757    }
758
759    #[test]
760    fn output_getter() {
761        use crate::output::{OutputData, OutputNode};
762        // Use structured (non-text) output so with_output preserves .output
763        let nodes = OutputData::nodes(vec![OutputNode::new("a"), OutputNode::new("b")]);
764        let result = ExecResult::with_output(nodes);
765        assert!(result.output().is_some());
766        assert!(result.has_output());
767
768        // Simple text now routes to .out, so output is None
769        let text_result = ExecResult::with_output(OutputData::text("test"));
770        assert!(!text_result.has_output());
771        assert_eq!(&*text_result.text_out(), "test");
772
773        let plain = ExecResult::success("text");
774        assert!(plain.output().is_none());
775        assert!(!plain.has_output());
776    }
777
778    #[test]
779    fn set_out_and_push_out_and_clear_out() {
780        let mut result = ExecResult::success("");
781        result.set_out("hello".into());
782        assert_eq!(&*result.text_out(),"hello");
783        result.push_out(" world");
784        assert_eq!(&*result.text_out(),"hello world");
785        result.clear_out();
786        assert!(result.text_out().is_empty());
787    }
788
789    #[test]
790    fn set_output_and_take_output() {
791        use crate::output::OutputData;
792        let mut result = ExecResult::success("");
793        assert!(result.take_output().is_none());
794
795        result.set_output(Some(OutputData::text("data")));
796        assert!(result.has_output());
797
798        let taken = result.take_output();
799        assert!(taken.is_some());
800        assert!(!result.has_output());
801    }
802
803    #[test]
804    fn materialize_populates_out_from_output() {
805        use crate::output::{OutputData, OutputNode};
806        // Use structured output to test materialization
807        let nodes = OutputData::nodes(vec![OutputNode::new("a"), OutputNode::new("b")]);
808        let mut result = ExecResult::with_output(nodes);
809        // Raw text payload is empty before materialize (text_out() would
810        // already fall back to the OutputData canonical string).
811        assert!(matches!(&result.out, OutputPayload::Text(s) if s.is_empty()));
812        assert!(result.has_output());
813        result.materialize();
814        assert_eq!(&*result.text_out(),"a\nb");
815        assert!(result.output.is_none());
816    }
817
818    #[test]
819    fn value_bytes_round_trips_through_envelope() {
820        let v = Value::Bytes(vec![0u8, 1, 2, 255, 128]);
821        let json = value_to_json(&v);
822        assert_eq!(json["_type"], "bytes");
823        assert_eq!(json["len"], 5);
824        // json_to_value recognizes the envelope and reconstructs Bytes.
825        assert_eq!(json_to_value(json), v);
826        // A plain object is NOT mistaken for bytes.
827        let obj = serde_json::json!({"name": "amy"});
828        assert!(matches!(json_to_value(obj), Value::Json(_)));
829    }
830
831    #[test]
832    fn no_envelope_never_decodes_bytes() {
833        // The envelope-free path is what external JSON (fromjson, access) uses:
834        // an object matching the byte-envelope shape stays a plain record, it is
835        // NOT silently decoded to Value::Bytes.
836        let envelope = crate::bytes::bytes_to_envelope(&[1u8, 2, 3]);
837        // The sniffing path DOES decode it (internal round-trip).
838        assert!(matches!(json_to_value(envelope.clone()), Value::Bytes(_)));
839        // The envelope-free path leaves it structured.
840        assert!(matches!(
841            json_to_value_no_envelope(envelope),
842            Value::Json(serde_json::Value::Object(_))
843        ));
844    }
845
846    #[test]
847    fn no_envelope_shares_unwrap_law_for_scalars() {
848        // Scalars unwrap identically to json_to_value; only the object arm differs.
849        assert_eq!(json_to_value_no_envelope(serde_json::json!(42)), Value::Int(42));
850        assert_eq!(json_to_value_no_envelope(serde_json::json!(1.5)), Value::Float(1.5));
851        assert_eq!(json_to_value_no_envelope(serde_json::json!(true)), Value::Bool(true));
852        assert_eq!(json_to_value_no_envelope(serde_json::json!("hi")), Value::String("hi".into()));
853        assert_eq!(json_to_value_no_envelope(serde_json::json!(null)), Value::Null);
854        assert!(matches!(
855            json_to_value_no_envelope(serde_json::json!([1, 2])),
856            Value::Json(serde_json::Value::Array(_))
857        ));
858    }
859
860    #[test]
861    fn output_payload_text_serializes_as_bare_string() {
862        // Wire compatibility: a text result's `out` stays a plain JSON string,
863        // exactly as when `out` was a `String`.
864        let r = ExecResult::success("hello");
865        let json: serde_json::Value = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
866        assert_eq!(json["out"], "hello");
867        // Round-trips back to a Text payload.
868        let back: ExecResult = serde_json::from_value(json).unwrap();
869        assert_eq!(&*back.text_out(), "hello");
870        assert!(!back.is_bytes());
871    }
872
873    #[test]
874    fn success_bytes_carries_binary_and_round_trips() {
875        let r = ExecResult::success_bytes(vec![0u8, 159, 146, 150]); // invalid UTF-8
876        assert!(r.is_bytes());
877        assert_eq!(r.out_bytes(), Some(&[0u8, 159, 146, 150][..]));
878        // try_text_out is the loud guard: invalid UTF-8 → error, not mangling.
879        assert!(r.try_text_out().is_err());
880        // text_out (infallible) decodes lossily — Phase-1 fallback.
881        assert!(r.text_out().contains('\u{fffd}'));
882        // Serializes as a base64 envelope and round-trips back to bytes.
883        let json: serde_json::Value = serde_json::to_value(&r).unwrap();
884        assert_eq!(json["out"]["_type"], "bytes");
885        let back: ExecResult = serde_json::from_value(json).unwrap();
886        assert_eq!(back.out_bytes(), Some(&[0u8, 159, 146, 150][..]));
887    }
888
889    #[test]
890    fn valid_utf8_bytes_coerce_to_text() {
891        let r = ExecResult::success_bytes(b"plain text".to_vec());
892        assert!(r.is_bytes());
893        assert_eq!(r.try_text_out().unwrap(), "plain text");
894        assert_eq!(&*r.text_out(), "plain text");
895    }
896
897    #[test]
898    fn materialize_preserves_existing_out() {
899        use crate::output::OutputData;
900        let mut result = ExecResult::with_output_and_text(OutputData::text("ignored"), "custom");
901        result.materialize();
902        assert_eq!(&*result.text_out(),"custom");
903    }
904
905    #[test]
906    fn take_output_for_stream_when_out_empty() {
907        use crate::output::{OutputData, OutputNode};
908        // Use structured output — text now goes to .out directly
909        let nodes = OutputData::nodes(vec![OutputNode::new("a")]);
910        let mut result = ExecResult::with_output(nodes);
911        let taken = result.take_output_for_stream();
912        assert!(taken.is_some());
913        assert!(!result.has_output());
914    }
915
916    #[test]
917    fn with_output_simple_text_populates_out_directly() {
918        use crate::output::OutputData;
919        let result = ExecResult::with_output(OutputData::text("hello"));
920        // Simple text should go to .out, not .output
921        assert!(!result.has_output());
922        assert_eq!(&*result.text_out(), "hello");
923        // Even JSON-shaped text is NOT auto-parsed — .data stays None.
924        let json_result = ExecResult::with_output(OutputData::text(r#"{"key": 1}"#));
925        assert!(json_result.data.is_none());
926    }
927
928    fn latch_req(paths: &[&str]) -> LatchRequest {
929        LatchRequest {
930            nonce: "a3f7b2c1".to_string(),
931            command: "rm".to_string(),
932            paths: paths.iter().map(|p| (*p).to_string()).collect(),
933            hint: "rm --confirm=\"a3f7b2c1\" important.dat".to_string(),
934            tool: "rm".to_string(),
935            argv: paths.iter().map(|p| (*p).to_string()).collect(),
936            ttl: 60,
937            job_id: None,
938        }
939    }
940
941    #[test]
942    fn latch_request_reads_the_latch_field() {
943        let mut result = ExecResult::failure(2, "rm: confirmation required (latch enabled)");
944        result.latch = Some(Box::new(latch_req(&["important.dat"])));
945
946        let req = result.latch_request().expect("a latch request");
947        assert_eq!(req.nonce, "a3f7b2c1");
948        assert_eq!(req.command, "rm");
949        assert_eq!(req.paths, vec!["important.dat".to_string()]);
950        assert_eq!(req.ttl, 60);
951        assert!(req.hint.contains("--confirm"));
952    }
953
954    #[test]
955    fn latch_request_handles_command_only_empty_paths() {
956        let mut result = ExecResult::failure(2, "kaish-trash empty: confirmation required");
957        result.latch = Some(Box::new(LatchRequest {
958            nonce: "deadbeef".to_string(),
959            command: "kaish-trash empty".to_string(),
960            paths: vec![],
961            hint: "kaish-trash empty --confirm=deadbeef".to_string(),
962            tool: "kaish-trash".to_string(),
963            argv: vec!["--".to_string(), "empty".to_string()],
964            ttl: 60,
965            job_id: None,
966        }));
967
968        let req = result.latch_request().expect("a latch request");
969        assert_eq!(req.command, "kaish-trash empty");
970        assert!(req.paths.is_empty());
971    }
972
973    #[test]
974    fn latch_request_none_when_no_latch_set() {
975        // A success result and a plain exit-2 usage error both carry no latch.
976        assert!(ExecResult::success("").latch_request().is_none());
977        assert!(ExecResult::failure(2, "rm: unknown flag --bogus")
978            .latch_request()
979            .is_none());
980    }
981
982    #[test]
983    fn latch_request_ignores_data_plane_data() {
984        // Data-plane `.data` (even on an exit-2 result) is never a latch — the
985        // latch lives on its own field. Structural guarantee, pinned.
986        let mut result = ExecResult::failure(2, "boom");
987        result.data = Some(Value::Json(serde_json::json!({"count": 3})));
988        assert!(result.latch_request().is_none());
989    }
990
991    #[test]
992    fn clear_stdout_drops_data_but_never_the_latch() {
993        // A stdout redirect clears the data-plane .data unconditionally, but the
994        // control-plane latch on its own field survives (rm precious > log still
995        // gates). Guards the plane split at the type level.
996        let mut result = ExecResult::success_data(Value::Json(serde_json::json!([1, 2, 3])));
997        result.latch = Some(Box::new(latch_req(&["precious.txt"])));
998        result.clear_stdout();
999        assert!(result.data.is_none(), "data-plane .data must clear");
1000        assert!(
1001            result.latch_request().is_some(),
1002            "control-plane latch must survive a stdout redirect"
1003        );
1004    }
1005
1006    #[test]
1007    fn take_output_for_stream_when_out_populated() {
1008        use crate::output::OutputData;
1009        let mut result = ExecResult::with_output_and_text(OutputData::text("x"), "custom");
1010        let taken = result.take_output_for_stream();
1011        assert!(taken.is_none());
1012        assert!(result.has_output()); // not taken
1013    }
1014}