kaish-kernel 0.8.0

Core kernel for kaish: lexer, parser, interpreter, and runtime
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
809
810
811
//! jq — Native JSON query tool using jaq.
//!
//! This implementation uses the jaq crate for native jq execution
//! without spawning an external process. Benefits:
//! - Parse-time filter validation (fail fast)
//! - No subprocess overhead
//! - Consistent behavior across platforms
//! - Type-safe Rust API
//!
//! # Examples
//!
//! ```kaish
//! echo '{"name": "Alice"}' | jq ".name"
//! echo '{"name": "Alice"}' | jq ".name" -r
//! jq ".items[]" path=/data/items.json
//! jq ".[] | select(.active)" -c
//! ```

use std::path::Path;

use async_trait::async_trait;
use clap::{CommandFactory, Parser};
use jaq_core::{load, compile, Ctx, RcIter};
use jaq_json::Val;

use crate::ast::Value;
use crate::interpreter::{ExecResult, OutputData};
use crate::tools::{schema_from_clap, ExecContext, ToolCtx, GlobalFlags, ParamSchema, Tool, ToolArgs, ToolSchema};

/// Native jq tool using jaq (pure Rust jq implementation).
pub struct JqNative;

/// clap-derived argv layer for jq. See docs/clap-migration.md.
///
/// jq's filter syntax stays hand-rolled — only argv-level flags are declared
/// here. `--arg` / `--argjson` are accept-and-ignore at the clap level; the
/// body reads them from `args.named` (kernel pre-parses them as
/// `consumes=2` `Json(Array(Array([NAME, VALUE])))` pairs).
#[derive(Parser, Debug)]
#[command(name = "jq", about = "Native JSON query processor")]
struct JqArgs {
    /// Raw output mode (-r): output strings without quotes.
    #[arg(short = 'r', long = "raw")]
    raw: bool,

    /// Compact output mode (-c): no pretty-printing.
    #[arg(short = 'c', long = "compact")]
    compact: bool,

    /// Use null as input instead of reading stdin (-n).
    #[arg(short = 'n', long = "null-input", visible_alias = "null_input")]
    null_input: bool,

    /// Read from VFS file instead of stdin.
    #[arg(long = "path")]
    path: Option<String>,

    /// Bind a kaish variable as a jq string: --arg NAME VALUE → $NAME.
    /// Accept-and-ignore: body reads from args.named (kernel pre-parses both
    /// tokens together as a 2-value pair via `consumes=2` in the schema).
    /// At the clap layer we accept a single string because to_argv() joins
    /// the pair as `--arg=NAME VALUE`.
    #[arg(id = "arg", long = "arg", action = clap::ArgAction::Append, value_name = "NAME VALUE")]
    _arg: Vec<String>,

    /// Bind a kaish variable as a jq JSON value: --argjson NAME JSON → $NAME.
    /// See _arg above for the consumes=2 / clap-layer split.
    #[arg(id = "argjson", long = "argjson", action = clap::ArgAction::Append, value_name = "NAME JSON")]
    _argjson: Vec<String>,

    #[command(flatten)]
    global: GlobalFlags,

    /// Sink — filter + path live on args.positional.
    #[arg(hide = true)]
    rest: Vec<String>,
}

type Filter = jaq_core::Filter<jaq_core::Native<Val>>;

