kaish-types 0.8.1

Pure data types for kaish — structured output, values, tool schemas
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
//! Structured output model (Tree-of-Tables) and output format handling.
//!
//! The unified output model uses `OutputData` containing a tree of `OutputNode`s:
//!
//! - **Builtins**: Pure data producers returning `OutputData`
//! - **Frontends**: Handle all rendering (REPL, MCP, kaijutsu)

use serde::{Deserialize, Serialize};

use crate::result::ExecResult;

// ============================================================
// Structured Output (Tree-of-Tables Model)
// ============================================================

/// Entry type for rendering hints (colors, icons).
///
/// This unified enum is used by both the new OutputNode system
/// and the legacy DisplayHint::Table for backward compatibility.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum EntryType {
    /// Generic text content.
    #[default]
    Text,
    /// Regular file.
    File,
    /// Directory.
    Directory,
    /// Executable file.
    Executable,
    /// Symbolic link.
    Symlink,
}

/// A node in the output tree.
///
/// All fields are always serialized (no skip_serializing_if) for predictable shape
/// across JSON, postcard, and bincode formats.
///
/// `text` is Option<String> because None and Some("") are semantically distinct:
/// - None: this is a named entry (file listing, table row), not a text node
/// - Some(""): this IS a text node whose content is empty (e.g. `echo ""`)
///
/// The `is_text_only()` method depends on this distinction.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default)]
pub struct OutputNode {
    /// Primary identifier (filename, key, label).
    pub name: String,
    /// Rendering hint (colors, icons).
    pub entry_type: EntryType,
    /// Text content (for echo, cat, exec).
    ///
    /// Three-state semantics:
    /// - `None` — named entry (file listing, table row), not text
    /// - `Some("")` — text node with empty content (e.g., `echo ""`)
    /// - `Some("x")` — text node with content
    ///
    /// `is_text_only()` returns true iff text is Some AND name/cells/children are empty.
    pub text: Option<String>,
    /// Additional columns (for ls -l, ps, env).
    pub cells: Vec<String>,
    /// Child nodes (for tree, find).
    pub children: Vec<OutputNode>,
}

impl OutputNode {
    /// Create a new node with a name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            ..Default::default()
        }
    }

    /// Create a text-only node (for echo, cat, etc.).
    pub fn text(content: impl Into<String>) -> Self {
        Self {
            text: Some(content.into()),
            ..Default::default()
        }
    }

    /// Set the entry type for rendering hints.
    pub fn with_entry_type(mut self, entry_type: EntryType) -> Self {
        self.entry_type = entry_type;
        self
    }

    /// Set additional columns for tabular output.
    pub fn with_cells(mut self, cells: Vec<String>) -> Self {
        self.cells = cells;
        self
    }

    /// Set child nodes for tree output.
    pub fn with_children(mut self, children: Vec<OutputNode>) -> Self {
        self.children = children;
        self
    }

    /// Set text content.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Check if this is a text-only node.
    pub fn is_text_only(&self) -> bool {
        self.text.is_some() && self.name.is_empty() && self.cells.is_empty() && self.children.is_empty()
    }

    /// Check if this node has children.
    pub fn has_children(&self) -> bool {
        !self.children.is_empty()
    }

    /// Estimate brace-notation byte size without materializing.
    pub fn estimated_byte_size(&self) -> usize {
        if self.children.is_empty() {
            self.name.len() + self.text.as_ref().map_or(0, |t| t.len())
        } else {
            // "name/{child1,child2,...}"
            let mut size = self.name.len() + 2; // name + "/{" + "}"
            for (i, child) in self.children.iter().enumerate() {
                if i > 0 {
                    size += 1; // comma separator
                }
                size += child.estimated_byte_size();
            }
            size + 1 // closing brace
        }
    }

    /// Write brace-notation to a writer. Returns bytes written.
    pub fn write_canonical(&self, w: &mut dyn std::io::Write, budget: usize) -> std::io::Result<usize> {
        if self.children.is_empty() {
            w.write_all(self.name.as_bytes())?;
            return Ok(self.name.len());
        }
        let mut written = 0;
        w.write_all(self.name.as_bytes())?;
        written += self.name.len();
        if written >= budget {
            return Ok(written);
        }
        w.write_all(b"/{")?;
        written += 2;
        for (i, child) in self.children.iter().enumerate() {
            if written >= budget {
                break;
            }
            if i > 0 {
                w.write_all(b",")?;
                written += 1;
            }
            written += child.write_canonical(w, budget.saturating_sub(written))?;
        }
        w.write_all(b"}")?;
        written += 1;
        Ok(written)
    }

    /// Get the display name, potentially with text content.
    pub fn display_name(&self) -> &str {
        if self.name.is_empty() {
            self.text.as_deref().unwrap_or("")
        } else {
            &self.name
        }
    }
}

