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
//! `.claude/` symlinking for Claude Code discovery.
//!
//! After `.omne/core/` and `.omne/dist/` are extracted, this module
//! wires two separate namespaces so Claude Code auto-discovers kernel
//! + distro entries without any runtime indirection:
//!
//! - `.omne/{core,dist}/skills/<name>/` — dir-layout skills → symlinked
//!   to `.claude/skills/<name>/` (auto-invoked via `SKILL.md` frontmatter
//!   triggers).
//! - `.omne/{core,dist}/cmds/<name>.md` — file-layout commands →
//!   symlinked to `.claude/commands/<name>.md` (invoked via explicit
//!   `/<name>` slash prompts from AI nodes).
//!
//! Distro shadows kernel in both namespaces (distro layer runs second
//! and overwrites any symlink produced by the kernel pass).
//!
//! Windows requires `ERROR_PRIVILEGE_NOT_HELD` unlocked via either
//! elevation or Developer Mode for both directory and file symlinks.
//! `preflight()` probes both and fails fast with an actionable error
//! before any download occurs.

use std::fs;
use std::io;
use std::path::Path;

use crate::error::CliError;

/// Windows error code for symlink-without-privilege.
#[cfg(windows)]
const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;

/// Probe whether this process can create directory AND file symlinks.
///
/// On Windows, creates throwaway symlinks in the system temp directory
/// for each kind. On `ERROR_PRIVILEGE_NOT_HELD`, returns
/// `SymlinkPrivilegeRequired` so `init` can bail before fetching
/// tarballs. On Unix this is a no-op — symlinks work unprivileged.
pub fn preflight() -> Result<(), CliError> {
    #[cfg(windows)]
    {
        use std::os::windows::fs::{symlink_dir, symlink_file};
        use std::sync::atomic::{AtomicU64, Ordering};
        use std::time::{SystemTime, UNIX_EPOCH};

        static COUNTER: AtomicU64 = AtomicU64::new(0);

        let tmp = std::env::temp_dir();
        let pid = std::process::id();
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);

        // --- Dir symlink probe ---
        let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir_src = tmp.join(format!("omne-preflight-dsrc-{pid}-{nanos}-{seq}"));
        let dir_dst = tmp.join(format!("omne-preflight-ddst-{pid}-{nanos}-{seq}"));
        fs::create_dir_all(&dir_src)?;
        let dir_result = symlink_dir(&dir_src, &dir_dst);
        let _ = fs::remove_dir(&dir_dst);
        let _ = fs::remove_dir_all(&dir_src);
        match dir_result {
            Ok(()) => {}
            Err(e) if e.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD) => {
                return Err(CliError::SymlinkPrivilegeRequired);
            }
            Err(e) => return Err(CliError::Io(format!("dir symlink preflight failed: {e}"))),
        }

        // --- File symlink probe ---
        let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
        let file_src = tmp.join(format!("omne-preflight-fsrc-{pid}-{nanos}-{seq}.md"));
        let file_dst = tmp.join(format!("omne-preflight-fdst-{pid}-{nanos}-{seq}.md"));
        fs::write(&file_src, b"preflight")?;
        let file_result = symlink_file(&file_src, &file_dst);
        let _ = fs::remove_file(&file_dst);
        let _ = fs::remove_file(&file_src);
        match file_result {
            Ok(()) => Ok(()),
            Err(e) if e.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD) => {
                Err(CliError::SymlinkPrivilegeRequired)
            }
            Err(e) => Err(CliError::Io(format!("file symlink preflight failed: {e}"))),
        }
    }

    #[cfg(not(windows))]
    {
        Ok(())
    }
}

/// Wire both `skills/` and `cmds/` namespaces across `.omne/core/`
/// and `.omne/dist/` into their respective `.claude/` destinations.
///
/// - `<layer>/skills/<name>/` → `.claude/skills/<name>/` (dir symlink)
/// - `<layer>/cmds/<name>.md` → `.claude/commands/<name>.md` (file symlink)
///
/// Kernel layer runs first, distro second — distro wins on name
/// collision within each namespace.
pub fn link_layers(root: &Path) -> Result<(), CliError> {
    let omne = root.join(".omne");
    let claude_skills = root.join(".claude").join("skills");
    let claude_commands = root.join(".claude").join("commands");
    fs::create_dir_all(&claude_skills)?;
    fs::create_dir_all(&claude_commands)?;

    for layer in ["core", "dist"] {
        let layer_skills = omne.join(layer).join("skills");
        if layer_skills.is_dir() {
            link_skills_layer(&layer_skills, &claude_skills)?;
        }
        let layer_cmds = omne.join(layer).join("cmds");
        if layer_cmds.is_dir() {
            link_cmds_layer(&layer_cmds, &claude_commands)?;
        }
    }
    Ok(())
}

