omne-cli 0.2.1

CLI for managing omne volumes: init, upgrade, and validate kernel and distro releases
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
//! `omne validate` — check volume integrity against the v2 layout.
//!
//! Walks up from cwd to find `.omne/`, runs integrity checks: required
//! directories, docs baseline, 1-hop boot chain, core manifest, distro
//! content, pipe schema validation, depth rule scoped to `lib/cfg/`,
//! and the legacy gate runner.

use std::path::{Component, Path};

use clap::Args as ClapArgs;
use path_clean::PathClean;
use walkdir::WalkDir;

use crate::error::CliError;
use crate::manifest;
use crate::python;
use crate::volume;

/// Maximum nesting depth for user-authored content under `lib/cfg/`.
/// Measured as path components relative to `.omne/` (includes the
/// `lib/cfg/` prefix). e.g. `lib/cfg/sub1` = depth 3, allowed.
const MAX_DEPTH: usize = 3;

/// Required top-level directories under `.omne/`.
const REQUIRED_DIRS: &[&str] = &["core", "dist", "lib", "var"];

/// Required fields in `.omne/omne.md` frontmatter.
const REQUIRED_MANIFEST_FIELDS: &[&str] = &[
    "volume",
    "distro",
    "distro-version",
    "created",
    "kernel-source",
    "distro-source",
];

/// Arguments for `omne validate`.
#[derive(Debug, ClapArgs)]
pub struct Args {}

pub fn run(_args: &Args) -> Result<(), CliError> {
    let cwd = std::env::current_dir()
        .map_err(|e| CliError::Io(format!("cannot determine current directory: {e}")))?;
    validate_at_root(&cwd)
}

/// Test seam: validate a volume rooted at (or walked up from) `start`.
pub fn validate_at_root(start: &Path) -> Result<(), CliError> {
    let root = volume::find_omne_root(start).ok_or(CliError::NotAVolume)?;
    let omne = root.join(".omne");

    let mut issues = Vec::new();
    check_required_dirs(&omne, &mut issues);
    check_core(&omne, &mut issues);
    check_dist(&omne, &mut issues);
    check_boot_chain(&root, &mut issues);
    check_docs_baseline(&omne, &mut issues);
    check_manifest(&omne, &mut issues);
    check_depth(&omne, &mut issues);
    check_gate_runner(&omne, &mut issues);
    check_pipes(&root, &mut issues);

    for warning in collect_legacy_skill_warnings(&omne) {
        eprintln!("\x1b[33mwarning:\x1b[0m {warning}");
    }

    if issues.is_empty() {
        eprintln!("\x1b[32mVolume is valid.\x1b[0m");
        Ok(())
    } else {
        Err(CliError::ValidationFailed { issues })
    }
}

/// Collect warnings for legacy single-file skills that v0.2.1+ no longer
/// links: any `.md` regular file directly under `.omne/core/skills/` or
/// `.omne/dist/skills/` (skill entries must now be directories with a
/// `SKILL.md`, and file-layout commands belong under the sibling
/// `cmds/` directory).
fn collect_legacy_skill_warnings(omne: &Path) -> Vec<String> {
    let mut warnings = Vec::new();
    for layer in ["core", "dist"] {
        let skills_dir = omne.join(layer).join("skills");
        let entries = match std::fs::read_dir(&skills_dir) {
            Ok(e) => e,
            Err(_) => continue,
        };
        for entry in entries.flatten() {
            let file_type = match entry.file_type() {
                Ok(ft) => ft,
                Err(_) => continue,
            };
            if !file_type.is_file() {
                continue;
            }
            let path = entry.path();
            if path.extension().is_none_or(|ext| ext != "md") {
                continue;
            }
            let name = match path.file_stem().and_then(|s| s.to_str()) {
                Some(n) => n.to_string(),
                None => continue,
            };
            warnings.push(format!(
                "single-file skill at {layer}/skills/{name}.md is no longer linked by v0.2.1+; move to {layer}/cmds/{name}.md"
            ));
        }
    }
    warnings.sort();
    warnings
}

