dalo 0.8.2

Git-backed skill management for AI agents.
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Agent target registry and detection.

use std::fs;
use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::error::{DaloError, DaloResult};
use crate::store::{self, StateFile, StorePaths, TargetState};

/// Target support level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetSupport {
    /// Supported V1 target.
    Supported,
    /// Known but unverified target.
    Experimental,
}

impl TargetSupport {
    /// Text label.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Supported => "supported",
            Self::Experimental => "experimental",
        }
    }
}

/// Static target registry entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TargetRegistryEntry {
    /// Target ID.
    pub id: &'static str,
    /// Display name.
    pub name: &'static str,
    /// Default skill path.
    pub default_path: Option<&'static str>,
    /// Support level.
    pub support: TargetSupport,
}

/// One detected target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetDetection {
    /// Target ID.
    pub id: String,
    /// Display name.
    pub name: String,
    /// Support level.
    pub support: TargetSupport,
    /// Expanded default path when known.
    pub path: Option<PathBuf>,
    /// Whether the path currently exists.
    pub exists: bool,
    /// Whether the target is linked in state.
    pub linked: bool,
}

/// Target detection report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetDetectReport {
    /// Detected targets.
    pub targets: Vec<TargetDetection>,
}

/// Target link status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetLinkStatus {
    /// Link would be created in dry-run mode.
    Planned,
    /// Target was linked.
    Linked,
    /// Existing target was updated.
    Updated,
    /// Target was already linked with the same path.
    Existing,
}

impl TargetLinkStatus {
    /// Text label.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Planned => "planned",
            Self::Linked => "linked",
            Self::Updated => "updated",
            Self::Existing => "existing",
        }
    }
}

/// Target link report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetLinkReport {
    /// Target ID.
    pub target_id: String,
    /// Expanded path.
    pub path: PathBuf,
    /// Canonical path.
    pub canonical_path: PathBuf,
    /// Link status.
    pub status: TargetLinkStatus,
    /// Whether the directory was created.
    pub created_dir: bool,
}

/// Target unlink status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetUnlinkStatus {
    /// Unlink would run in dry-run mode.
    Planned,
    /// Target was unlinked.
    Unlinked,
    /// Target was not linked.
    Missing,
}

impl TargetUnlinkStatus {
    /// Text label.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Planned => "planned",
            Self::Unlinked => "unlinked",
            Self::Missing => "missing",
        }
    }
}

/// Target unlink report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TargetUnlinkReport {
    /// Target ID.
    pub target_id: String,
    /// Unlink status.
    pub status: TargetUnlinkStatus,
}

/// Return the built-in target registry.
#[must_use]
pub fn registry() -> &'static [TargetRegistryEntry] {
    &[
        TargetRegistryEntry {
            id: "codex",
            name: "Codex",
            default_path: Some("~/.agents/skills"),
            support: TargetSupport::Supported,
        },
        TargetRegistryEntry {
            id: "claude",
            name: "Claude Code",
            default_path: Some("~/.claude/skills"),
            support: TargetSupport::Supported,
        },
        TargetRegistryEntry {
            id: "openclaw",
            name: "OpenClaw",
            default_path: Some("~/.agents/skills"),
            support: TargetSupport::Supported,
        },
        TargetRegistryEntry {
            id: "hermes",
            name: "Hermes",
            default_path: Some("~/.hermes/skills"),
            support: TargetSupport::Supported,
        },
        TargetRegistryEntry {
            id: "generic",
            name: "Generic folder",
            default_path: None,
            support: TargetSupport::Supported,
        },
        TargetRegistryEntry {
            id: "cursor",
            name: "Cursor",
            default_path: None,
            support: TargetSupport::Experimental,
        },
        TargetRegistryEntry {
            id: "opencode",
            name: "OpenCode",
            default_path: None,
            support: TargetSupport::Experimental,
        },
    ]
}

/// Detect target paths and current link state.
#[must_use = "the target detection report should be rendered or inspected"]
pub fn detect_targets(store_root: &Path) -> DaloResult<TargetDetectReport> {
    let paths = StorePaths::new(store_root.to_path_buf());
    let state = read_state_if_initialized(&paths)?;

    let targets = registry()
        .iter()
        .map(|entry| detect_entry(entry, state.as_ref()))
        .collect::<DaloResult<Vec<_>>>()?;

    Ok(TargetDetectReport { targets })
}

