kaish-kernel 0.17.1

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
//! Introspection builtins for kaish.
//!
//! These builtins provide visibility into kernel state for context generation.

use async_trait::async_trait;
use clap::{CommandFactory, Parser};

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

// ============================================================================
// kaish-tools — List available tools
// ============================================================================

/// Tools builtin: lists all available tools and their schemas.
pub struct Tools;

/// clap-derived argv layer for kaish-tools.
#[derive(Parser, Debug)]
#[command(name = "kaish-tools", about = "List available tools and their schemas")]
struct ToolsArgs {
    #[command(flatten)]
    global: GlobalFlags,

    /// Tool name to introspect; lists all tools when empty.
    tool: Vec<String>,
}

#[async_trait]
impl Tool for Tools {
    fn name(&self) -> &str {
        "kaish-tools"
    }

    fn schema(&self) -> ToolSchema {
        schema_from_clap(
            &ToolsArgs::command(),
            "kaish-tools",
            "List available tools and their schemas",
            [
                ("List all tools", "kaish-tools"),
                ("Show tool detail", "kaish-tools cat"),
            ],
        )
    }

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

        let tool_name = args.get_string("name", 0);

        if let Some(name) = tool_name {
            format_tool_detail(&ctx.tool_schemas, &name)
        } else {
            format_tool_list(&ctx.tool_schemas)
        }
    }
}

fn format_tool_list(schemas: &[ToolSchema]) -> ExecResult {
    let headers = vec![
        "NAME".to_string(),
        "DESCRIPTION".to_string(),
        "PARAMS".to_string(),
        "OPERATIONS".to_string(),
    ];

    let nodes: Vec<OutputNode> = schemas
        .iter()
        .map(|s| {
            let param_count = s.params.len().to_string();
            // Comma-joined: a table cell is a plain string (spec §F.3 item
            // 5 is additive — the existing `NAME`/`DESCRIPTION`/`PARAMS`
            // keys and their one-string-per-cell shape must not change
            // under a policy engine already reading `kaish-tools --json`).
            // Empty for a tool that gates nothing.
            OutputNode::new(&s.name)
                .with_cells(vec![s.description.clone(), param_count, s.operations.join(",")])
        })
        .collect();

    ExecResult::with_output(OutputData::table(headers, nodes))
}

fn format_tool_detail(schemas: &[ToolSchema], name: &str) -> ExecResult {
    let schema = schemas.iter().find(|s| s.name == name);

    match schema {
        Some(s) => {
            // Every section below calls the same kaish_help::topic renderer
            // `help <tool>` uses, so the two introspection surfaces cannot
            // drift into two spellings of a tool's params, subcommands,
            // examples, operations, or aliases.
            let mut output = format!("{}\n{}\n", s.name, s.description);
            output.push_str(&kaish_help::topic::command_aliases_line(&s.aliases));
            output.push('\n');

            if !s.params.is_empty() {
                output.push_str("Parameters:\n");
                output.push_str(&kaish_help::topic::param_lines(&s.params, "  "));
            }

            if !s.subcommands.is_empty() {
                output.push_str("Subcommands:\n");
                output.push_str(&kaish_help::topic::subcommand_roster(&s.subcommands));
            }

            if !s.examples.is_empty() {
                output.push_str("Examples:\n");
                output.push_str(&kaish_help::topic::examples_section(&s.examples));
            }

            if !s.operations.is_empty() {
                output.push_str(&kaish_help::topic::operations_line(&s.operations));
            }

            ExecResult::with_output(OutputData::text(output))
        }
        None => ExecResult::failure(1, format!("tool not found: {}", name)),
    }
}

// ============================================================================
// kaish-mounts — List VFS mount points
// ============================================================================

/// Mounts builtin: lists all VFS mount points.
pub struct Mounts;

/// clap-derived argv layer for kaish-mounts.
#[derive(Parser, Debug)]
#[command(name = "kaish-mounts", about = "List VFS mount points")]
struct MountsArgs {
    #[command(flatten)]
    global: GlobalFlags,
}