/// Structured output data from a command.
///
/// This is the top-level structure for command output.
/// It contains optional column headers and a list of root nodes.
///
/// `headers` is Option<Vec<String>> because None means "not tabular" while
/// Some(vec![]) means "tabular with no column headers." The rendering dispatch
/// in to_json() and the REPL formatter branch on this distinction.
///
/// # Rendering Rules
///
/// | Structure | Interactive | Piped/Model |
/// |-----------|-------------|-------------|
/// | Single node with `text` | Print text | Print text |
/// | Flat nodes, `name` only | Multi-column, colored | One per line |
/// | Flat nodes with `cells` | Aligned table | TSV or names only |
/// | Nested `children` | Box-drawing tree | Brace notation |
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(default)]
#[non_exhaustive]
pub struct OutputData {
    /// Column headers (optional, for table output).
    pub headers: Option<Vec<String>>,
    /// Top-level nodes.
    pub root: Vec<OutputNode>,
    /// Render-only override for `--json` consumers. When `Some`,
    /// `to_json()` returns this verbatim instead of inferring from
    /// `headers` / `root` / `cells`. Use it when a builtin wants its
    /// `--json` shape to be richer than the table form (e.g. grep
    /// emitting per-match objects with submatches and byte offsets).
    ///
    /// Skipped by serde (and thus by postcard / bincode) — this is a
    /// transient render hint, not part of the persisted shape.
    #[serde(skip)]
    #[cfg_attr(feature = "schema", schemars(skip))]
    pub rich_json: Option<serde_json::Value>,
}

impl OutputData {
    /// Create new empty output data.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create output data with a single text node.
    ///
    /// This is the simplest form for commands like `echo`.
    pub fn text(content: impl Into<String>) -> Self {
        Self {
            headers: None,
            root: vec![OutputNode::text(content)],
            rich_json: None,
        }
    }

    /// Create output data with named nodes (for ls, etc.).
    pub fn nodes(nodes: Vec<OutputNode>) -> Self {
        Self {
            headers: None,
            root: nodes,
            rich_json: None,
        }
    }

    /// Create output data with headers and nodes (for ls -l, ps, etc.).
    pub fn table(headers: Vec<String>, nodes: Vec<OutputNode>) -> Self {
        Self {
            headers: Some(headers),
            root: nodes,
            rich_json: None,
        }
    }

    /// Set column headers.
    pub fn with_headers(mut self, headers: Vec<String>) -> Self {
        self.headers = Some(headers);
        self
    }

    /// Attach a render-only `--json` override. See `rich_json` field doc.
    pub fn with_rich_json(mut self, value: serde_json::Value) -> Self {
        self.rich_json = Some(value);
        self
    }

    /// Check if this output is simple text (single text-only node).
    pub fn is_simple_text(&self) -> bool {
        self.root.len() == 1 && self.root[0].is_text_only()
    }

    /// Check if this output is a flat list (no nested children).
    pub fn is_flat(&self) -> bool {
        self.root.iter().all(|n| !n.has_children())
    }

    /// Check if this output has tabular data (nodes with cells).
    pub fn is_tabular(&self) -> bool {
        self.root.iter().any(|n| !n.cells.is_empty())
    }

    /// Get the text content if this is simple text output.
    pub fn as_text(&self) -> Option<&str> {
        if self.is_simple_text() {
            self.root[0].text.as_deref()
        } else {
            None
        }
    }