fn link_skills_layer(src_skills: &Path, dst_skills: &Path) -> Result<(), CliError> {
    for entry in fs::read_dir(src_skills)? {
        let entry = entry?;
        let src = entry.path();
        if !src.is_dir() {
            // Only directory-layout skills (skills/<name>/SKILL.md).
            // File-layout commands belong under the sibling `cmds/` dir;
            // `validate` warns if any are found here.
            continue;
        }
        let name = entry.file_name();
        let dst = dst_skills.join(&name);
        replace_symlink(&src, &dst, LinkKind::Dir)?;
    }
    Ok(())
}

fn link_cmds_layer(src_cmds: &Path, dst_commands: &Path) -> Result<(), CliError> {
    for entry in fs::read_dir(src_cmds)? {
        let entry = entry?;
        let src = entry.path();
        // Accept only regular `.md` files.
        let file_type = entry.file_type()?;
        if !file_type.is_file() {
            continue;
        }
        if src.extension().is_none_or(|ext| ext != "md") {
            continue;
        }
        let name = entry.file_name();
        let dst = dst_commands.join(&name);
        replace_symlink(&src, &dst, LinkKind::File)?;
    }
    Ok(())
}

#[derive(Clone, Copy)]
enum LinkKind {
    Dir,
    File,
}

/// Remove any existing symlink at `dst`, then create a fresh one
/// pointing at `src`. Refuses to remove a real file/directory so a
/// user's hand-authored entry is never clobbered.
fn replace_symlink(src: &Path, dst: &Path, kind: LinkKind) -> Result<(), CliError> {
    if let Ok(meta) = fs::symlink_metadata(dst) {
        if meta.file_type().is_symlink() {
            remove_symlink(dst, kind)?;
        } else {
            let namespace = match kind {
                LinkKind::Dir => "skills",
                LinkKind::File => "commands",
            };
            return Err(CliError::Io(format!(
                ".claude/{namespace}/{} exists and is not a symlink — refusing to overwrite",
                dst.file_name().unwrap_or_default().to_string_lossy()
            )));
        }
    }
    let result = match kind {
        LinkKind::Dir => symlink_dir(src, dst),
        LinkKind::File => symlink_file(src, dst),
    };
    result.map_err(|e| {
        #[cfg(windows)]
        if e.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD) {
            return CliError::SymlinkPrivilegeRequired;
        }
        CliError::Io(format!(
            "failed to symlink {} -> {}: {e}",
            dst.display(),
            src.display()
        ))
    })
}

#[cfg(windows)]
fn symlink_dir(src: &Path, dst: &Path) -> io::Result<()> {
    std::os::windows::fs::symlink_dir(src, dst)
}

#[cfg(unix)]
fn symlink_dir(src: &Path, dst: &Path) -> io::Result<()> {
    std::os::unix::fs::symlink(src, dst)
}

#[cfg(windows)]
fn symlink_file(src: &Path, dst: &Path) -> io::Result<()> {
    std::os::windows::fs::symlink_file(src, dst)
}

#[cfg(unix)]
fn symlink_file(src: &Path, dst: &Path) -> io::Result<()> {
    std::os::unix::fs::symlink(src, dst)
}