/// Format a byte count in a human-readable short form (right-aligned for columns).
/// Returns "-" for None (disk-backed mount — disk residency is the host's concern).
fn format_resident(bytes: Option<u64>) -> String {
    match bytes {
        None => "-".to_string(),
        Some(b) => {
            const UNITS: &[&str] = &["", "K", "M", "G", "T"];
            let mut size = b as f64;
            let mut idx = 0;
            while size >= 1024.0 && idx < UNITS.len() - 1 {
                size /= 1024.0;
                idx += 1;
            }
            if idx == 0 {
                b.to_string()
            } else if size >= 10.0 {
                format!("{:.0}{}", size, UNITS[idx])
            } else {
                format!("{:.1}{}", size, UNITS[idx])
            }
        }
    }
}

#[async_trait]
impl Tool for Mounts {
    fn name(&self) -> &str {
        "kaish-mounts"
    }

    fn schema(&self) -> ToolSchema {
        schema_from_clap(
            &MountsArgs::command(),
            "kaish-mounts",
            "List VFS mount points",
            [("Show mount points", "kaish-mounts")],
        )
    }

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

        let mounts = ctx.backend.mounts();
        let budget = ctx.vfs_budget.as_ref();

        let headers = vec![
            "PATH".to_string(),
            "MODE".to_string(),
            "RESIDENT".to_string(),
        ];

        let nodes: Vec<OutputNode> = mounts
            .iter()
            .map(|m| {
                let mode = if m.read_only { "ro" } else { "rw" };
                OutputNode::new(m.path.to_string_lossy())
                    .with_cells(vec![mode.to_string(), format_resident(m.resident_bytes)])
            })
            .collect();

        // Build the text-mode budget summary line (appended after the table).
        let budget_summary = budget.map(|b| {
            format!(
                "\nvfs-memory budget: {} used / {} limit / {} remaining",
                format_resident(Some(b.used())),
                format_resident(Some(b.limit())),
                format_resident(Some(b.remaining())),
            )
        });

        // Build the --json override: {mounts: [...], budget: {...}} so the
        // budget object is not a fake mount row. OutputData::with_rich_json
        // makes to_json() return this verbatim.
        let rich = {
            let mount_array: Vec<serde_json::Value> = mounts
                .iter()
                .map(|m| {
                    let mut obj = serde_json::Map::new();
                    obj.insert("path".to_string(), serde_json::Value::String(m.path.to_string_lossy().into_owned()));
                    obj.insert("read_only".to_string(), serde_json::Value::Bool(m.read_only));
                    match m.resident_bytes {
                        Some(n) => obj.insert("resident_bytes".to_string(), serde_json::Value::Number(n.into())),
                        None => obj.insert("resident_bytes".to_string(), serde_json::Value::Null),
                    };
                    serde_json::Value::Object(obj)
                })
                .collect();

            let mut top = serde_json::Map::new();
            top.insert("mounts".to_string(), serde_json::Value::Array(mount_array));
            if let Some(b) = budget {
                let mut bobj = serde_json::Map::new();
                bobj.insert("label".to_string(), serde_json::Value::String(b.label().to_string()));
                bobj.insert("used".to_string(), serde_json::Value::Number(b.used().into()));
                bobj.insert("limit".to_string(), serde_json::Value::Number(b.limit().into()));
                bobj.insert("remaining".to_string(), serde_json::Value::Number(b.remaining().into()));
                top.insert("budget".to_string(), serde_json::Value::Object(bobj));
            }
            serde_json::Value::Object(top)
        };

        let output = OutputData::table(headers, nodes).with_rich_json(rich);