    /// Extract the owned String from a single-text-node OutputData.
    /// Returns `Err(self)` for non-simple-text output (tables, trees, multi-node),
    /// giving the caller back the unconsumed OutputData.
    pub fn into_text(mut self) -> Result<String, Self> {
        if self.root.len() == 1 && self.root[0].is_text_only() {
            Ok(self.root.pop().and_then(|n| n.text).unwrap_or_default())
        } else {
            Err(self)
        }
    }

    /// Estimate canonical string byte size without materializing.
    ///
    /// Lower bound — actual may be slightly larger due to formatting.
    /// Mirrors `to_canonical_string()` structure but only accumulates sizes.
    pub fn estimated_byte_size(&self) -> usize {
        if self.root.len() == 1 && self.root[0].is_text_only() {
            return self.root[0].text.as_ref().map_or(0, |t| t.len());
        }

        if self.is_flat() {
            let mut size = 0;
            for (i, n) in self.root.iter().enumerate() {
                if i > 0 {
                    size += 1; // newline separator
                }
                size += n.display_name().len();
                for cell in &n.cells {
                    size += 1 + cell.len(); // tab + cell
                }
            }
            return size;
        }

        // Tree: estimate brace notation
        let mut size = 0;
        for (i, n) in self.root.iter().enumerate() {
            if i > 0 {
                size += 1; // newline separator
            }
            size += n.estimated_byte_size();
        }
        size
    }

    /// Write canonical representation to a writer with optional byte budget.
    ///
    /// Returns total bytes written. Stops after budget exceeded (imprecise:
    /// one write past the limit is fine — caller uses this for spill detection,
    /// not for exact truncation).
    pub fn write_canonical(&self, w: &mut dyn std::io::Write, budget: Option<usize>) -> std::io::Result<usize> {
        let mut written = 0usize;
        let budget = budget.unwrap_or(usize::MAX);

        if self.root.len() == 1 && self.root[0].is_text_only() {
            if let Some(ref text) = self.root[0].text {
                w.write_all(text.as_bytes())?;
                return Ok(text.len());
            }
            return Ok(0);
        }

        if self.is_flat() {
            for (i, n) in self.root.iter().enumerate() {
                if i > 0 {
                    w.write_all(b"\n")?;
                    written += 1;
                }
                let name = n.display_name();
                w.write_all(name.as_bytes())?;
                written += name.len();
                for cell in &n.cells {
                    w.write_all(b"\t")?;
                    w.write_all(cell.as_bytes())?;
                    written += 1 + cell.len();
                }
                if written > budget {
                    return Ok(written);
                }
            }
            return Ok(written);
        }

        // Tree: brace notation
        for (i, n) in self.root.iter().enumerate() {
            if i > 0 {
                w.write_all(b"\n")?;
                written += 1;
            }
            written += n.write_canonical(w, budget.saturating_sub(written))?;
            if written > budget {
                return Ok(written);
            }
        }
        Ok(written)
    }