/// Walk `.omne/dist/pipes/*.md` and surface every parse / structural
/// / volume-aware validation issue per pipe. Missing `dist/pipes/`
/// directory is silently skipped — a fresh volume with no distro
/// pipes is a valid state.
fn check_pipes(root: &Path, issues: &mut Vec<String>) {
    let pipes_dir = volume::dist_dir(root).join("pipes");
    if !pipes_dir.is_dir() {
        return;
    }
    let entries = match std::fs::read_dir(&pipes_dir) {
        Ok(e) => e,
        Err(e) => {
            issues.push(format!("cannot read {}: {e}", pipes_dir.display()));
            return;
        }
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().is_none_or(|ext| ext != "md") {
            continue;
        }
        match crate::pipe::load(&path, root) {
            Ok(pipe) => {
                for warning in crate::pipe::collect_warnings(&pipe) {
                    eprintln!("\x1b[33mwarning:\x1b[0m pipe {}: {warning}", path.display());
                }
            }
            Err(crate::pipe::LoadError::Parse(e)) => {
                issues.push(format!("pipe {}: {e}", path.display()));
            }
            Err(crate::pipe::LoadError::Invalid(errs)) => {
                for err in errs {
                    issues.push(format!("pipe {}: {err}", path.display()));
                }
            }
        }
    }
}

/// Check that all required top-level directories exist under `.omne/`.
fn check_required_dirs(omne: &Path, issues: &mut Vec<String>) {
    for &dir in REQUIRED_DIRS {
        if !omne.join(dir).is_dir() {
            issues.push(format!("missing required directory: .omne/{dir}/"));
        }
    }
}

/// Check that `.omne/core/manifest.json` exists.
fn check_core(omne: &Path, issues: &mut Vec<String>) {
    let core = omne.join("core");
    if !core.is_dir() {
        return;
    }
    if !core.join("manifest.json").is_file() {
        issues.push("missing kernel manifest: core/manifest.json".to_string());
    }
}

/// Check that `.omne/dist/AGENTS.md` exists (boot chain target).
fn check_dist(omne: &Path, issues: &mut Vec<String>) {
    let dist = omne.join("dist");
    if !dist.is_dir() {
        return;
    }
    if !dist.join("AGENTS.md").is_file() {
        issues.push("missing distro entry point: dist/AGENTS.md".to_string());
    }
}

/// Check the 1-hop boot chain: volume root `CLAUDE.md` must contain
/// exactly `@.omne/dist/AGENTS.md`. Detects legacy multi-hop chains
/// and suggests migration.
fn check_boot_chain(root: &Path, issues: &mut Vec<String>) {
    let bootloader = root.join("CLAUDE.md");
    if !bootloader.is_file() {
        issues.push("missing CLAUDE.md at volume root".to_string());
        return;
    }
    let content = match std::fs::read_to_string(&bootloader) {
        Ok(c) => c,
        Err(e) => {
            issues.push(format!("cannot read CLAUDE.md: {e}"));
            return;
        }
    };

    let imports: Vec<&str> = content
        .lines()
        .map(str::trim)
        .filter(|l| l.starts_with('@'))
        .collect();

    if imports.is_empty() {
        issues.push("CLAUDE.md has no @import — expected @.omne/dist/AGENTS.md".to_string());
        return;
    }

    let has_v2_import = imports.contains(&"@.omne/dist/AGENTS.md");

    if !has_v2_import {
        let is_legacy = imports.iter().any(|&l| {
            l.contains("MANIFEST.md") || l.contains("SYSTEM.md") || l.contains(".omne/image/")
        });
        if is_legacy {
            issues.push(
                "legacy boot chain detected — run `omne init` to migrate to 1-hop @.omne/dist/AGENTS.md"
                    .to_string(),
            );
        } else {
            issues.push(format!(
                "CLAUDE.md @import does not reference .omne/dist/AGENTS.md — found: {}",
                imports.join(", ")
            ));
        }
    }
}

/// Warn (not error) if docs baseline is incomplete.
fn check_docs_baseline(omne: &Path, issues: &mut Vec<String>) {
    let docs = omne.join("lib").join("docs");
    if !docs.is_dir() {
        return;
    }
    if !docs.join("index.md").is_file() {
        eprintln!("\x1b[33mwarning:\x1b[0m missing lib/docs/index.md");
    }
    for subdir in ["raw", "inter", "wiki"] {
        if !docs.join(subdir).is_dir() {
            eprintln!("\x1b[33mwarning:\x1b[0m missing lib/docs/{subdir}/");
        }
    }
    let _ = issues; // docs baseline is warning-only
}