/// Link a target.
pub fn link_target(
    store_root: &Path,
    target_id: &str,
    path_override: Option<&Path>,
    dry_run: bool,
) -> DaloResult<TargetLinkReport> {
    let entry = registry_entry(target_id)?;
    let path = target_path(entry, path_override)?;
    let existed_before = path.exists();

    let paths = StorePaths::new(store_root.to_path_buf());
    let mut state = if dry_run {
        None
    } else {
        Some(store::read_state(&paths)?)
    };

    let canonical_path = canonicalize_target_path(&path);
    let status = if dry_run {
        TargetLinkStatus::Planned
    } else {
        let state = state
            .as_mut()
            .expect("state is loaded before non-dry-run target link");
        let status = upsert_target_state(state, entry.id, &path, &canonical_path)?;
        if !existed_before {
            fs::create_dir_all(&path)?;
        }
        if let Err(error) = store::write_state(&paths, state) {
            if !existed_before {
                // Only remove the leaf when it is still empty. This avoids
                // leaving a phantom target directory without risking content
                // that appeared concurrently.
                let _ = fs::remove_dir(&path);
            }
            return Err(error);
        }
        status
    };

    Ok(TargetLinkReport {
        target_id: entry.id.to_owned(),
        path,
        canonical_path,
        status,
        created_dir: !existed_before && !dry_run,
    })
}

/// Unlink a target from state without removing target files.
pub fn unlink_target(
    store_root: &Path,
    target_id: &str,
    dry_run: bool,
) -> DaloResult<TargetUnlinkReport> {
    registry_entry(target_id)?;

    let paths = StorePaths::new(store_root.to_path_buf());
    let mut state = store::read_state(&paths)?;
    let original_len = state.targets.len();
    let linked = state.targets.iter().any(|target| target.id == target_id);
    let status = if dry_run {
        if linked {
            TargetUnlinkStatus::Planned
        } else {
            TargetUnlinkStatus::Missing
        }
    } else {
        state.targets.retain(|target| target.id != target_id);
        state.rebuild_materialization_dirs_for_removal()?;
        store::write_state(&paths, &state)?;

        if state.targets.len() == original_len {
            TargetUnlinkStatus::Missing
        } else {
            TargetUnlinkStatus::Unlinked
        }
    };

    Ok(TargetUnlinkReport {
        target_id: target_id.to_owned(),
        status,
    })
}

fn detect_entry(
    entry: &TargetRegistryEntry,
    state: Option<&StateFile>,
) -> DaloResult<TargetDetection> {
    let path = entry
        .default_path
        .map(PathBuf::from)
        .map(|path| store::expand_user_path(&path))
        .transpose()?;
    let exists = path.as_ref().is_some_and(|path| path.exists());
    let linked = state.is_some_and(|state| {
        state
            .targets
            .iter()
            .any(|target| target.id == entry.id && target.enabled)
    });

    Ok(TargetDetection {
        id: entry.id.to_owned(),
        name: entry.name.to_owned(),
        support: entry.support,
        path,
        exists,
        linked,
    })
}

fn read_state_if_initialized(paths: &StorePaths) -> DaloResult<Option<StateFile>> {
    if paths.state_file.exists() {
        Ok(Some(store::read_state(paths)?))
    } else {
        Ok(None)
    }
}

fn registry_entry(target_id: &str) -> DaloResult<&'static TargetRegistryEntry> {
    registry()
        .iter()
        .find(|entry| entry.id == target_id)
        .ok_or_else(|| DaloError::UnknownTarget {
            target: target_id.to_owned(),
        })
}

fn target_path(entry: &TargetRegistryEntry, path_override: Option<&Path>) -> DaloResult<PathBuf> {
    if let Some(path) = path_override {
        return store::expand_user_path(path);
    }

    let Some(default_path) = entry.default_path else {
        return Err(DaloError::TargetPathRequired {
            target: entry.id.to_owned(),
        });
    };

    store::expand_user_path(Path::new(default_path))
}

