leviath-cli 0.3.8

Command-line interface for Leviath agent framework
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
//! `lev pack` - Bundle an agent project for distribution.

use clap::Args;
use leviath_package::AgentBundler;
use std::path::{Path, PathBuf};

use leviath_core::manifest::parse_manifest;

/// Arguments for `lev pack`.
#[derive(Args)]
pub struct PackArgs {
    /// Path to agent project (default: current directory)
    #[arg(value_name = "PATH")]
    pub path: Option<String>,

    /// Output file path (default: {name}-{version}.leviath-bundle)
    #[arg(short, long)]
    pub output: Option<String>,
}

/// Run `lev pack`: build a distributable bundle from an agent directory.
pub async fn execute(args: PackArgs) -> anyhow::Result<()> {
    execute_with_bundle(args, &|dir| AgentBundler::new().bundle(dir)).await
}

/// [`execute`] with an injectable bundling operation.
///
/// The `bundle` closure is a trait object so its failure arm (`bundler.bundle`
/// erroring) can be exercised on every platform. Reaching that arm through the
/// real bundler requires the directory walk itself to fail, which is only
/// possible OS-agnostically via injection inside `leviath-package`; here the
/// simpler seam is to inject the whole bundle step. Production always passes
/// the real `AgentBundler`.
async fn execute_with_bundle(
    args: PackArgs,
    bundle: &dyn Fn(&Path) -> anyhow::Result<Vec<u8>>,
) -> anyhow::Result<()> {
    let path = args.path.unwrap_or_else(|| ".".to_string());
    let project_path = Path::new(&path);

    tracing::info!("Packing agent");

    // Find and parse agent.leviath to get name + version
    let manifest_path = find_manifest(project_path)?;
    let manifest_content = std::fs::read_to_string(&manifest_path)
        .map_err(|e| anyhow::anyhow!("Failed to read manifest: {}", e))?;
    let blueprint = parse_manifest(&manifest_content)?;

    println!("Packing agent: {} v{}", blueprint.name, blueprint.version);

    // Determine output path
    let output_path =
        determine_output_path(args.output.as_deref(), &blueprint.name, &blueprint.version);

    // Bundle the project
    let project_dir = manifest_path.parent().unwrap_or(Path::new("."));

    let data = bundle(project_dir)?;
    let bundle_size = data.len();

    std::fs::write(&output_path, &data).map_err(|e| {
        anyhow::anyhow!(
            "Failed to write bundle to '{}': {}",
            output_path.display(),
            e
        )
    })?;

    // Print summary
    println!("Bundle written to: {}", output_path.display());
    println!("Bundle size: {}", format_size(bundle_size));

    // List contents summary
    println!("\nContents:");
    let file_count = count_files(project_dir);
    println!("  {} files bundled", file_count);
    println!("  Manifest: agent.leviath");

    let scripts_dir = project_dir.join("scripts");
    if scripts_dir.exists() {
        let script_count = count_files(&scripts_dir);
        println!("  Scripts: {} files", script_count);
    }

    let tests_dir = project_dir.join("tests");
    if tests_dir.exists() {
        let test_count = count_files(&tests_dir);
        println!("  Tests: {} files", test_count);
    }

    println!("\nDone! Install with: lev add {}", output_path.display());

    Ok(())
}

/// Resolves the bundle output path.
fn determine_output_path(output: Option<&str>, name: &str, version: &str) -> PathBuf {
    match output {
        Some(out) => PathBuf::from(out),
        None => PathBuf::from(format!("{}-{}.leviath-bundle", name, version)),
    }
}

fn find_manifest(project_path: &Path) -> anyhow::Result<PathBuf> {
    find_manifest_with_cwd(project_path, &std::env::current_dir().unwrap_or_default())
}