/// Parse and compile a jq filter expression.
///
/// `global_vars` are the bindings introduced by `--arg` / `--argjson`, in
/// declaration order. Each name must start with `$` (per `jaq_core`'s
/// `with_global_vars` contract). Values are supplied at execution time via
/// `Ctx::new` in the same order.
fn compile_filter(filter_str: &str, global_vars: &[String]) -> Result<Filter, String> {
    // Create arena for parsing
    let arena = load::Arena::default();

    // Load standard library definitions
    let defs = jaq_std::defs().chain(jaq_json::defs());
    let loader = load::Loader::new(defs);

    // Parse the filter
    let modules = loader
        .load(&arena, load::File { path: (), code: filter_str })
        .map_err(|errs| {
            let msgs: Vec<String> = errs
                .into_iter()
                .flat_map(|(_, e)| -> Vec<String> {
                    match e {
                        load::Error::Io(io_errs) => io_errs.into_iter().map(|(_, msg)| msg).collect(),
                        load::Error::Lex(lex_errs) => lex_errs.into_iter().map(|(expected, _)| format!("expected {}", expected.as_str())).collect(),
                        load::Error::Parse(parse_errs) => parse_errs.into_iter().map(|(expected, _)| format!("expected {}", expected.as_str())).collect(),
                    }
                })
                .collect();
            format!("jq parse error: {}", msgs.join(", "))
        })?;

    // Compile with standard library functions and any `--arg` / `--argjson` bindings.
    let funs = jaq_std::funs().chain(jaq_json::funs());
    let compiler = compile::Compiler::default()
        .with_funs(funs)
        .with_global_vars(global_vars.iter().map(String::as_str));
    let filter = compiler.compile(modules).map_err(|errs| {
        let msgs: Vec<String> = errs
            .into_iter()
            .flat_map(|(_, errors)| {
                errors.into_iter().map(|(_, undefined)| format!("undefined {}", undefined.as_str()))
            })
            .collect();
        format!("jq compile error: {}", msgs.join(", "))
    })?;

    Ok(filter)
}

/// Outcome of running a compiled jq filter: rendered text for pipes/stdout
/// plus the raw per-output JSON values so callers can populate `.data`.
///
/// `text` uses `-r` or pretty JSON per the caller's preference and is the
/// canonical representation for downstream pipe stages. `values` preserves
/// the filter's output stream as a list of JSON values regardless of how
/// they were rendered — this is what enables `for i in $(jq -r '.[]' …)`
/// to iterate each element instead of binding the whole newline-joined
/// stdout to a single loop variable.
struct JqRun {
    text: String,
    values: Vec<serde_json::Value>,
}

/// Execute a compiled jq filter on pre-parsed JSON.
///
/// `var_values` holds JSON values for any `--arg` / `--argjson` bindings
/// declared at compile time, in the **same order** as `global_vars` passed
/// to `compile_filter`. They're converted to `Val` inside this function
/// because `Val` contains `Rc` pointers and is therefore `!Send` — keeping
/// the conversion here lets the async caller stay `Send` across `.await`.
fn execute_filter_json(
    filter: &Filter,
    json: serde_json::Value,
    raw_output: bool,
    var_values: Vec<serde_json::Value>,
) -> Result<JqRun, String> {
    // Convert serde_json::Value to jaq_json::Val
    let input_val = json_to_val(json);
    let vars: Vec<Val> = var_values.into_iter().map(json_to_val).collect();

    // Create execution context with empty inputs iterator
    let inputs: RcIter<_> = RcIter::new(Box::new(core::iter::empty()));
    let ctx = Ctx::new(vars, &inputs);

    // Run the filter
    let results: Vec<Result<Val, jaq_core::Error<Val>>> = filter
        .run((ctx, input_val))
        .collect();

    // Format output and collect raw values in lock-step.
    let mut text = String::new();
    let mut values = Vec::with_capacity(results.len());
    for result in results {
        match result {
            Ok(val) => {
                let formatted = if raw_output {
                    format_raw(&val)
                } else {
                    format_json(&val)
                };
                if !text.is_empty() {
                    text.push('\n');
                }
                text.push_str(&formatted);
                values.push(val_to_json(&val));
            }
            Err(e) => {
                return Err(format!("jq runtime error: {}", e));
            }
        }
    }

    Ok(JqRun { text, values })
}

/// Convert serde_json::Value to jaq_json::Val.
fn json_to_val(json: serde_json::Value) -> Val {
    use std::rc::Rc;
    match json {
        serde_json::Value::Null => Val::Null,
        serde_json::Value::Bool(b) => Val::Bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                // Try to fit in isize, fall back to Num for large values
                if let Ok(i) = isize::try_from(i) {
                    Val::Int(i)
                } else {
                    Val::Num(Rc::new(n.to_string()))
                }
            } else if let Some(f) = n.as_f64() {
                Val::Float(f)
            } else {
                // Fall back to string representation for very large numbers
                Val::Num(Rc::new(n.to_string()))
            }
        }
        serde_json::Value::String(s) => Val::Str(Rc::new(s)),
        serde_json::Value::Array(arr) => Val::Arr(Rc::new(arr.into_iter().map(json_to_val).collect())),
        serde_json::Value::Object(obj) => {
            Val::obj(obj.into_iter().map(|(k, v)| (Rc::new(k), json_to_val(v))).collect())
        }
    }
}