/// Check that `.omne/omne.md` exists, has frontmatter, and contains
/// all required fields.
fn check_manifest(omne: &Path, issues: &mut Vec<String>) {
    let readme = omne.join("omne.md");
    if !readme.is_file() {
        issues.push("missing .omne/omne.md".to_string());
        return;
    }

    let content = match std::fs::read_to_string(&readme) {
        Ok(c) => c,
        Err(e) => {
            issues.push(format!("cannot read .omne/omne.md: {e}"));
            return;
        }
    };

    let yaml_body = match manifest::extract_frontmatter_block(&content) {
        Ok(body) => body,
        Err(_) => {
            issues.push(".omne/omne.md has no YAML frontmatter (---...---)".to_string());
            return;
        }
    };

    for &field in REQUIRED_MANIFEST_FIELDS {
        let has_field = yaml_body
            .lines()
            .any(|line| line.starts_with(field) && line[field.len()..].starts_with(':'));
        if !has_field {
            issues.push(format!(".omne/omne.md missing required field: {field}"));
        }
    }
}

/// Check depth of directories under `lib/cfg/` only. MAX_DEPTH = 3.
/// `core/`, `dist/`, and `lib/docs/` are excluded — release artifacts
/// and knowledge-base content may have deep nesting.
fn check_depth(omne: &Path, issues: &mut Vec<String>) {
    let base = omne.join("lib").join("cfg");
    if !base.is_dir() {
        return;
    }
    for entry in WalkDir::new(&base).min_depth(1) {
        let entry = match entry {
            Ok(e) => e,
            Err(_) => continue,
        };
        if !entry.file_type().is_dir() {
            continue;
        }
        let rel = match entry.path().strip_prefix(omne) {
            Ok(r) => r,
            Err(_) => continue,
        };
        let depth = rel.components().count();
        if depth > MAX_DEPTH {
            issues.push(format!(
                "depth violation ({depth} > {MAX_DEPTH}): .omne/{}",
                rel.display()
            ));
        }
    }
}

/// Read gate_runner from core/manifest.json, validate path safety, and
/// invoke it with the discovered Python interpreter.
fn check_gate_runner(omne: &Path, issues: &mut Vec<String>) {
    let core_manifest = omne.join("core/manifest.json");
    if !core_manifest.is_file() {
        return;
    }

    let content = match std::fs::read_to_string(&core_manifest) {
        Ok(c) => c,
        Err(_) => return,
    };

    let data: serde_json::Value = match serde_json::from_str(&content) {
        Ok(d) => d,
        Err(_) => {
            issues.push("core/manifest.json is invalid JSON".to_string());
            return;
        }
    };

    let gate_runner = match data.get("gate_runner").and_then(|v| v.as_str()) {
        Some(gr) => gr,
        None => return,
    };

    let dist_dir = omne.join("dist");
    if !is_safe_gate_runner_path(gate_runner, &dist_dir) {
        issues.push(format!("gate runner path escapes dist/: {gate_runner}"));
        return;
    }

    let runner_path = dist_dir.join(gate_runner);
    if !runner_path.is_file() {
        eprintln!("\x1b[33mwarning:\x1b[0m gate runner not found: dist/{gate_runner} (skipping)");
        return;
    }

    let interpreter = match python::find_interpreter() {
        Some(interp) => interp,
        None => {
            eprintln!("\x1b[33m{}\x1b[0m", python::missing_python_warning());
            return;
        }
    };

    if let Err(e) = python::run_gate_runner(&interpreter, &runner_path, &dist_dir) {
        match e {
            python::Error::GateRunnerFailed {
                exit_code,
                stdout,
                stderr,
            } => {
                let mut msg = format!("gate runner failed (exit {exit_code}):");
                for line in stdout.trim().lines() {
                    msg.push_str(&format!("\n  {line}"));
                }
                for line in stderr.trim().lines() {
                    msg.push_str(&format!("\n  {line}"));
                }
                issues.push(msg);
            }
            python::Error::GateRunnerTimedOut { elapsed_seconds } => {
                issues.push(format!(
                    "gate runner timed out after {elapsed_seconds} seconds"
                ));
            }
            python::Error::InterpreterInvocation(io_err) => {
                issues.push(format!("failed to invoke gate runner: {io_err}"));
            }
        }
    }
}

