kaish-kernel 0.8.2

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
//! cut — Remove sections from each line of files.

use async_trait::async_trait;
use clap::{CommandFactory, Parser};
use std::path::Path;

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

/// Cut tool: select portions of each line.
pub struct Cut;

/// clap-derived argv layer for cut. See docs/clap-migration.md.
#[derive(Parser, Debug)]
#[command(name = "cut", about = "Remove sections from each line")]
struct CutArgs {
    /// Field delimiter (-d)
    #[arg(short = 'd', long = "delimiter")]
    delimiter: Option<String>,

    /// Select fields by number, e.g. '1,3' or '1-3' (-f)
    #[arg(short = 'f', long = "fields")]
    fields: Option<String>,

    /// Select characters by position (-c)
    #[arg(short = 'c', long = "characters")]
    characters: Option<String>,

    #[command(flatten)]
    global: GlobalFlags,

    /// Files to read; reads stdin when none are given.
    paths: Vec<String>,
}

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

    fn schema(&self) -> ToolSchema {
        schema_from_clap(
            &CutArgs::command(),
            "cut",
            "Remove sections from each line",
            [
                ("Extract first field (CSV)", "cut -d ',' -f 1 data.csv"),
                ("Extract fields 1 and 3", "cut -d ':' -f 1,3 /etc/passwd"),
                ("Extract characters 1-10", "cut -c 1-10 file.txt"),
            ],
        )
    }

    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 CutArgs::try_parse_from(
            std::iter::once("cut".to_string()).chain(args.to_argv()),
        ) {
            Ok(p) => p,
            Err(e) => return ExecResult::failure(2, format!("cut: {e}")),
        };
        parsed.global.apply(ctx);

        // POSIX: cut accepts multiple files and concatenates their content.
        // When no file is given, read stdin.
        let input = if args.positional.is_empty() {
            ctx.read_stdin_to_string().await.unwrap_or_default()
        } else {
            let mut acc = String::new();
            for value in &args.positional {
                let path = crate::interpreter::value_to_string(value);
                let resolved = ctx.resolve_path(&path);
                match ctx.backend.read(Path::new(&resolved), None).await {
                    Ok(data) => match String::from_utf8(data) {
                        Ok(s) => acc.push_str(&s),
                        Err(_) => return ExecResult::failure(1, format!("cut: {}: invalid UTF-8", path)),
                    },
                    Err(e) => return ExecResult::failure(1, format!("cut: {}: {}", path, e)),
                }
            }
            acc
        };

        let delimiter = parsed.delimiter.clone()
            .or_else(|| args.get_string("delimiter", usize::MAX))
            .or_else(|| args.get_string("d", usize::MAX))
            .unwrap_or_else(|| "\t".to_string());

        let fields = parsed.fields.clone()
            .or_else(|| args.get_string("fields", usize::MAX))
            .or_else(|| args.get_string("f", usize::MAX));

        let characters = parsed.characters.clone()
            .or_else(|| args.get_string("characters", usize::MAX))
            .or_else(|| args.get_string("c", usize::MAX));

        if delimiter.chars().count() > 1 {
            return ExecResult::failure(1, "cut: delimiter must be a single character");
        }

        if fields.is_none() && characters.is_none() {
            return ExecResult::failure(1, "cut: must specify either -f or -c");
        }

        let mut output = Vec::new();

        for line in input.lines() {
            if let Some(ref char_spec) = characters {
                // Character mode
                let chars: Vec<char> = line.chars().collect();
                let selected = select_indices(char_spec, chars.len());
                let result: String = selected
                    .iter()
                    .filter_map(|&i| chars.get(i).copied())
                    .collect();
                output.push(result);
            } else if let Some(ref field_spec) = fields {
                // Field mode
                let delim_char = delimiter.chars().next().unwrap_or('\t');
                let parts: Vec<&str> = line.split(delim_char).collect();
                let selected = select_indices(field_spec, parts.len());
                let result: Vec<&str> = selected
                    .iter()
                    .filter_map(|&i| parts.get(i).copied())
                    .collect();
                output.push(result.join(&delimiter));
            }
        }

        if output.is_empty() {
            ExecResult::success("")
        } else {
            // Populate .data so `for v in $(cut …)` iterates per output line.
            // cut reads input via `.lines()` so each line is newline-clean —
            // safe to treat as a true N-item list without word-splitting risk.
            let text = format!("{}\n", output.join("\n"));
            let data = Value::Json(serde_json::Value::Array(
                output.into_iter().map(serde_json::Value::String).collect(),
            ));
            ExecResult::success_with_data(text, data)
        }
    }
}