fn find_manifest_with_cwd(project_path: &Path, cwd: &Path) -> anyhow::Result<PathBuf> {
    if project_path.is_file()
        && project_path.file_name() == Some(std::ffi::OsStr::new("agent.leviath"))
    {
        return Ok(project_path.to_path_buf());
    }

    if project_path.is_dir() {
        let manifest = project_path.join("agent.leviath");
        if manifest.exists() {
            return Ok(manifest);
        }
    }

    let current_manifest = cwd.join("agent.leviath");
    if current_manifest.exists() {
        return Ok(current_manifest);
    }

    anyhow::bail!(
        "Could not find agent.leviath in {} or current directory",
        project_path.display()
    )
}

fn format_size(bytes: usize) -> String {
    if bytes < 1024 {
        format!("{} B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
    }
}

/// The real directory reader used in production. A named function (rather than
/// an inline closure) so tests that need to pass a reader which their code path
/// never actually invokes don't introduce an uncovered closure-body region.
fn real_read_dir(p: &Path) -> std::io::Result<std::fs::ReadDir> {
    std::fs::read_dir(p)
}

/// Count files in `dir` recursively; returns 0 on I/O errors.
fn count_files(dir: &Path) -> usize {
    count_files_with(dir, &real_read_dir)
}

/// [`count_files`] with an injectable directory reader so the "read_dir failed
/// on an existing directory -> return the count so far" arm can be exercised
/// deterministically on every platform. That arm is otherwise only reachable
/// via a `chmod 0o000` directory (Unix-only). A trait object (not `impl Fn`)
/// keeps every caller sharing one monomorphization. Production always passes
/// `std::fs::read_dir`.
fn count_files_with(
    dir: &Path,
    read_dir: &dyn Fn(&Path) -> std::io::Result<std::fs::ReadDir>,
) -> usize {
    let mut count = 0;
    if dir.is_dir()
        && let Ok(entries) = read_dir(dir)
    {
        for entry in entries.filter_map(|e| e.ok()) {
            count += count_path(&entry.path(), read_dir);
        }
    }
    count
}

/// Count the files contributed by a single walked path: 1 for a regular file,
/// the recursive count for a directory, and 0 for anything else (a broken
/// symlink, a special file, or a path that vanished mid-walk). Split out so the
/// "neither a file nor a directory" arm is testable OS-agnostically (a
/// nonexistent path is neither), rather than only via a Unix broken symlink.
fn count_path(path: &Path, read_dir: &dyn Fn(&Path) -> std::io::Result<std::fs::ReadDir>) -> usize {
    if path.is_file() {
        1
    } else if path.is_dir() {
        count_files_with(path, read_dir)
    } else {
        0
    }
}

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

    // ─── tracing subscriber ────────────────────────────────────────────────
    //
    // Without a registered subscriber, `tracing::info!`'s macro expansion
    // short-circuits field evaluation before the "is level enabled" check
    // runs, so field-expression lines show as uncovered even though the
    // surrounding branch executes. Each test below calls `with_tracing(|| {})`
    // once as a bare statement (rather than wrapping the whole test body) to
    // install the shared `AlwaysOnSubscriber` (see `crate::test_support`) as
    // the process-wide default before the rest of the test runs.

    // ─── format_size ───────────────────────────────────────────────────────

    #[test]
    fn format_size_bytes() {
        assert_eq!(format_size(0), "0 B");
        assert_eq!(format_size(512), "512 B");
        assert_eq!(format_size(1023), "1023 B");
    }

    #[test]
    fn format_size_kilobytes() {
        assert_eq!(format_size(1024), "1.0 KB");
        assert_eq!(format_size(2048), "2.0 KB");
        assert_eq!(format_size(1536), "1.5 KB");
    }

    #[test]
    fn format_size_megabytes() {
        assert_eq!(format_size(1024 * 1024), "1.0 MB");
        assert_eq!(format_size(5 * 1024 * 1024), "5.0 MB");
    }

    // ─── count_files ───────────────────────────────────────────────────────

    #[test]
    fn count_files_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(count_files(dir.path()), 0);
    }

    #[test]
    fn count_files_with_files() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("a.txt"), "a").unwrap();
        std::fs::write(dir.path().join("b.txt"), "b").unwrap();
        assert_eq!(count_files(dir.path()), 2);
    }

    #[test]
    fn count_files_nested() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("top.txt"), "t").unwrap();
        std::fs::create_dir_all(dir.path().join("sub")).unwrap();
        std::fs::write(dir.path().join("sub/nested.txt"), "n").unwrap();
        assert_eq!(count_files(dir.path()), 2);
    }

    #[test]
    fn count_files_non_directory_returns_zero() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("a.txt");
        std::fs::write(&file, "hello").unwrap();
        assert_eq!(count_files(&file), 0);
    }

    #[test]
    fn count_files_read_dir_error_returns_zero() {
        // An injected `read_dir` that fails on an existing directory exercises
        // the "read_dir errored -> keep the count so far" arm deterministically
        // on every platform.
        let dir = tempfile::tempdir().unwrap();
        let result = count_files_with(dir.path(), &|_| {
            Err(std::io::Error::other("simulated read_dir failure"))
        });
        assert_eq!(result, 0);
    }

    #[test]
    fn count_path_neither_file_nor_dir_counts_zero() {
        // A nonexistent path is neither a file nor a directory, so `count_path`
        // contributes 0 - covering the `else` arm on every platform.
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("does-not-exist");
        assert_eq!(count_path(&missing, &real_read_dir), 0);
    }

    // ─── find_manifest ─────────────────────────────────────────────────────

    #[test]
    fn find_manifest_in_directory() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = dir.path().join("agent.leviath");
        std::fs::write(&manifest, "name = \"test\"").unwrap();
        let result = find_manifest(dir.path());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), manifest);
    }

    #[test]
    fn find_manifest_direct_file() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = dir.path().join("agent.leviath");
        std::fs::write(&manifest, "name = \"test\"").unwrap();
        let result = find_manifest(&manifest);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), manifest);
    }

    #[test]
    fn find_manifest_not_found_errors() {
        let dir = tempfile::tempdir().unwrap();
        let result = find_manifest(dir.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("agent.leviath"));
    }

    // ─── find_manifest_with_cwd ────────────────────────────────────────────

    #[test]
    fn find_manifest_with_cwd_finds_in_directory() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = dir.path().join("agent.leviath");
        std::fs::write(&manifest, "name = \"test\"").unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let result = find_manifest_with_cwd(dir.path(), cwd.path());
        assert_eq!(result.unwrap(), manifest);
    }

    #[test]
    fn find_manifest_with_cwd_finds_direct_file() {
        let dir = tempfile::tempdir().unwrap();
        let manifest = dir.path().join("agent.leviath");
        std::fs::write(&manifest, "name = \"test\"").unwrap();
        let cwd = tempfile::tempdir().unwrap();
        let result = find_manifest_with_cwd(&manifest, cwd.path());
        assert_eq!(result.unwrap(), manifest);
    }

    #[test]
    fn find_manifest_with_cwd_falls_back_to_cwd() {
        let empty_dir = tempfile::tempdir().unwrap();
        let cwd_dir = tempfile::tempdir().unwrap();
        let cwd_manifest = cwd_dir.path().join("agent.leviath");
        std::fs::write(&cwd_manifest, "name = \"test\"").unwrap();
        let result = find_manifest_with_cwd(empty_dir.path(), cwd_dir.path());
        assert_eq!(result.unwrap(), cwd_manifest);
    }

    #[test]
    fn find_manifest_with_cwd_errors_when_not_found() {
        let empty_project = tempfile::tempdir().unwrap();
        let empty_cwd = tempfile::tempdir().unwrap();
        let result = find_manifest_with_cwd(empty_project.path(), empty_cwd.path());
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("agent.leviath"));
    }

    // ─── output path determination ─────────────────────────────────────────

    #[test]
    fn output_path_from_args() {
        let output_path =
            determine_output_path(Some("my-output.leviath-bundle"), "my-agent", "1.0.0");
        assert_eq!(output_path, PathBuf::from("my-output.leviath-bundle"));
    }

    #[test]
    fn output_path_default() {
        let output_path = determine_output_path(None, "my-agent", "1.0.0");
        assert_eq!(output_path, PathBuf::from("my-agent-1.0.0.leviath-bundle"));
    }

    // ─── format_size edge cases ───────────────────────────────────────────

    #[test]
    fn format_size_boundary_kb() {
        assert_eq!(format_size(1023), "1023 B");
        assert_eq!(format_size(1024), "1.0 KB");
    }

    #[test]
    fn format_size_boundary_mb() {
        assert_eq!(format_size(1024 * 1024 - 1), "1024.0 KB");
        assert_eq!(format_size(1024 * 1024), "1.0 MB");
    }

    #[test]
    fn format_size_fractional_kb() {
        assert_eq!(format_size(1536), "1.5 KB");
        assert_eq!(format_size(2560), "2.5 KB");
    }

    // ─── count_files edge cases ───────────────────────────────────────────

    #[test]
    fn count_files_nested_multiple_levels() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("a/b/c")).unwrap();
        std::fs::write(dir.path().join("root.txt"), "r").unwrap();
        std::fs::write(dir.path().join("a/level1.txt"), "1").unwrap();
        std::fs::write(dir.path().join("a/b/level2.txt"), "2").unwrap();
        std::fs::write(dir.path().join("a/b/c/level3.txt"), "3").unwrap();
        assert_eq!(count_files(dir.path()), 4);
    }

    // ─── find_manifest edge cases ─────────────────────────────────────────

    #[test]
    fn find_manifest_nonexistent_path_errors() {
        let result = find_manifest(Path::new("/tmp/nonexistent-leviath-test-dir"));
        assert!(result.is_err());
    }

    // ─── output path generation ───────────────────────────────────────────

    #[test]
    fn output_path_with_special_chars() {
        let output_path = determine_output_path(None, "my-agent", "1.0.0-beta.1");
        assert_eq!(
            output_path,
            PathBuf::from("my-agent-1.0.0-beta.1.leviath-bundle")
        );
    }

    // ─── execute ─────────────────────────────────────────────────────────

    fn make_project_dir(with_scripts: bool, with_tests: bool) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("agent.leviath"),
            "[agent]\nname = \"packed-agent\"\nversion = \"1.0.0\"\ndescription = \"d\"\n",
        )
        .unwrap();
        if with_scripts {
            std::fs::create_dir_all(dir.path().join("scripts")).unwrap();
            std::fs::write(dir.path().join("scripts/run.sh"), "#!/bin/sh\n").unwrap();
        }
        if with_tests {
            std::fs::create_dir_all(dir.path().join("tests")).unwrap();
            std::fs::write(dir.path().join("tests/test1.txt"), "test").unwrap();
        }
        dir
    }

    #[tokio::test]
    async fn execute_packs_project_to_explicit_output() {
        with_tracing(|| {});
        let project = make_project_dir(false, false);
        let output_dir = tempfile::tempdir().unwrap();
        let output_path = output_dir.path().join("out.leviath-bundle");
        let args = PackArgs {
            path: Some(project.path().to_str().unwrap().to_string()),
            output: Some(output_path.to_str().unwrap().to_string()),
        };
        execute(args).await.unwrap();
        assert!(output_path.exists());
        assert!(std::fs::metadata(&output_path).unwrap().len() > 0);
    }

    #[tokio::test]
    async fn execute_with_scripts_and_tests_dirs() {
        with_tracing(|| {});
        let project = make_project_dir(true, true);
        let output_dir = tempfile::tempdir().unwrap();
        let output_path = output_dir.path().join("out.leviath-bundle");
        let args = PackArgs {
            path: Some(project.path().to_str().unwrap().to_string()),
            output: Some(output_path.to_str().unwrap().to_string()),
        };
        execute(args).await.unwrap();
        assert!(output_path.exists());
    }

    #[tokio::test]
    async fn execute_missing_manifest_errors() {
        with_tracing(|| {});
        let project = tempfile::tempdir().unwrap();
        let output_dir = tempfile::tempdir().unwrap();
        let output_path = output_dir.path().join("out.leviath-bundle");
        let args = PackArgs {
            path: Some(project.path().to_str().unwrap().to_string()),
            output: Some(output_path.to_str().unwrap().to_string()),
        };
        let err = execute(args).await.unwrap_err();
        assert!(err.to_string().contains("Could not find agent.leviath"));
    }

    #[tokio::test]
    async fn execute_unwritable_output_path_errors() {
        with_tracing(|| {});
        let project = make_project_dir(false, false);
        let output_path = project
            .path()
            .join("nonexistent-subdir")
            .join("out.leviath-bundle");
        let args = PackArgs {
            path: Some(project.path().to_str().unwrap().to_string()),
            output: Some(output_path.to_str().unwrap().to_string()),
        };
        let err = execute(args).await.unwrap_err();
        assert!(err.to_string().contains("Failed to write bundle"));
    }

    #[tokio::test]
    async fn execute_with_path_none_falls_back_to_dot() {
        // args.path = None triggers the unwrap_or_else closure on line 21.
        with_tracing(|| {});
        let args = PackArgs {
            path: None,
            output: None,
        };
        let err = execute(args).await.unwrap_err();
        assert!(err.to_string().contains("agent.leviath"));
    }

    #[tokio::test]
    async fn execute_invalid_manifest_toml_errors() {
        // Manifest exists but is invalid TOML - covers parse_manifest ? on line 30.
        with_tracing(|| {});
        let project = tempfile::tempdir().unwrap();
        std::fs::write(project.path().join("agent.leviath"), "not valid toml ][").unwrap();
        let output_dir = tempfile::tempdir().unwrap();
        let output_path = output_dir.path().join("out.leviath-bundle");
        let args = PackArgs {
            path: Some(project.path().to_str().unwrap().to_string()),
            output: Some(output_path.to_str().unwrap().to_string()),
        };
        execute(args).await.unwrap_err();
    }

    #[tokio::test]
    async fn execute_unreadable_manifest_errors() {
        // `agent.leviath` exists but is a *directory*: `find_manifest` returns
        // it (exists() passes), then `read_to_string` fails on every platform,
        // covering the "Failed to read manifest" map_err arm.
        with_tracing(|| {});
        let project = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(project.path().join("agent.leviath")).unwrap();
        let output_dir = tempfile::tempdir().unwrap();
        let output_path = output_dir.path().join("out.leviath-bundle");
        let args = PackArgs {
            path: Some(project.path().to_str().unwrap().to_string()),
            output: Some(output_path.to_str().unwrap().to_string()),
        };
        let e = execute(args).await.unwrap_err();
        assert!(e.to_string().contains("Failed to read manifest"));
    }

    #[tokio::test]
    async fn execute_bundle_error_propagated() {
        // Inject a bundling op that fails, covering the `bundle(project_dir)?`
        // error arm on every platform.
        with_tracing(|| {});
        let project = make_project_dir(false, false);
        let output_dir = tempfile::tempdir().unwrap();
        let output_path = output_dir.path().join("out.leviath-bundle");
        let args = PackArgs {
            path: Some(project.path().to_str().unwrap().to_string()),
            output: Some(output_path.to_str().unwrap().to_string()),
        };
        let result =
            execute_with_bundle(args, &|_| Err(anyhow::anyhow!("simulated bundle failure"))).await;
        let e = result.unwrap_err();
        assert!(e.to_string().contains("simulated bundle failure"));
    }
}