fn remove_symlink(dst: &Path, kind: LinkKind) -> io::Result<()> {
    #[cfg(windows)]
    {
        match kind {
            // Windows: dir-symlinks must be removed with remove_dir.
            LinkKind::Dir => fs::remove_dir(dst),
            LinkKind::File => fs::remove_file(dst),
        }
    }
    #[cfg(unix)]
    {
        let _ = kind;
        fs::remove_file(dst)
    }
}

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

    fn make_dir_skill(root: &Path, layer: &str, name: &str) {
        let dir = root.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(root: &Path, layer: &str, name: &str) {
        let dir = root.join(".omne").join(layer).join("cmds");
        fs::create_dir_all(&dir).unwrap();
        fs::write(
            dir.join(format!("{name}.md")),
            format!("---\nname: {name}\n---\n# {name}\n"),
        )
        .unwrap();
    }

    #[test]
    fn links_kernel_skill() {
        let tmp = TempDir::new().unwrap();
        make_dir_skill(tmp.path(), "core", "query-installation");

        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/skills/query-installation");
        let meta = fs::symlink_metadata(&link).unwrap();
        assert!(meta.file_type().is_symlink());
    }

    #[test]
    fn links_distro_skill() {
        let tmp = TempDir::new().unwrap();
        make_dir_skill(tmp.path(), "dist", "assess-domain");

        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/skills/assess-domain");
        assert!(fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink());
    }

    #[test]
    fn dist_shadows_kernel_skill_on_name_collision() {
        let tmp = TempDir::new().unwrap();
        make_dir_skill(tmp.path(), "core", "dup");
        make_dir_skill(tmp.path(), "dist", "dup");

        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/skills/dup");
        let target = fs::read_link(&link).unwrap();
        assert!(
            target.to_string_lossy().contains("dist"),
            "expected dist/ target, got {}",
            target.display()
        );
    }

    #[test]
    fn links_multiple_skills() {
        let tmp = TempDir::new().unwrap();
        make_dir_skill(tmp.path(), "dist", "a");
        make_dir_skill(tmp.path(), "dist", "b");
        make_dir_skill(tmp.path(), "dist", "c");

        link_layers(tmp.path()).unwrap();

        for name in ["a", "b", "c"] {
            let link = tmp.path().join(".claude/skills").join(name);
            assert!(fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink());
        }
    }

    #[test]
    fn refuses_to_overwrite_real_skill_directory() {
        let tmp = TempDir::new().unwrap();
        make_dir_skill(tmp.path(), "dist", "preexisting");

        let real = tmp.path().join(".claude/skills/preexisting");
        fs::create_dir_all(&real).unwrap();
        fs::write(real.join("SKILL.md"), "user content").unwrap();

        let err = link_layers(tmp.path()).unwrap_err();
        assert!(
            matches!(err, CliError::Io(ref m) if m.contains("refusing to overwrite")),
            "expected Io refusal, got {err:?}"
        );
    }

    #[test]
    fn idempotent_skills() {
        let tmp = TempDir::new().unwrap();
        make_dir_skill(tmp.path(), "dist", "repeat");

        link_layers(tmp.path()).unwrap();
        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/skills/repeat");
        assert!(fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink());
    }

    // ── cmds/ namespace tests ──────────────────────────────────────

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

        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/commands/plan.md");
        let meta = fs::symlink_metadata(&link).unwrap();
        assert!(meta.file_type().is_symlink());
    }

    #[test]
    fn links_distro_cmd() {
        let tmp = TempDir::new().unwrap();
        make_cmd(tmp.path(), "dist", "implement");

        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/commands/implement.md");
        assert!(fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink());
    }

    #[test]
    fn dist_shadows_kernel_cmd_on_name_collision() {
        let tmp = TempDir::new().unwrap();
        make_cmd(tmp.path(), "core", "dup");
        make_cmd(tmp.path(), "dist", "dup");

        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/commands/dup.md");
        let target = fs::read_link(&link).unwrap();
        assert!(
            target.to_string_lossy().contains("dist"),
            "expected dist/ target, got {}",
            target.display()
        );
    }

    #[test]
    fn mixed_layer_both_namespaces() {
        let tmp = TempDir::new().unwrap();
        make_dir_skill(tmp.path(), "dist", "my-skill");
        make_cmd(tmp.path(), "dist", "my-cmd");

        link_layers(tmp.path()).unwrap();

        assert!(
            fs::symlink_metadata(tmp.path().join(".claude/skills/my-skill"))
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert!(
            fs::symlink_metadata(tmp.path().join(".claude/commands/my-cmd.md"))
                .unwrap()
                .file_type()
                .is_symlink()
        );
    }

    #[test]
    fn non_md_file_in_cmds_is_skipped() {
        let tmp = TempDir::new().unwrap();
        let cmds_dir = tmp.path().join(".omne/dist/cmds");
        fs::create_dir_all(&cmds_dir).unwrap();
        fs::write(cmds_dir.join("notes.txt"), "not a cmd").unwrap();
        fs::write(cmds_dir.join("plan.bak"), "backup").unwrap();
        make_cmd(tmp.path(), "dist", "real");

        link_layers(tmp.path()).unwrap();

        assert!(fs::symlink_metadata(tmp.path().join(".claude/commands/real.md")).is_ok());
        assert!(fs::symlink_metadata(tmp.path().join(".claude/commands/notes.txt")).is_err());
        assert!(fs::symlink_metadata(tmp.path().join(".claude/commands/plan.bak")).is_err());
    }

    #[test]
    fn subdirectory_in_cmds_is_skipped() {
        let tmp = TempDir::new().unwrap();
        let cmds_dir = tmp.path().join(".omne/dist/cmds");
        fs::create_dir_all(cmds_dir.join("nested")).unwrap();
        make_cmd(tmp.path(), "dist", "real");

        link_layers(tmp.path()).unwrap();

        assert!(fs::symlink_metadata(tmp.path().join(".claude/commands/real.md")).is_ok());
        assert!(fs::symlink_metadata(tmp.path().join(".claude/commands/nested")).is_err());
    }

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

        let real_dir = tmp.path().join(".claude/commands");
        fs::create_dir_all(&real_dir).unwrap();
        fs::write(real_dir.join("plan.md"), "user content").unwrap();

        let err = link_layers(tmp.path()).unwrap_err();
        assert!(
            matches!(err, CliError::Io(ref m) if m.contains("refusing to overwrite")),
            "expected Io refusal, got {err:?}"
        );
    }

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

        link_layers(tmp.path()).unwrap();
        link_layers(tmp.path()).unwrap();

        let link = tmp.path().join(".claude/commands/plan.md");
        assert!(fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink());
    }

    #[test]
    fn preflight_succeeds_in_test_environment() {
        // CI / dev environments running the test suite should have
        // symlink capability (both dir and file). If this fails on
        // Windows CI, Developer Mode is off and needs enabling.
        preflight().unwrap();
    }
}