        // For text mode: if there's a budget summary, materialize the table
        // to its canonical string first, then append the summary line.
        // `with_output_and_text` stores both: `out` (text rendering) and
        // `output` (structured, used by --json via rich_json override).
        if let Some(summary) = budget_summary {
            let text = format!("{}{}", output.to_canonical_string(), summary);
            ExecResult::with_output_and_text(output, text)
        } else {
            ExecResult::with_output(output)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::Value;
    use crate::interpreter::{apply_output_format, OutputFormat};
    use crate::tools::{ParamSchema, ToolSchema as TS};
    use crate::vfs::{MemoryFs, VfsRouter};
    use std::sync::Arc;

    fn make_ctx() -> ExecContext {
        let mut vfs = VfsRouter::new();
        vfs.mount("/", MemoryFs::new());
        vfs.mount("/tmp", MemoryFs::new());
        let mut ctx = ExecContext::new(Arc::new(vfs));
        ctx.set_tool_schemas(vec![
            TS::new("echo", "Print arguments"),
            TS::new("cat", "Concatenate files"),
        ]);
        ctx
    }

    // ============================
    // tools tests
    // ============================

    #[tokio::test]
    async fn test_tools_list_plain() {
        let mut ctx = make_ctx();
        let args = ToolArgs::new();

        let result = Tools.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(result.text_out().contains("echo"));
        assert!(result.text_out().contains("cat"));
        // Should have structured OutputData with table headers
        let output = result.output().expect("should have OutputData");
        assert!(output.headers.is_some());
    }

    #[tokio::test]
    async fn test_tools_list_json_via_global_flag() {
        let mut ctx = make_ctx();
        let args = ToolArgs::new();

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

        // Simulate global --json (handled by kernel)
        let result = apply_output_format(result, OutputFormat::Json);
        let data: Vec<serde_json::Value> = serde_json::from_str(&result.text_out()).expect("valid JSON");
        assert_eq!(data.len(), 2);
        assert!(data[0].get("NAME").is_some());
    }

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

        let result = Tools.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(result.text_out().contains("echo"));
        assert!(result.text_out().contains("Print arguments"));
    }

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