/// Check that a gate runner path is safe (no traversal, no absolute paths).
fn is_safe_gate_runner_path(gate_runner: &str, base_dir: &Path) -> bool {
    let path = Path::new(gate_runner);

    if path.is_absolute() {
        return false;
    }

    for component in path.components() {
        match component {
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return false;
            }
            _ => {}
        }
    }

    let resolved = base_dir.join(path).clean();
    let base_clean = base_dir.clean();
    resolved.starts_with(&base_clean)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Build a minimal fixture volume rooted at `tmp` with the layout
    /// needed for `collect_legacy_skill_warnings` — only the
    /// `core/skills/` and `dist/skills/` directories are created; callers
    /// populate them per test.
    fn make_volume(tmp: &Path) {
        let omne = tmp.join(".omne");
        fs::create_dir_all(omne.join("core").join("skills")).unwrap();
        fs::create_dir_all(omne.join("dist").join("skills")).unwrap();
        fs::create_dir_all(omne.join("core").join("cmds")).unwrap();
        fs::create_dir_all(omne.join("dist").join("cmds")).unwrap();
    }

    fn make_dir_skill(tmp: &Path, layer: &str, name: &str) {
        let dir = tmp.join(".omne").join(layer).join("skills").join(name);
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join("SKILL.md"),
            format!("---\nname: {name}\ndescription: test\n---\n"),
        )
        .unwrap();
    }

    fn make_cmd(tmp: &Path, layer: &str, name: &str) {
        let path = tmp
            .join(".omne")
            .join(layer)
            .join("cmds")
            .join(format!("{name}.md"));
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, format!("# {name}\n")).unwrap();
    }

    fn make_legacy_file_skill(tmp: &Path, layer: &str, name: &str) {
        let path = tmp
            .join(".omne")
            .join(layer)
            .join("skills")
            .join(format!("{name}.md"));
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, format!("# {name}\n")).unwrap();
    }

    #[test]
    fn no_warnings_for_valid_cmds_and_dir_skills() {
        let tmp = TempDir::new().unwrap();
        make_volume(tmp.path());
        make_cmd(tmp.path(), "dist", "foo");
        make_dir_skill(tmp.path(), "dist", "bar");

        let warnings = collect_legacy_skill_warnings(&tmp.path().join(".omne"));
        assert!(
            warnings.is_empty(),
            "expected no warnings, got {warnings:?}"
        );
    }

    #[test]
    fn warns_on_legacy_dist_file_skill() {
        let tmp = TempDir::new().unwrap();
        make_volume(tmp.path());
        make_legacy_file_skill(tmp.path(), "dist", "plan");

        let warnings = collect_legacy_skill_warnings(&tmp.path().join(".omne"));
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains("dist/skills/plan.md")
                && warnings[0].contains("dist/cmds/plan.md"),
            "unexpected warning text: {}",
            warnings[0]
        );
    }

    #[test]
    fn warns_on_legacy_core_file_skill() {
        let tmp = TempDir::new().unwrap();
        make_volume(tmp.path());
        make_legacy_file_skill(tmp.path(), "core", "plan");

        let warnings = collect_legacy_skill_warnings(&tmp.path().join(".omne"));
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains("core/skills/plan.md")
                && warnings[0].contains("core/cmds/plan.md"),
            "unexpected warning text: {}",
            warnings[0]
        );
    }

    #[test]
    fn warns_on_legacy_even_when_cmds_present() {
        let tmp = TempDir::new().unwrap();
        make_volume(tmp.path());
        make_legacy_file_skill(tmp.path(), "dist", "plan");
        make_cmd(tmp.path(), "dist", "plan");

        let warnings = collect_legacy_skill_warnings(&tmp.path().join(".omne"));
        assert_eq!(warnings.len(), 1, "got {warnings:?}");
        assert!(
            warnings[0].contains("dist/skills/plan.md"),
            "unexpected warning text: {}",
            warnings[0]
        );
    }

    #[test]
    fn ignores_dir_skills_and_non_md_files() {
        let tmp = TempDir::new().unwrap();
        make_volume(tmp.path());
        make_dir_skill(tmp.path(), "dist", "legit");
        // Non-.md file directly under skills/ should be ignored.
        fs::write(
            tmp.path().join(".omne/dist/skills/README.txt"),
            "not a skill",
        )
        .unwrap();

        let warnings = collect_legacy_skill_warnings(&tmp.path().join(".omne"));
        assert!(
            warnings.is_empty(),
            "expected no warnings, got {warnings:?}"
        );
    }

    #[test]
    fn missing_skills_dirs_produce_no_warnings() {
        let tmp = TempDir::new().unwrap();
        // Do not call make_volume — no `.omne/` exists.
        let warnings = collect_legacy_skill_warnings(&tmp.path().join(".omne"));
        assert!(warnings.is_empty());
    }
}