kaish-kernel 0.16.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
//! tree — Display directory structure.

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

use crate::interpreter::{EntryType, ExecResult, OutputData, OutputNode};
use crate::tools::builtin::get_path_string;
use crate::tools::{schema_from_clap, ExecContext, ToolCtx, GlobalFlags, Tool, ToolArgs, ToolSchema};

/// Tree tool: display directory structure.
pub struct Tree;

/// clap-derived argv layer for tree.
#[derive(Parser, Debug)]
#[command(name = "tree", about = "Display directory structure")]
struct TreeArgs {
    /// Maximum depth to display.
    #[arg(short = 'L', long = "level")]
    level: Option<i64>,

    /// Traditional tree format with box-drawing.
    #[arg(long = "traditional")]
    traditional: bool,

    /// Flat indent format.
    #[arg(long = "flat")]
    flat: bool,

    /// Show only files, no directory entries.
    #[arg(short = 'f', long = "files-only", visible_alias = "files_only")]
    files_only: bool,

    /// Show hidden files.
    #[arg(short = 'a', long = "all")]
    all: bool,

    /// Include ignored directories.
    #[arg(long = "no-ignore", visible_alias = "no_ignore")]
    no_ignore: bool,

    #[command(flatten)]
    global: GlobalFlags,

    /// Starting directory; defaults to the current directory.
    paths: Vec<String>,
}

/// Node in the tree structure.
#[derive(Debug, Default)]
struct TreeNode {
    children: BTreeMap<String, TreeNode>,
    is_dir: bool,
    /// Set when the walk could not open this directory. GNU `tree`'s
    /// convention is to mark the node inline rather than leave it
    /// childless — childless is indistinguishable from a genuinely empty
    /// directory, so silence here would misrepresent, not just omit.
    has_error: bool,
}

impl TreeNode {
    fn insert(&mut self, path: &[&str], is_dir: bool) {
        if path.is_empty() {
            return;
        }

        let entry = self
            .children
            .entry(path[0].to_string())
            .or_default();

        if path.len() == 1 {
            entry.is_dir = is_dir;
        } else {
            entry.is_dir = true; // Intermediate nodes are directories
            entry.insert(&path[1..], is_dir);
        }
    }

    /// Mark the node at `path` as a directory the walk failed to open. The
    /// node always already exists (it was inserted when discovered as a
    /// directory entry of its parent); if it somehow doesn't, this is a
    /// silent no-op rather than a panic on a walk-order quirk.
    fn mark_error(&mut self, path: &[&str]) {
        if path.is_empty() {
            self.has_error = true;
            return;
        }
        if let Some(entry) = self.children.get_mut(path[0]) {
            if path.len() == 1 {
                entry.has_error = true;
            } else {
                entry.mark_error(&path[1..]);
            }
        }
    }

    fn format_traditional(&self, prefix: &str, _is_last: bool, output: &mut String) {
        let mut children: Vec<_> = self.children.iter().collect();
        children.sort_by_key(|(name, _)| *name);

        for (i, (name, node)) in children.iter().enumerate() {
            let is_last_child = i == children.len() - 1;
            let connector = if is_last_child { "└── " } else { "├── " };
            let name_suffix = if node.is_dir && node.children.is_empty() {
                "/"
            } else {
                ""
            };

            output.push_str(prefix);
            output.push_str(connector);
            output.push_str(name);
            output.push_str(name_suffix);
            if node.has_error {
                output.push_str(" [error opening dir]");
            }
            output.push('\n');

            if !node.children.is_empty() {
                let new_prefix = if is_last_child {
                    format!("{}    ", prefix)
                } else {
                    format!("{}", prefix)
                };
                node.format_traditional(&new_prefix, is_last_child, output);
            }
        }
    }