/// Parse a field/character specification like "1,3,5" or "1-3" or "2-"
/// Returns 0-indexed positions.
fn select_indices(spec: &str, max_len: usize) -> Vec<usize> {
    let mut indices = Vec::new();

    for part in spec.split(',') {
        let part = part.trim();
        if part.contains('-') {
            // Range specification
            let parts: Vec<&str> = part.split('-').collect();
            let start = parts
                .first()
                .and_then(|s| s.parse::<usize>().ok())
                .unwrap_or(1);
            let end = parts
                .get(1)
                .and_then(|s| {
                    if s.is_empty() {
                        Some(max_len)
                    } else {
                        s.parse::<usize>().ok()
                    }
                })
                .unwrap_or(max_len);

            for i in start..=end {
                if i > 0 && i <= max_len {
                    indices.push(i - 1); // Convert to 0-indexed
                }
            }
        } else if let Ok(n) = part.parse::<usize>()
            && n > 0 && n <= max_len {
                indices.push(n - 1); // Convert to 0-indexed
            }
    }

    indices
}

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

    async fn make_ctx() -> ExecContext {
        let mut vfs = VfsRouter::new();
        let mem = MemoryFs::new();
        mem.write(Path::new("csv.txt"), b"alice,25,engineer\nbob,30,manager")
            .await
            .unwrap();
        mem.write(Path::new("tsv.txt"), b"one\ttwo\tthree\nfour\tfive\tsix")
            .await
            .unwrap();
        mem.write(Path::new("text.txt"), b"hello world\nfoo bar")
            .await
            .unwrap();
        vfs.mount("/", mem);
        ExecContext::new(Arc::new(vfs))
    }

    #[tokio::test]
    async fn test_cut_single_field() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/csv.txt".into()));
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("1".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["alice", "bob"]);
    }

    #[tokio::test]
    async fn test_cut_multiple_fields() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/csv.txt".into()));
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("1,3".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["alice,engineer", "bob,manager"]);
    }

    #[tokio::test]
    async fn test_cut_field_range() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/csv.txt".into()));
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("2-3".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["25,engineer", "30,manager"]);
    }

    #[tokio::test]
    async fn test_cut_tab_delimiter() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/tsv.txt".into()));
        args.named
            .insert("fields".to_string(), Value::String("2".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["two", "five"]);
    }

    #[tokio::test]
    async fn test_cut_characters() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/text.txt".into()));
        args.named
            .insert("characters".to_string(), Value::String("1-5".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["hello", "foo b"]);
    }

    #[tokio::test]
    async fn test_cut_stdin() {
        let mut ctx = make_ctx().await;
        ctx.set_stdin("a:b:c\n1:2:3\n".to_string());

        let mut args = ToolArgs::new();
        args.named
            .insert("delimiter".to_string(), Value::String(":".into()));
        args.named
            .insert("fields".to_string(), Value::String("2".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["b", "2"]);
    }

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

        let result = Cut.execute(args, &mut ctx).await;
        assert!(!result.ok());
        assert!(result.err.contains("-f or -c"));
    }

    #[test]
    fn test_select_indices() {
        assert_eq!(select_indices("1", 5), vec![0]);
        assert_eq!(select_indices("1,3", 5), vec![0, 2]);
        assert_eq!(select_indices("1-3", 5), vec![0, 1, 2]);
        assert_eq!(select_indices("2-", 5), vec![1, 2, 3, 4]);
        assert_eq!(select_indices("1,3-5", 5), vec![0, 2, 3, 4]);
    }

    // --- Additional tests for edge cases and common patterns ---

    #[tokio::test]
    async fn test_cut_open_range_from_start() {
        // cut -f -3 (fields 1-3)
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/csv.txt".into()));
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("-2".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["alice,25", "bob,30"]);
    }

    #[tokio::test]
    async fn test_cut_out_of_range_field() {
        // Requesting field beyond available columns should return empty for that field
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/csv.txt".into()));
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("5".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        // Fields beyond range are silently ignored
        assert!(result.text_out().trim().is_empty() || result.text_out().lines().all(|l| l.is_empty()));
    }

    #[tokio::test]
    async fn test_cut_unicode_characters() {
        // Unicode character cutting
        let mut ctx = make_ctx().await;
        ctx.set_stdin("日本語テスト\n".to_string());

        let mut args = ToolArgs::new();
        args.named
            .insert("characters".to_string(), Value::String("1-3".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "日本語");
    }

    #[tokio::test]
    async fn test_cut_empty_input() {
        let mut ctx = make_ctx().await;
        ctx.set_stdin("".to_string());

        let mut args = ToolArgs::new();
        args.named
            .insert("fields".to_string(), Value::String("1".into()));

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

    #[tokio::test]
    async fn test_cut_single_column_csv() {
        let mut ctx = make_ctx().await;
        ctx.set_stdin("value1\nvalue2\nvalue3\n".to_string());

        let mut args = ToolArgs::new();
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("1".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["value1", "value2", "value3"]);
    }

    #[tokio::test]
    async fn test_cut_mixed_ranges_and_single() {
        // Common pattern: cut -f 1,3-5,7
        let mut ctx = make_ctx().await;
        ctx.set_stdin("a,b,c,d,e,f,g,h\n".to_string());

        let mut args = ToolArgs::new();
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("1,3-5,7".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert_eq!(result.text_out().trim(), "a,c,d,e,g");
    }

    #[tokio::test]
    async fn test_cut_multi_char_delimiter_error() {
        // Bug L: multi-character delimiter should error, not silently truncate
        let mut ctx = make_ctx().await;
        ctx.set_stdin("a::b::c\n".to_string());

        let mut args = ToolArgs::new();
        args.named
            .insert("delimiter".to_string(), Value::String("::".into()));
        args.named
            .insert("fields".to_string(), Value::String("1".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(!result.ok());
        assert!(result.err.contains("single character"));
    }

    /// POSIX: `cut FILE1 FILE2` reads from both files in order and applies
    /// the same field/character selection to the concatenated input.
    #[tokio::test]
    async fn test_cut_multiple_files_concatenate() {
        let mut vfs = VfsRouter::new();
        let mem = MemoryFs::new();
        mem.write(Path::new("a.csv"), b"alice,25\nbob,30\n").await.unwrap();
        mem.write(Path::new("b.csv"), b"carol,40\n").await.unwrap();
        vfs.mount("/", mem);
        let mut ctx = ExecContext::new(Arc::new(vfs));

        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/a.csv".into()));
        args.positional.push(Value::String("/b.csv".into()));
        args.named
            .insert("delimiter".to_string(), Value::String(",".into()));
        args.named
            .insert("fields".to_string(), Value::String("1".into()));

        let result = Cut.execute(args, &mut ctx).await;
        assert!(result.ok(), "cut multi-file should succeed: {}", result.err);
        let text = result.text_out();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines, vec!["alice", "bob", "carol"], "expected concat of both files");
    }
}