/// Format a jaq value as raw output (strings without quotes).
fn format_raw(val: &Val) -> String {
    match val {
        Val::Str(s) => s.to_string(),
        Val::Null => "null".to_string(),
        Val::Bool(b) => b.to_string(),
        Val::Int(n) => n.to_string(),
        Val::Float(n) => format!("{:?}", n),
        Val::Num(s) => s.to_string(),
        Val::Arr(arr) => {
            let items: Vec<String> = arr.iter().map(format_raw).collect();
            items.join("\n")
        }
        Val::Obj(_) => serde_json::to_string(&val_to_json(val)).unwrap_or_default(),
    }
}

/// Format a jaq value as JSON.
fn format_json(val: &Val) -> String {
    serde_json::to_string_pretty(&val_to_json(val)).unwrap_or_default()
}

/// Convert ast::Value to serde_json::Value for jq processing.
///
/// This is smarter than the generic value_to_json because it handles the case
/// where Value::String contains serialized JSON (for legacy compatibility).
/// Value::Json is returned directly as it's already a serde_json::Value.
fn ast_value_to_json(value: &Value) -> serde_json::Value {
    match value {
        Value::Null => serde_json::Value::Null,
        Value::Bool(b) => serde_json::Value::Bool(*b),
        Value::Int(i) => serde_json::Value::Number((*i).into()),
        Value::Float(f) => {
            serde_json::Number::from_f64(*f)
                .map(serde_json::Value::Number)
                .unwrap_or(serde_json::Value::Null)
        }
        Value::String(s) => {
            // Try to parse as JSON first - for backwards compatibility with serialized JSON in strings
            serde_json::from_str(s).unwrap_or_else(|_| serde_json::Value::String(s.clone()))
        }
        Value::Json(json) => json.clone(),
        Value::Blob(blob) => {
            let mut map = serde_json::Map::new();
            map.insert("_type".to_string(), serde_json::Value::String("blob".to_string()));
            map.insert("id".to_string(), serde_json::Value::String(blob.id.clone()));
            map.insert("size".to_string(), serde_json::Value::Number(blob.size.into()));
            map.insert("contentType".to_string(), serde_json::Value::String(blob.content_type.clone()));
            serde_json::Value::Object(map)
        }
    }
}

/// Convert jaq Val to serde_json Value.
fn val_to_json(val: &Val) -> serde_json::Value {
    match val {
        Val::Null => serde_json::Value::Null,
        Val::Bool(b) => serde_json::Value::Bool(*b),
        Val::Int(n) => serde_json::Value::Number((*n as i64).into()),
        Val::Float(n) => serde_json::Number::from_f64(*n)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        Val::Num(s) => {
            // Parse the string number back to a JSON number
            serde_json::from_str(s).unwrap_or(serde_json::Value::String(s.to_string()))
        }
        Val::Str(s) => serde_json::Value::String(s.to_string()),
        Val::Arr(arr) => serde_json::Value::Array(arr.iter().map(val_to_json).collect()),
        Val::Obj(obj) => {
            let map: serde_json::Map<String, serde_json::Value> = obj
                .iter()
                .map(|(k, v)| (k.to_string(), val_to_json(v)))
                .collect();
            serde_json::Value::Object(map)
        }
    }
}

#[async_trait]
impl Tool for JqNative {
    fn name(&self) -> &str {
        "jq"
    }