    fn format_flat(&self, indent: usize, output: &mut String) {
        let mut children: Vec<_> = self.children.iter().collect();
        children.sort_by_key(|(name, _)| *name);

        for (name, node) in children {
            let spaces = "  ".repeat(indent);
            let name_suffix = if node.is_dir { "/" } else { "" };

            output.push_str(&spaces);
            output.push_str(name);
            output.push_str(name_suffix);
            if node.has_error {
                output.push_str(" [error opening dir]");
            }
            output.push('\n');

            if !node.children.is_empty() {
                node.format_flat(indent + 1, output);
            }
        }
    }

    /// Convert TreeNode to OutputNode for the structured output model.
    ///
    /// An unreadable directory's marker is embedded directly in the node
    /// `name` (rather than a side channel) so it survives unchanged through
    /// both the default compact-notation text render
    /// (`OutputData::to_canonical_string`, which reads `node.name`) and
    /// `--json` (`node_to_json`, which uses `node.name` as the object key).
    fn to_output_node(&self, name: &str) -> OutputNode {
        let entry_type = if self.is_dir {
            EntryType::Directory
        } else {
            EntryType::File
        };

        let children: Vec<OutputNode> = self.children
            .iter()
            .map(|(child_name, child_node)| child_node.to_output_node(child_name))
            .collect();

        let display_name = if self.has_error {
            format!("{name} [error opening dir]")
        } else {
            name.to_string()
        };

        OutputNode::new(display_name)
            .with_entry_type(entry_type)
            .with_children(children)
    }
}

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

    fn schema(&self) -> ToolSchema {
        schema_from_clap(
            &TreeArgs::command(),
            "tree",
            "Display directory structure",
            [
                ("Compact notation (default)", "tree src/"),
                ("Traditional tree", "tree --traditional src/"),
                ("Flat indent", "tree --flat src/"),
                ("JSON output", "tree --json src/"),
                ("Limited depth", "tree -L 2 src/"),
            ],
        )
    }

    async fn execute(&self, mut 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");
        };
        args.flagify_bool_named(&self.schema());

        let argv = match args.to_argv() {
            Ok(v) => v,
            Err(e) => return ExecResult::failure(2, format!("tree: {e}")),
        };
        let parsed = match TreeArgs::try_parse_from(
            std::iter::once("tree".to_string()).chain(argv),
        ) {
            Ok(p) => p,
            Err(e) => return ExecResult::failure(2, format!("tree: {e}")),
        };
        parsed.global.apply(ctx);

        // A binary `path` operand goes loud rather than silently defaulting to
        // "." (the "no operand given" case).
        let path = match get_path_string(&args, "path", 0) {
            Ok(p) => p.unwrap_or_else(|| ".".to_string()),
            Err(e) => return ExecResult::failure(1, format!("tree: {e}")),
        };

        let resolved = ctx.resolve_path(&path).to_string_lossy().to_string();

        // Fail loudly when the start path does not exist — silent success with
        // a bare root node is confusing and masks typos.
        if !ctx.backend.exists(Path::new(&resolved)).await {
            return ExecResult::failure(1, format!("tree: {}: No such file or directory", path));
        }

        // Parse options off the clap struct. A non-numeric `-L`/`--level` was
        // already a loud clap error; a negative one is refused here rather
        // than wrapping to "effectively unlimited".
        let max_depth: Option<usize> = match parsed.level {
            Some(l) if l < 0 => {
                return ExecResult::failure(
                    2,
                    format!("tree: invalid --level {l}: must be >= 0"),
                )
            }
            other => other.map(|l| l as usize),
        };

        let traditional = parsed.traditional;
        let flat = parsed.flat;
        let files_only = parsed.files_only;
        let show_hidden = parsed.all;
        let no_ignore = parsed.no_ignore;

        // Build tree by walking directory
        let mut tree = TreeNode::default();

        // Set up ignore filter from config (unless --no-ignore)
        let ignore_filter = if no_ignore {
            None
        } else {
            ctx.build_ignore_filter(&ctx.resolve_path(&resolved)).await
        };

        // Walk directory using stack-based iteration
        let mut stack: Vec<(String, usize)> = vec![(resolved.clone(), 0usize)];
        // Every directory the walk could not open: reported on stderr and
        // folded into a nonzero exit once the walk finishes, matching
        // ls -R's accumulate-and-continue handling of the same failure. A
        // directory the ignore filter already skipped (below) never reaches
        // this call, so a gitignored-and-unreadable directory is not an
        // error.
        let mut errors: Vec<String> = Vec::new();
        // Set when the root itself can't be opened — it has no TreeNode of
        // its own to mark_error on (the root is implicit; `tree.children`
        // holds only what was discovered underneath it), so its marker is
        // applied directly to the top-level output below instead.
        let mut root_has_error = false;

        while let Some((dir, depth)) = stack.pop() {
            // Check max depth
            if let Some(max) = max_depth
                && depth >= max {
                    continue;
                }

            // List directory contents
            let entries = match ctx.backend.list(Path::new(&dir)).await {
                Ok(entries) => entries,
                Err(e) => {
                    let dir_trimmed = dir.trim_end_matches('/');
                    let relative = dir_trimmed
                        .strip_prefix(&resolved)
                        .unwrap_or(dir_trimmed)
                        .trim_start_matches('/');
                    if relative.is_empty() {
                        root_has_error = true;
                        errors.push(format!("tree: {}: {}", path, e));
                    } else {
                        let parts: Vec<&str> = relative.split('/').collect();
                        tree.mark_error(&parts);
                        errors.push(format!(
                            "tree: {}/{}: {}",
                            path.trim_end_matches('/'),
                            relative,
                            e
                        ));
                    }
                    continue;
                }
            };

            for entry in entries {
                // Skip hidden files unless -a
                if !show_hidden && entry.name.starts_with('.') {
                    continue;
                }

                // Check ignore filter
                if let Some(ref filter) = ignore_filter
                    && filter.is_name_ignored(&entry.name, entry.is_dir()) {
                        continue;
                    }

                let dir_str = dir.trim_end_matches('/');
                let full_path = format!("{}/{}", dir_str, entry.name);

                // Calculate relative path from root
                let relative = full_path
                    .strip_prefix(&resolved)
                    .unwrap_or(&full_path)
                    .trim_start_matches('/');

                if entry.is_dir() {
                    stack.push((full_path.clone(), depth + 1));

                    // Add directory to tree unless files_only
                    if !files_only {
                        let parts: Vec<&str> = relative.split('/').collect();
                        tree.insert(&parts, true);
                    }
                } else {
                    let parts: Vec<&str> = relative.split('/').collect();
                    tree.insert(&parts, false);
                }
            }
        }

        // Get root name for formatting
        let root_name = Path::new(&path)
            .file_name()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_else(|| ".".to_string());
        let root_marker = if root_has_error { " [error opening dir]" } else { "" };

        // Handle explicit text format requests
        if flat {
            let mut output = format!("{}/{}\n", root_name, root_marker);
            tree.format_flat(1, &mut output);
            return apply_walk_errors(
                ExecResult::with_output(OutputData::text(output.trim_end())),
                &errors,
            );
        }

        if traditional {
            let mut output = format!("{}/{}\n", root_name, root_marker);
            tree.format_traditional("", false, &mut output);
            return apply_walk_errors(
                ExecResult::with_output(OutputData::text(output.trim_end())),
                &errors,
            );
        }

        // Build structured OutputData with tree structure
        let root_node = OutputNode::new(format!("{}{}", root_name, root_marker))
            .with_entry_type(EntryType::Directory)
            .with_children(
                tree.children
                    .iter()
                    .map(|(name, node)| node.to_output_node(name))
                    .collect()
            );

        apply_walk_errors(
            ExecResult::with_output(OutputData::nodes(vec![root_node])),
            &errors,
        )
    }
}