fn canonicalize_target_path(path: &Path) -> PathBuf {
    if let Ok(canonical) = path.canonicalize() {
        return canonical;
    }

    // The directory may not exist yet (notably during dry-run, which skips
    // `create_dir_all`). Canonicalize the parent and re-attach the final
    // component so a symlinked ancestor (e.g. `/var` -> `/private/var`) resolves
    // identically whether or not the leaf exists. This keeps the dry-run
    // "planned" canonical path equal to what the real run later persists.
    match (path.parent(), path.file_name()) {
        (Some(parent), Some(file_name)) => match parent.canonicalize() {
            Ok(canonical_parent) => canonical_parent.join(file_name),
            Err(_) => path.to_path_buf(),
        },
        _ => path.to_path_buf(),
    }
}

fn upsert_target_state(
    state: &mut StateFile,
    target_id: &str,
    path: &Path,
    canonical_path: &Path,
) -> DaloResult<TargetLinkStatus> {
    let existing = state
        .targets
        .iter_mut()
        .find(|target| target.id == target_id);

    let status = if let Some(target) = existing {
        if target.path == path && target.canonical_path == canonical_path && target.enabled {
            TargetLinkStatus::Existing
        } else {
            target.path = path.to_path_buf();
            target.canonical_path = canonical_path.to_path_buf();
            target.enabled = true;
            TargetLinkStatus::Updated
        }
    } else {
        state.targets.push(TargetState {
            id: target_id.to_owned(),
            path: path.to_path_buf(),
            canonical_path: canonical_path.to_path_buf(),
            enabled: true,
            extra: Default::default(),
        });
        TargetLinkStatus::Linked
    };

    state.rebuild_materialization_dirs()?;
    Ok(status)
}

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

    #[test]
    fn registry_should_include_v1_targets() {
        let ids = registry().iter().map(|entry| entry.id).collect::<Vec<_>>();

        assert_eq!(
            ids,
            [
                "codex", "claude", "openclaw", "hermes", "generic", "cursor", "opencode",
            ]
        );
    }

    #[test]
    fn link_target_should_dedupe_shared_physical_directory() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        let shared_target = temp_dir.path().join("skills");
        store::init_store(store_root.clone(), false).expect("init should succeed");

        link_target(&store_root, "codex", Some(&shared_target), false)
            .expect("codex link should succeed");
        link_target(&store_root, "openclaw", Some(&shared_target), false)
            .expect("openclaw link should succeed");

        let state =
            store::read_state(&StorePaths::new(store_root)).expect("state should be readable");

        assert_eq!(state.targets.len(), 2);
        assert_eq!(state.materialization_dirs.len(), 1);
        assert_eq!(
            state.materialization_dirs[0].logical_targets,
            ["codex".to_owned(), "openclaw".to_owned()]
        );
    }

    #[test]
    fn link_target_should_report_stable_canonical_path_between_dry_run_and_real_run() {
        use std::os::unix::fs as unix_fs;

        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        store::init_store(store_root.clone(), false).expect("init should succeed");
        // A symlinked parent means the not-yet-created leaf path differs from its
        // canonical form. Dry-run (which skips dir creation) must still report the
        // same canonical path the real run later persists.
        let real_parent = temp_dir.path().join("real");
        std::fs::create_dir_all(&real_parent).expect("real parent should be created");
        let linked_parent = temp_dir.path().join("linked");
        unix_fs::symlink(&real_parent, &linked_parent).expect("symlink should be created");
        let target = linked_parent.join("skills");

        let planned = link_target(&store_root, "codex", Some(&target), true)
            .expect("dry-run link should succeed");
        let applied = link_target(&store_root, "codex", Some(&target), false)
            .expect("real link should succeed");

        assert_eq!(planned.canonical_path, applied.canonical_path);
    }

    #[test]
    fn link_target_should_read_store_before_creating_target_dir() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("missing-store");
        let target = temp_dir.path().join("skills");

        let error = link_target(&store_root, "codex", Some(&target), false)
            .expect_err("link should require an initialized store");

        assert!(matches!(error, DaloError::StoreNotInitialized { .. }));
        assert!(!target.exists());
    }

    #[test]
    fn link_target_should_not_create_directory_when_metadata_merge_fails() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        let shared_target = temp_dir.path().join("shared-skills");
        store::init_store(store_root.clone(), false).expect("init should succeed");
        let paths = StorePaths::new(store_root.clone());
        let state = conflicting_future_directory_state(temp_dir.path(), &shared_target);
        store::write_state(&paths, &state).expect("conflicting future state should be written");

        let error = link_target(&store_root, "codex", Some(&shared_target), false)
            .expect_err("lossy metadata merge should block link");

        assert!(matches!(error, DaloError::StateMetadataConflict { .. }));
        assert!(!shared_target.exists());
        assert_eq!(
            store::read_state(&paths).expect("state should remain readable"),
            state
        );
    }

    #[test]
    fn unlink_target_should_drop_unrelated_conflicting_directory_metadata() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        let shared_target = temp_dir.path().join("shared-skills");
        store::init_store(store_root.clone(), false).expect("init should succeed");
        let paths = StorePaths::new(store_root.clone());
        let state = conflicting_future_directory_state(temp_dir.path(), &shared_target);
        store::write_state(&paths, &state).expect("conflicting future state should be written");

        let report = unlink_target(&store_root, "codex", false)
            .expect("unrelated metadata must not wedge target removal");
        let updated = store::read_state(&paths).expect("updated state should be readable");

        assert_eq!(report.status, TargetUnlinkStatus::Unlinked);
        assert!(updated.targets.iter().all(|target| target.id != "codex"));
        assert_eq!(updated.materialization_dirs.len(), 1);
        assert_eq!(updated.materialization_dirs[0].path, shared_target);
        assert_eq!(
            updated.materialization_dirs[0].logical_targets,
            ["claude".to_owned(), "openclaw".to_owned()]
        );
        assert!(
            !updated.materialization_dirs[0]
                .extra
                .contains_key("future_directory_field")
        );
    }

    #[test]
    fn unlink_target_dry_run_should_report_missing_for_unlinked_target() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        store::init_store(store_root.clone(), false).expect("init should succeed");

        let report =
            unlink_target(&store_root, "codex", true).expect("dry-run unlink should inspect state");

        assert_eq!(report.status, TargetUnlinkStatus::Missing);
    }

    #[test]
    fn link_generic_should_require_path() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        store::init_store(store_root.clone(), false).expect("init should succeed");

        let error = link_target(&store_root, "generic", None, false)
            .expect_err("generic should require a path");

        assert_eq!(
            error.to_string(),
            "target `generic` requires an explicit path"
        );
    }

    fn conflicting_future_directory_state(root: &Path, shared_target: &Path) -> StateFile {
        let mut state = StateFile::empty();
        state.targets = vec![
            TargetState {
                id: "codex".to_owned(),
                path: root.join("old-codex"),
                canonical_path: root.join("old-codex"),
                enabled: true,
                extra: Default::default(),
            },
            TargetState {
                id: "claude".to_owned(),
                path: root.join("old-claude"),
                canonical_path: root.join("old-claude"),
                enabled: true,
                extra: Default::default(),
            },
            TargetState {
                id: "openclaw".to_owned(),
                path: root.join("old-openclaw"),
                canonical_path: root.join("old-openclaw"),
                enabled: true,
                extra: Default::default(),
            },
        ];
        state
            .rebuild_materialization_dirs()
            .expect("initial directories should rebuild");
        for (target_id, value) in [("claude", "claude value"), ("openclaw", "openclaw value")] {
            state
                .materialization_dirs
                .iter_mut()
                .find(|directory| directory.logical_targets == [target_id.to_owned()])
                .expect("target directory should exist")
                .extra
                .insert(
                    "future_directory_field".to_owned(),
                    toml::Value::String(value.to_owned()),
                );
        }
        for target in state
            .targets
            .iter_mut()
            .filter(|target| target.id != "codex")
        {
            target.path = shared_target.to_path_buf();
            target.canonical_path = shared_target.to_path_buf();
        }
        state
    }
}