    /// Convert to canonical string output (for pipes).
    ///
    /// This produces a simple string representation suitable for
    /// piping to other commands:
    /// - Text nodes: their text content
    /// - Named nodes: names joined by newlines
    /// - Tabular nodes (name + cells): TSV format (name\tcell1\tcell2...)
    /// - Nested nodes: brace notation
    pub fn to_canonical_string(&self) -> String {
        if let Some(text) = self.as_text() {
            return text.to_string();
        }

        // For flat lists (with or without cells), output one line per node
        if self.is_flat() {
            return self.root.iter()
                .map(|n| {
                    if n.cells.is_empty() {
                        n.display_name().to_string()
                    } else {
                        // For tabular data, use TSV format
                        let mut parts = vec![n.display_name().to_string()];
                        parts.extend(n.cells.iter().cloned());
                        parts.join("\t")
                    }
                })
                .collect::<Vec<_>>()
                .join("\n");
        }

        // For trees, use brace notation
        fn format_node(node: &OutputNode) -> String {
            if node.children.is_empty() {
                node.name.clone()
            } else {
                let children: Vec<String> = node.children.iter()
                    .map(format_node)
                    .collect();
                format!("{}/{{{}}}", node.name, children.join(","))
            }
        }

        self.root.iter()
            .map(format_node)
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Serialize to a JSON value for `--json` flag handling.
    ///
    /// Bare data, no envelope — optimized for `jq` patterns.
    ///
    /// | Structure | JSON |
    /// |-----------|------|
    /// | Simple text | `"hello world"` |
    /// | Flat list (names only) | `["file1", "file2"]` |
    /// | Table (headers + cells) | `[{"col1": "v1", ...}, ...]` |
    /// | Tree (nested children) | `{"dir": {"file": null}}` |
    pub fn to_json(&self) -> serde_json::Value {
        // Builtin-supplied override wins (used by `grep --json` to expose
        // submatches/byte offsets that don't fit the table model).
        if let Some(rich) = &self.rich_json {
            return rich.clone();
        }
        // Simple text -> JSON string
        if let Some(text) = self.as_text() {
            return serde_json::Value::String(text.to_string());
        }

        // Table -> array of objects keyed by headers
        if let Some(ref headers) = self.headers {
            let rows: Vec<serde_json::Value> = self.root.iter().map(|node| {
                let mut map = serde_json::Map::new();
                // First header maps to node.name
                if let Some(first) = headers.first() {
                    map.insert(first.clone(), serde_json::Value::String(node.name.clone()));
                }
                // Remaining headers map to cells
                for (header, cell) in headers.iter().skip(1).zip(node.cells.iter()) {
                    map.insert(header.clone(), serde_json::Value::String(cell.clone()));
                }
                serde_json::Value::Object(map)
            }).collect();
            return serde_json::Value::Array(rows);
        }

        // Tree -> nested object
        if !self.is_flat() {
            fn node_to_json(node: &OutputNode) -> serde_json::Value {
                if node.children.is_empty() {
                    serde_json::Value::Null
                } else {
                    let mut map = serde_json::Map::new();
                    for child in &node.children {
                        map.insert(child.name.clone(), node_to_json(child));
                    }
                    serde_json::Value::Object(map)
                }
            }

            // Single root node -> its children as the top-level object
            if self.root.len() == 1 {
                return node_to_json(&self.root[0]);
            }
            // Multiple root nodes -> object with each root as a key
            let mut map = serde_json::Map::new();
            for node in &self.root {
                map.insert(node.name.clone(), node_to_json(node));
            }
            return serde_json::Value::Object(map);
        }

        // Flat list -> array of strings
        let items: Vec<serde_json::Value> = self.root.iter()
            .map(|n| serde_json::Value::String(n.display_name().to_string()))
            .collect();
        serde_json::Value::Array(items)
    }
}

// ============================================================
// Output Format (Global --json flag)
// ============================================================

/// Output serialization format, requested via global flags.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// JSON serialization via OutputData::to_json()
    Json,
}