/// Fold accumulated per-directory listing failures into a result: stderr
/// gets every failure (the walk continues past each one rather than
/// stopping at the first), and the exit code moves to 1 so an agent reading
/// only the exit code doesn't mistake a partial walk for a complete one.
fn apply_walk_errors(mut result: ExecResult, errors: &[String]) -> ExecResult {
    if !errors.is_empty() {
        result.err = ExecResult::terminate_diagnostic(errors.join("\n"));
        result = result.with_code(1);
    }
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::Value;
    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.mkdir(Path::new("src")).await.unwrap();
        mem.mkdir(Path::new("src/lib")).await.unwrap();

        mem.write(Path::new("src/main.rs"), b"fn main() {}")
            .await
            .unwrap();
        mem.write(Path::new("src/lib.rs"), b"pub mod lib;")
            .await
            .unwrap();
        mem.write(Path::new("src/lib/utils.rs"), b"pub fn util() {}")
            .await
            .unwrap();
        mem.write(Path::new("README.md"), b"# Test").await.unwrap();

        vfs.mount("/", mem);
        ExecContext::new(Arc::new(vfs))
    }

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

        let result = Tree.execute(args, &mut ctx).await;
        assert!(result.ok());
        // Default format now returns structured OutputData
        // Canonical output uses brace notation for nested children
        assert!(result.text_out().contains("src"));
        // Should have structured output
        assert!(result.has_output());
    }

    #[tokio::test]
    async fn test_tree_traditional() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/src".into()));
        args.flags.insert("traditional".to_string());

        let result = Tree.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(result.text_out().contains("main.rs"));
        assert!(result.text_out().contains("lib.rs"));
        // Check for lib directory
        assert!(result.text_out().contains("lib"));
        // Traditional format uses box-drawing chars
        assert!(result.text_out().contains("") || result.text_out().contains(""));
    }

    #[tokio::test]
    async fn test_tree_flat() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/src".into()));
        args.flags.insert("flat".to_string());

        let result = Tree.execute(args, &mut ctx).await;
        assert!(result.ok());
        // Flat format uses indentation
        assert!(result.text_out().contains("src/"));
        assert!(result.text_out().contains("main.rs"));
    }

    #[tokio::test]
    async fn test_tree_json_via_global_flag() {
        use crate::interpreter::{apply_output_format, OutputFormat};

        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/src".into()));

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

        // Simulate global --json (handled by kernel)
        let result = apply_output_format(result, OutputFormat::Json);
        assert!(result.text_out().starts_with('{'));
        assert!(result.text_out().ends_with('}'));
    }

    #[tokio::test]
    async fn test_tree_depth() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/src".into()));
        args.named.insert("level".to_string(), Value::Int(1));

        let result = Tree.execute(args, &mut ctx).await;
        assert!(result.ok());
        // Should show immediate children but not nested
        assert!(result.text_out().contains("lib/") || result.text_out().contains("lib"));
        // utils.rs is at depth 2, should not appear
        // (actually depends on how we count - lib/ is at depth 1, utils.rs at depth 2)
    }

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

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

        // Default tree (no flags) should return OutputData with nested structure
        match result.output() {
            Some(output) => {
                assert!(!output.root.is_empty());
                // Root node should be "src"
                assert_eq!(output.root[0].name, "src");
                // Should have children (the tree content)
                assert!(!output.root[0].children.is_empty());
            }
            None => panic!("Expected OutputData for default tree output"),
        }
    }

    #[tokio::test]
    async fn test_tree_explicit_flag_returns_text() {
        let mut ctx = make_ctx().await;
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("/src".into()));
        args.flags.insert("traditional".to_string());

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

        // Explicit format flags should return plain text output
        // (output is still Some but it's simple text, not a tree structure)
        assert!(result.text_out().contains("") || result.text_out().contains(""));
    }
}