    fn schema(&self) -> ToolSchema {
        // Start from clap reflection, then layer the required `filter`
        // positional on top — clap doesn't model the schema's
        // "required positional" concept for our sink. Also override the
        // `_arg`/`_argjson` params: clap parses them as 1-value (because
        // to_argv joins NAME+VALUE as a single string after `=`), but the
        // kernel's pre-parse needs `consumes=2` to grab both POSIX-style
        // tokens.
        let mut schema = schema_from_clap(
            &JqArgs::command(),
            "jq",
            "JSON query processor — built into kaish (native jaq, no external binary). \
             The canonical way to extract fields from JSON: pipe data in, read \
             from a variable via `jq '.field' <<< \"$VAR\"`, or bind kaish \
             variables into the filter with `--arg` / `--argjson` plus `-n`.",
            [
                ("Extract a field", "cat data.json | jq '.name'"),
                ("Raw string output", "cat data.json | jq -r '.version'"),
                ("Filter an array", "cat items.json | jq '.[] | select(.active)'"),
                ("Read JSON from a variable", r#"jq -r '.name' <<< "$RESULT""#),
                (
                    "Bind a kaish variable into the filter",
                    r#"R='{"x":42}'; jq -n --argjson r "$R" '$r.x'"#,
                ),
            ],
        );
        // Bump consumes=2 for arg/argjson: clap layer parses them as
        // single-value (the kernel joins NAME+VALUE as `--arg=NAME VALUE`
        // before clap sees it), but the kernel's POSIX-style pre-parse
        // needs to grab both tokens.
        for p in schema.params.iter_mut() {
            if matches!(p.name.as_str(), "arg" | "argjson") {
                p.consumes = 2;
            }
        }
        // Re-insert the required `filter` positional that clap can't model
        // (jq's filter expression is its first positional arg).
        schema = schema.param(
            ParamSchema::required("filter", "string", "jq filter expression").positional(),
        );
        schema
    }

    async fn execute(&self, args: ToolArgs, ctx: &mut dyn ToolCtx) -> ExecResult {
        let Some(ctx) = ctx.as_any_mut().downcast_mut::<ExecContext>() else {
            return ExecResult::failure(1, "internal error: kernel builtin requires ExecContext");
        };
        let parsed = match JqArgs::try_parse_from(
            std::iter::once("jq".to_string()).chain(args.to_argv()),
        ) {
            Ok(p) => p,
            Err(e) => return ExecResult::failure(2, format!("jq: {e}")),
        };
        parsed.global.apply(ctx);

        // Get filter (required, positional 0)
        let filter_str = match args.get_string("filter", 0) {
            Some(f) => f,
            None => return ExecResult::failure(1, "jq: filter expression required"),
        };

        // Collect `--arg NAME VALUE` (string) and `--argjson NAME VALUE` (JSON)
        // bindings in declaration order. jaq needs the names at compile time
        // and the values at run time — same order on both sides.
        let (global_var_names, global_var_values) = match collect_bindings(&args) {
            Ok(pair) => pair,
            Err(e) => return ExecResult::failure(1, e),
        };

        // Compile filter (validates at execution time)
        let filter = match compile_filter(&filter_str, &global_var_names) {
            Ok(f) => f,
            Err(e) => return ExecResult::failure(1, e),
        };

        let raw_output = parsed.raw || args.has_flag("raw") || args.has_flag("r");
        let _compact = parsed.compact || args.has_flag("compact") || args.has_flag("c");
        let null_input =
            parsed.null_input || args.has_flag("null-input") || args.has_flag("n");

        // Get input JSON. `-n` / `--null-input` skips stdin entirely and feeds
        // `null` to the filter — same as real jq. Otherwise: fast path through
        // pre-parsed structured data, then file, then stdin text.
        let input_json: serde_json::Value = if null_input {
            serde_json::Value::Null
        } else if let Some(path) = args.get_string("path", 1) {
            if !path.is_empty() {
                // Read from backend - path takes precedence over stdin
                let resolved = ctx.resolve_path(&path);
                match ctx.backend.read(Path::new(&resolved), None).await {
                    Ok(bytes) => {
                        let text = String::from_utf8_lossy(&bytes);
                        match serde_json::from_str(&text) {
                            Ok(json) => json,
                            Err(e) => return ExecResult::failure(1, format!("jq: invalid JSON in {}: {}", path, e)),
                        }
                    }
                    Err(e) => {
                        return ExecResult::failure(1, format!("jq: failed to read {}: {}", path, e))
                    }
                }
            } else if let Some(data) = ctx.take_stdin_data() {
                // Fast path: use pre-parsed structured data from pipeline
                ast_value_to_json(&data)
            } else if let Some(text) = ctx.read_stdin_to_string().await {
                // Fallback: parse stdin text as JSON
                match serde_json::from_str(&text) {
                    Ok(json) => json,
                    Err(e) => return ExecResult::failure(1, format!("jq: invalid JSON input: {}", e)),
                }
            } else {
                return ExecResult::failure(1, "jq: no input provided");
            }
        } else if let Some(data) = ctx.take_stdin_data() {
            // Fast path: use pre-parsed structured data from pipeline
            ast_value_to_json(&data)
        } else if let Some(text) = ctx.read_stdin_to_string().await {
            // Fallback: parse stdin text as JSON
            match serde_json::from_str(&text) {
                Ok(json) => json,
                Err(e) => return ExecResult::failure(1, format!("jq: invalid JSON input: {}", e)),
            }
        } else {
            return ExecResult::failure(1, "jq: no input provided");
        };

        // Execute filter with the JSON input
        match execute_filter_json(&filter, input_json, raw_output, global_var_values) {
            Ok(run) => build_exec_result(run),
            Err(e) => ExecResult::failure(1, e),
        }
    }
}

/// Pull `--arg` / `--argjson` pairs out of `ToolArgs` and turn them into
/// (jaq var name, jaq value) tuples in declaration order.
///
/// Values are returned as `serde_json::Value` (which is `Send`) and
/// converted to jaq's `Val` inside `execute_filter_json`. Holding the
/// `Rc`-full `Val` across an `.await` would make the async body `!Send`.
fn collect_bindings(args: &ToolArgs) -> Result<(Vec<String>, Vec<serde_json::Value>), String> {
    let mut names: Vec<String> = Vec::new();
    let mut values: Vec<serde_json::Value> = Vec::new();

    // Walk --arg pairs: Value::Json(Array([Array([NAME, VALUE]), ...]))
    if let Some(Value::Json(serde_json::Value::Array(occurrences))) = args.named.get("arg") {
        for occ in occurrences {
            let (name, raw) = extract_pair(occ, "arg")?;
            names.push(format!("${name}"));
            values.push(serde_json::Value::String(raw));
        }
    }

    // Walk --argjson pairs: same shape, but the value is parsed as JSON.
    if let Some(Value::Json(serde_json::Value::Array(occurrences))) = args.named.get("argjson") {
        for occ in occurrences {
            let (name, raw) = extract_pair(occ, "argjson")?;
            let parsed: serde_json::Value = serde_json::from_str(&raw)
                .map_err(|e| format!("jq: --argjson {name}: invalid JSON: {e}"))?;
            names.push(format!("${name}"));
            values.push(parsed);
        }
    }

    Ok((names, values))
}

/// Pull a (name, value) pair out of a serde_json 2-element array stored by
/// the kernel's `consumes=2` flag-collection path.
fn extract_pair(occ: &serde_json::Value, flag: &str) -> Result<(String, String), String> {
    match occ {
        serde_json::Value::Array(pair) if pair.len() == 2 => {
            let name = value_as_string(&pair[0])
                .ok_or_else(|| format!("jq: --{flag} NAME must be a string"))?;
            let value = value_as_string(&pair[1])
                .ok_or_else(|| format!("jq: --{flag} VALUE must be a string"))?;
            Ok((name, value))
        }
        other => Err(format!(
            "jq: internal error: --{flag} expected 2-element pair, got {other}"
        )),
    }
}

/// Coerce a serde_json value into the string form jaq expects. Agents
/// routinely pass numbers without quoting (`--argjson x 42`) and kaish
/// evaluates the positional to `Value::Int(42)` → `json::Number`, so we
/// stringify it here.
fn value_as_string(v: &serde_json::Value) -> Option<String> {
    match v {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Number(n) => Some(n.to_string()),
        serde_json::Value::Bool(b) => Some(b.to_string()),
        // Objects / arrays / null aren't sensible for --arg NAMEs and also
        // aren't usually what you want for raw --argjson values — but if a
        // shell expands something exotic, round-trip via serialisation.
        _ => Some(v.to_string()),
    }
}

/// Build an ExecResult from a JqRun, carrying the filter output stream
/// into `.data` so for-loop command substitution can iterate per-value.
///
/// - 0 values → empty text, no `.data`.
/// - 1 value → render normally; promote the value to `.data` so `kaish-last`
///   and single-value iteration are consistent across `-r` and JSON modes.
/// - 2+ values → render normally; set `.data = Json(Array([…]))` so the
///   CommandSubst arm in the kernel hands a JSON array to the for-loop
///   regardless of the `-r` / `-c` rendering flags.
fn build_exec_result(run: JqRun) -> ExecResult {
    use crate::interpreter::json_to_value;
    let JqRun { text, mut values } = run;
    if values.is_empty() {
        return ExecResult::with_output(OutputData::text(text));
    }
    // Single-value output: keep `.data` as the underlying scalar/object so
    // `jq '.name'` continues to expose a non-array value via `kaish-last`.
    if values.len() == 1 {
        if let Some(only) = values.pop() {
            return ExecResult::success_with_data(text, json_to_value(only));
        }
    }
    ExecResult::success_with_data(text, Value::Json(serde_json::Value::Array(values)))
}

/// Validate a jq filter expression without executing it.
/// Returns Ok(()) if valid, Err(message) if invalid.
#[cfg(test)]
fn validate_filter(filter: &str) -> Result<(), String> {
    compile_filter(filter, &[])?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::WriteMode;
    use crate::vfs::{MemoryFs, VfsRouter};
    use std::sync::Arc;

    fn make_ctx() -> ExecContext {
        let mut vfs = VfsRouter::new();
        vfs.mount("/", MemoryFs::new());
        ExecContext::new(Arc::new(vfs))
    }

    #[test]
    fn test_validate_filter_valid() {
        assert!(validate_filter(".name").is_ok());
        assert!(validate_filter(".items[]").is_ok());
        assert!(validate_filter(".[] | select(.active)").is_ok());
        assert!(validate_filter("map(.x + 1)").is_ok());
    }

    #[test]
    fn test_validate_filter_invalid() {
        assert!(validate_filter(".[[[invalid").is_err());
        assert!(validate_filter(".foo | | bar").is_err());
    }

    #[tokio::test]
    async fn test_jq_native_simple_filter() {
        let mut ctx = make_ctx();
        ctx.set_stdin(r#"{"name": "Alice"}"#.to_string());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".name".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "\"Alice\"");
    }

    #[tokio::test]
    async fn test_jq_native_raw_output() {
        let mut ctx = make_ctx();
        ctx.set_stdin(r#"{"name": "Alice"}"#.to_string());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".name".into()));
        args.flags.insert("r".to_string());

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Alice");
    }

    #[tokio::test]
    async fn test_jq_native_array_iteration() {
        let mut ctx = make_ctx();
        ctx.set_stdin(r#"[1, 2, 3]"#.to_string());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".[]".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "1\n2\n3");
    }

    #[tokio::test]
    async fn test_jq_native_invalid_json() {
        let mut ctx = make_ctx();
        ctx.set_stdin("not valid json".to_string());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(!result.ok());
        assert!(result.err.contains("invalid JSON"));
    }

    #[tokio::test]
    async fn test_jq_native_invalid_filter() {
        let mut ctx = make_ctx();
        ctx.set_stdin(r#"{"a": 1}"#.to_string());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".[[[invalid".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(!result.ok());
    }

    #[tokio::test]
    async fn test_jq_native_no_input() {
        let mut ctx = make_ctx();
        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(!result.ok());
        assert!(result.err.contains("no input"));
    }

    #[tokio::test]
    async fn test_jq_native_from_vfs_file() {
        let mut ctx = make_ctx();

        // Write test data to backend
        ctx.backend
            .write(Path::new("/test.json"), br#"{"value": 42}"#, WriteMode::Overwrite)
            .await
            .expect("failed to write test file");

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".value".into()));
        args.named
            .insert("path".to_string(), Value::String("/test.json".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "42");
    }

    // ============================================================================
    // Real-world model output compatibility tests
    // Source: Claude Code session output, 2026-01-25
    // These test standard jq invocation patterns that models generate
    // ============================================================================

    #[tokio::test]
    async fn test_jq_positional_file_argument() {
        // Real-world: jq '.result[]' /tmp/file.json
        let mut ctx = make_ctx();
        ctx.backend
            .write(
                Path::new("/tmp/data.json"),
                br#"{"result": [1, 2, 3]}"#,
                WriteMode::Overwrite,
            )
            .await
            .unwrap();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".result[]".into()));
        args.positional.push(Value::String("/tmp/data.json".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq positional file failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "1\n2\n3");
    }

    #[tokio::test]
    async fn test_jq_select_with_positional_file() {
        // Real-world: jq '[.[] | select(.active)] | length' file.json
        let mut ctx = make_ctx();
        ctx.backend
            .write(
                Path::new("/query.json"),
                br#"[{"id": 1, "active": true}, {"id": 2, "active": false}, {"id": 3, "active": true}]"#,
                WriteMode::Overwrite,
            )
            .await
            .unwrap();

        let mut args = ToolArgs::new();
        args.positional
            .push(Value::String("[.[] | select(.active)] | length".into()));
        args.positional.push(Value::String("/query.json".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq select failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "2");
    }

    #[tokio::test]
    async fn test_jq_type_check_positional_file() {
        // Real-world: jq 'type' /tmp/file.json
        let mut ctx = make_ctx();
        ctx.backend
            .write(Path::new("/check.json"), br#"[1, 2, 3]"#, WriteMode::Overwrite)
            .await
            .unwrap();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("type".into()));
        args.positional.push(Value::String("/check.json".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq type check failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "\"array\"");
    }

    #[tokio::test]
    async fn test_jq_index_access_positional_file() {
        // Real-world: jq '.[0]' /tmp/file.json
        let mut ctx = make_ctx();
        ctx.backend
            .write(
                Path::new("/arr.json"),
                br#"[{"name": "first"}, {"name": "second"}]"#,
                WriteMode::Overwrite,
            )
            .await
            .unwrap();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".[0]".into()));
        args.positional.push(Value::String("/arr.json".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq index failed: {}", result.err);
        assert!(result.text_out().contains("\"name\": \"first\""));
    }

    #[tokio::test]
    async fn test_jq_raw_output_with_positional_file() {
        // Real-world: jq -r '.name' /tmp/file.json
        let mut ctx = make_ctx();
        ctx.backend
            .write(
                Path::new("/person.json"),
                br#"{"name": "Alice"}"#,
                WriteMode::Overwrite,
            )
            .await
            .unwrap();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".name".into()));
        args.positional.push(Value::String("/person.json".into()));
        args.flags.insert("r".to_string());

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq -r failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "Alice"); // No quotes with -r
    }

    #[tokio::test]
    async fn test_jq_stdin_still_works() {
        // Ensure stdin path still works when no file argument
        let mut ctx = make_ctx();
        ctx.set_stdin(r#"{"value": 42}"#.to_string());

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".value".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq stdin failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "42");
    }

    #[tokio::test]
    async fn test_jq_named_path_still_works() {
        // Ensure path= named argument still works
        let mut ctx = make_ctx();
        ctx.backend
            .write(Path::new("/named.json"), br#"{"x": 99}"#, WriteMode::Overwrite)
            .await
            .unwrap();

        let mut args = ToolArgs::new();
        args.positional.push(Value::String(".x".into()));
        args.named
            .insert("path".to_string(), Value::String("/named.json".into()));

        let result = JqNative.execute(args, &mut ctx).await;
        assert!(result.ok(), "jq path= failed: {}", result.err);
        assert_eq!(result.text_out().trim(), "99");
    }
}