        let result = Tools.execute(args, &mut ctx).await;
        assert!(!result.ok());
        assert!(result.err.contains("tool not found"));
    }

    #[tokio::test]
    async fn test_tools_detail_recurses_into_nested_subcommands() {
        // Same two-level grammar as help's regression test: a node
        // (`worktree`) with no params of its own, a leaf (`list`) with one.
        let leaf = TS::new("list", "List the repository's working trees").param(
            ParamSchema::optional("porcelain", "bool", Value::Bool(false), "Machine-readable output"),
        );
        let node = TS::new("worktree", "Work with the repository's working trees").subcommand(leaf);
        let git = TS::new("git", "Git plumbing and porcelain").subcommand(node);

        let mut ctx = make_ctx();
        ctx.set_tool_schemas(vec![git]);
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("git".into()));

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

        assert!(
            text.contains("worktree list — List the repository's working trees"),
            "expected full-path leaf line, got:\n{text}"
        );
        assert!(text.contains("porcelain"), "expected leaf parameter to render, got:\n{text}");
        assert!(
            text.contains("Machine-readable output"),
            "expected leaf parameter description to render, got:\n{text}"
        );

        // Same flat-roster contract as `help <tool>`: exactly two spaces of
        // indent, path and description joined by " — ".
        let roster_start = text.find("Subcommands:\n").expect("Subcommands section") + "Subcommands:\n".len();
        for line in text[roster_start..].lines() {
            if line.is_empty() || line.starts_with("    ") || line.starts_with("Operations:") {
                continue; // param line, or past the roster
            }
            assert!(
                line.starts_with("  ") && !line.starts_with("   "),
                "roster line must start with exactly two spaces: {line:?}"
            );
            assert!(line.contains(""), "roster line must use the ' — ' separator: {line:?}");
        }
    }

    #[tokio::test]
    async fn test_tools_detail_recurses_three_levels() {
        let leaf = TS::new("list", "List sessions in this context").param(ParamSchema::optional(
            "active",
            "bool",
            Value::Bool(false),
            "Only running sessions",
        ));
        let session = TS::new("session", "Session operations").subcommand(leaf);
        let context = TS::new("context", "Context operations").subcommand(session);
        let kj = TS::new("kj", "kaijutsu control").subcommand(context);

        let mut ctx = make_ctx();
        ctx.set_tool_schemas(vec![kj]);
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("kj".into()));

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

        assert!(
            text.contains("context session list — List sessions in this context"),
            "expected three-level full-path leaf line, got:\n{text}"
        );
        assert!(text.contains("active"), "expected leaf parameter to render, got:\n{text}");
    }

    #[tokio::test]
    async fn test_tools_detail_flat_tool_byte_identical() {
        // Control: a tool with no subcommands must render exactly as it did
        // before recursion was added — same header, params, operations.
        let mut cat = TS::new("cat", "Concatenate files")
            .param(ParamSchema::required("path", "string", "File path to read"));
        cat.operations = vec!["fs.read".to_string()];

        let mut ctx = make_ctx();
        ctx.set_tool_schemas(vec![cat]);
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("cat".into()));

        let result = Tools.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert_eq!(
            result.text_out(),
            "cat\nConcatenate files\n\nParameters:\n  path : string (required)\n    File path to read\nOperations: fs.read\n"
        );
    }

    #[tokio::test]
    async fn test_tools_detail_renders_examples() {
        // `help <tool>` already named a tool's examples; `kaish-tools
        // <name>` silently dropped them.
        let mut ctx = make_ctx();
        let echo = TS::new("echo", "Print arguments")
            .example("Print a literal string", "echo hello");
        ctx.set_tool_schemas(vec![echo]);
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("echo".into()));

        let result = Tools.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        assert!(
            text.contains("Print a literal string") && text.contains("echo hello"),
            "expected the example to render, got:\n{text}"
        );
    }

    #[tokio::test]
    async fn test_tools_detail_renders_parameter_aliases() {
        // `help <tool>`'s push_params names a flag's aliases (`-n` for
        // `--max-count`); `kaish-tools <name>`'s inline loop dropped them.
        let mut ctx = make_ctx();
        let head = TS::new("head", "Print the first lines")
            .param(ParamSchema::optional("lines", "int", Value::Int(10), "Line count").with_aliases(["-n"]));
        ctx.set_tool_schemas(vec![head]);
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("head".into()));

        let result = Tools.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        assert!(
            text.contains("(also: -n)"),
            "expected the parameter's alias to render, got:\n{text}"
        );
    }

    #[tokio::test]
    async fn test_tools_detail_renders_command_aliases() {
        let mut ctx = make_ctx();
        let list = TS::new("list", "List sessions").with_command_aliases(["ls"]);
        ctx.set_tool_schemas(vec![list]);
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("list".into()));

        let result = Tools.execute(args, &mut ctx).await;
        assert!(result.ok());
        let text = result.text_out();
        assert!(
            text.contains("Aliases: ls"),
            "expected the command alias to render, got:\n{text}"
        );
    }

    // ============================
    // mounts tests
    // ============================

    #[tokio::test]
    async fn test_mounts_list_plain() {
        let mut ctx = make_ctx();
        let args = ToolArgs::new();

        let result = Mounts.execute(args, &mut ctx).await;
        assert!(result.ok());
        assert!(result.text_out().contains("/"));
        assert!(result.text_out().contains("/tmp"));
        assert!(result.text_out().contains("rw"));
    }

    #[tokio::test]
    async fn test_mounts_list_json_via_global_flag() {
        let mut ctx = make_ctx();
        let args = ToolArgs::new();

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

        // Simulate global --json (handled by kernel).
        // Shape is now {mounts: [{path, read_only, resident_bytes}, ...]}
        // (and optionally a "budget" key when a budget is set — not present here).
        let result = apply_output_format(result, OutputFormat::Json);
        let top: serde_json::Value =
            serde_json::from_str(&result.text_out()).expect("valid JSON");

        let data = top.get("mounts").expect("must have 'mounts' key");
        assert!(data.is_array(), "'mounts' must be an array");
        let data = data.as_array().unwrap();
        assert!(!data.is_empty());

        let paths: Vec<&str> = data
            .iter()
            .filter_map(|v| v.get("path").and_then(|p| p.as_str()))
            .collect();
        assert!(paths.contains(&"/"));
        assert!(paths.contains(&"/tmp"));

        // No budget key for an unbudgeted context.
        assert!(top.get("budget").is_none(), "no budget key for unbudgeted ctx");
    }
}