/// Transform an ExecResult into the requested output format.
///
/// Serializes regardless of exit code — commands like `diff` (exit 1 = files differ)
/// and `grep` (exit 1 = no matches) use non-zero exits for semantic meaning,
/// not errors. The `--json` contract must hold for all exit codes.
pub fn apply_output_format(mut result: ExecResult, format: OutputFormat) -> ExecResult {
    if !result.has_output() && result.text_out().is_empty() {
        // No stdout to format. A failure that carries a diagnostic message must
        // still honor --json — otherwise the message leaks out as plain text
        // even though structured output was requested. Emit a JSON error object
        // so the contract holds on the error path. A clean non-zero exit with no
        // message (e.g. `grep` no-match, exit 1) is not an error and stays empty.
        if !result.ok() && !result.err.is_empty() {
            match format {
                OutputFormat::Json => {
                    let obj = serde_json::json!({
                        "error": result.err,
                        "code": result.code,
                    });
                    result.data = Some(crate::result::json_to_value(obj.clone()));
                    result.set_out(
                        serde_json::to_string(&obj).unwrap_or_else(|_| "null".to_string()),
                    );
                }
            }
        }
        return result;
    }
    match format {
        OutputFormat::Json => {
            if let Some(output) = result.output() {
                let json_value = output.to_json();
                // NLL: borrow of result via output ends here (json_value is owned)
                result.set_out(serde_json::to_string(&json_value)
                    .unwrap_or_else(|_| "null".to_string()));
                result.data = Some(crate::result::json_to_value(json_value));
            } else {
                // Text-only: wrap as JSON string. .data mirrors the same string.
                let text = result.text_out().into_owned();
                let json_out = serde_json::to_string(&text)
                    .unwrap_or_else(|_| "null".to_string());
                result.data = Some(crate::value::Value::String(text));
                result.set_out(json_out);
            }
            // Clear sentinel — format already applied, prevents double-encoding
            result.set_output(None);
            result
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn entry_type_variants() {
        assert_ne!(EntryType::File, EntryType::Directory);
        assert_ne!(EntryType::Directory, EntryType::Executable);
        assert_ne!(EntryType::Executable, EntryType::Symlink);
    }

    #[test]
    fn to_json_simple_text() {
        let output = OutputData::text("hello world");
        assert_eq!(output.to_json(), serde_json::json!("hello world"));
    }

    #[test]
    fn to_json_flat_list() {
        let output = OutputData::nodes(vec![
            OutputNode::new("file1"),
            OutputNode::new("file2"),
            OutputNode::new("file3"),
        ]);
        assert_eq!(output.to_json(), serde_json::json!(["file1", "file2", "file3"]));
    }

    #[test]
    fn to_json_table() {
        let output = OutputData::table(
            vec!["NAME".into(), "SIZE".into(), "TYPE".into()],
            vec![
                OutputNode::new("foo.rs").with_cells(vec!["1024".into(), "file".into()]),
                OutputNode::new("bar/").with_cells(vec!["4096".into(), "dir".into()]),
            ],
        );
        assert_eq!(output.to_json(), serde_json::json!([
            {"NAME": "foo.rs", "SIZE": "1024", "TYPE": "file"},
            {"NAME": "bar/", "SIZE": "4096", "TYPE": "dir"},
        ]));
    }

    #[test]
    fn to_json_tree() {
        let child1 = OutputNode::new("main.rs").with_entry_type(EntryType::File);
        let child2 = OutputNode::new("utils.rs").with_entry_type(EntryType::File);
        let subdir = OutputNode::new("lib")
            .with_entry_type(EntryType::Directory)
            .with_children(vec![child2]);
        let root = OutputNode::new("src")
            .with_entry_type(EntryType::Directory)
            .with_children(vec![child1, subdir]);

        let output = OutputData::nodes(vec![root]);
        assert_eq!(output.to_json(), serde_json::json!({
            "main.rs": null,
            "lib": {"utils.rs": null},
        }));
    }

    #[test]
    fn to_json_tree_multiple_roots() {
        let root1 = OutputNode::new("src")
            .with_entry_type(EntryType::Directory)
            .with_children(vec![OutputNode::new("main.rs")]);
        let root2 = OutputNode::new("docs")
            .with_entry_type(EntryType::Directory)
            .with_children(vec![OutputNode::new("README.md")]);

        let output = OutputData::nodes(vec![root1, root2]);
        assert_eq!(output.to_json(), serde_json::json!({
            "src": {"main.rs": null},
            "docs": {"README.md": null},
        }));
    }

    #[test]
    fn to_json_empty() {
        let output = OutputData::new();
        assert_eq!(output.to_json(), serde_json::json!([]));
    }

    #[test]
    fn apply_output_format_clears_sentinel() {
        let output = OutputData::table(
            vec!["NAME".into()],
            vec![OutputNode::new("test")],
        );
        let result = ExecResult::with_output(output);
        assert!(result.has_output(), "before: sentinel present");

        let formatted = apply_output_format(result, OutputFormat::Json);
        assert!(!formatted.has_output(), "after Json: sentinel cleared");
    }

    #[test]
    fn apply_output_format_no_double_encoding() {
        let output = OutputData::nodes(vec![
            OutputNode::new("file1"),
            OutputNode::new("file2"),
        ]);
        let result = ExecResult::with_output(output);

        let after_json = apply_output_format(result, OutputFormat::Json);
        let json_out = after_json.text_out().into_owned();
        assert!(!after_json.has_output(), "sentinel cleared by Json");

        let parsed: serde_json::Value = serde_json::from_str(&json_out).expect("valid JSON");
        assert_eq!(parsed, serde_json::json!(["file1", "file2"]));
    }

    #[test]
    fn apply_output_format_populates_data() {
        let output = OutputData::nodes(vec![
            OutputNode::new("file1"),
            OutputNode::new("file2"),
        ]);
        let result = ExecResult::with_output(output);
        assert!(result.data.is_none(), "before: no data on non-text output");

        let formatted = apply_output_format(result, OutputFormat::Json);
        assert!(formatted.data.is_some(), "after Json: data populated");

        // data should match the JSON in out
        let data = formatted.data.unwrap();
        assert!(matches!(data, crate::value::Value::Json(_)), "data should be Json variant");
        if let crate::value::Value::Json(json) = data {
            assert_eq!(json, serde_json::json!(["file1", "file2"]));
        }
    }

    #[test]
    fn apply_output_format_compact_json() {
        let output = OutputData::nodes(vec![
            OutputNode::new("file1"),
            OutputNode::new("file2"),
        ]);
        let result = ExecResult::with_output(output);

        let formatted = apply_output_format(result, OutputFormat::Json);
        // Compact JSON: no pretty-printing (no newlines within the array)
        let out = formatted.text_out();
        assert!(!out.contains('\n'), "should be compact JSON, got: {}", out);
        assert_eq!(&*out, r#"["file1","file2"]"#);
    }

    #[test]
    fn apply_output_format_emits_json_error_object_on_failure() {
        // A failure with empty stdout and a populated err must still honor
        // --json: emit {"error", "code"} rather than leaking the message as
        // plain text (e.g. `grep --json --bogus-flag`).
        let result = ExecResult::failure(2, "grep: unknown flag --bogus-flag");
        assert!(!result.has_output());
        assert!(result.text_out().is_empty());

        let formatted = apply_output_format(result, OutputFormat::Json);
        let out = formatted.text_out().into_owned();
        let parsed: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(
            parsed,
            serde_json::json!({"error": "grep: unknown flag --bogus-flag", "code": 2})
        );
        // .data mirrors the JSON object.
        assert!(matches!(formatted.data, Some(crate::value::Value::Json(_))));
    }

    #[test]
    fn apply_output_format_leaves_clean_no_match_empty() {
        // grep no-match: exit 1, empty stdout, empty err. Not an error — must
        // NOT be wrapped in a JSON error object; stays empty.
        let result = ExecResult::failure(1, "");
        let formatted = apply_output_format(result, OutputFormat::Json);
        assert!(formatted.text_out().is_empty());
        assert!(formatted.data.is_none());
    }

    #[test]
    fn apply_output_format_empty_success_stays_empty() {
        let result = ExecResult::success("");
        let formatted = apply_output_format(result, OutputFormat::Json);
        assert!(formatted.text_out().is_empty());
        assert!(formatted.data.is_none());
    }

    #[test]
    fn estimated_byte_size_text_only_node() {
        let node = OutputNode::text("hello world");
        // Text-only node: name is empty, text is "hello world" (11 bytes)
        assert_eq!(node.estimated_byte_size(), 11);
    }

    #[test]
    fn estimated_byte_size_named_node() {
        let node = OutputNode::new("file.txt");
        assert_eq!(node.estimated_byte_size(), 8);
    }

    #[test]
    fn write_canonical_respects_budget() {
        let parent = OutputNode::new("root")
            .with_children(vec![
                OutputNode::new("aaaa"),
                OutputNode::new("bbbb"),
                OutputNode::new("cccc"),
            ]);
        // With a very small budget, should stop writing children early
        let mut buf = Vec::new();
        let written = parent.write_canonical(&mut buf, 8).unwrap();
        let output = String::from_utf8(buf).unwrap();
        // "root" (4) + "/{" (2) = 6, then budget check kicks in after first child
        assert!(written <= 16, "should respect budget, wrote {} bytes: {}", written, output);
        // Should at least write the root name
        assert!(output.starts_with("root"), "should start with root: {}", output);
    }

    #[test]
    fn into_text_simple() {
        let data = OutputData::text("hello");
        assert_eq!(data.into_text(), Ok("hello".to_string()));
    }

    #[test]
    fn into_text_non_simple() {
        let data = OutputData::nodes(vec![OutputNode::new("a"), OutputNode::new("b")]);
        assert!(data.into_text().is_err());
    }

    #[test]
    fn into_text_empty() {
        let data = OutputData::text("");
        assert_eq!(data.into_text(), Ok("".to_string()));
    }
}