dalo 1.11.1

Your team's agent skills, versioned like code. Review, pin, and sync skills, instructions, and hooks into every agent.
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
//! Agent target registry and detection.

use std::collections::BTreeMap;
use std::env;
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: its skill directory and symlink discovery are
    /// verified against a named agent release in `docs/agents.md`.
    Supported,
    /// Known but unverified target. No built-in target uses this level in V1;
    /// it stays available for targets registered before verification.
    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,
    /// Linked path when configured, otherwise the 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>,
}

/// One verified native instruction-file destination shared by logical targets.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstructionFileDestination {
    /// Logical target IDs that resolve to this physical file.
    pub logical_targets: Vec<String>,
    /// Effective physical instruction-file path.
    pub path: PathBuf,
}

/// 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,
}

/// Built-in target IDs as the `target link` hints spell them.
///
/// [`registry`] is the source of truth; `link_hint_should_name_every_builtin`
/// keeps this list and the CLI long help in step with it, so a newly supported
/// target cannot be left out of the command Dalo tells people to run.
pub const LINK_HINT_TARGETS: &str = "codex|claude|cursor|openclaw|hermes|opencode|generic";

/// 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: "cursor",
            name: "Cursor",
            default_path: Some("~/.cursor/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: "opencode",
            name: "OpenCode",
            default_path: Some("~/.config/opencode/skills"),
            support: TargetSupport::Supported,
        },
        TargetRegistryEntry {
            id: "generic",
            name: "Generic folder",
            default_path: None,
            support: TargetSupport::Supported,
        },
    ]
}

/// Resolve logical agent targets to verified native user-level instruction files.
///
/// Physical destinations are de-duplicated after resolving existing symlinks.
/// Targets without a verified native mapping fail closed instead of guessing.
pub fn resolve_instruction_files(
    target_ids: &[String],
) -> DaloResult<Vec<InstructionFileDestination>> {
    let default_config_dir = |name: &str| {
        env::var_os("HOME")
            .map(PathBuf::from)
            .map(|home| home.join(name))
            .ok_or_else(|| DaloError::StateError {
                reason: "HOME is required to resolve native instruction files".to_owned(),
            })
    };
    let mut destinations = BTreeMap::<PathBuf, Vec<String>>::new();

    for target_id in target_ids {
        registry_entry(target_id)?;
        let path = match target_id.as_str() {
            "codex" => match env::var_os("CODEX_HOME") {
                Some(path) => PathBuf::from(path),
                None => default_config_dir(".codex")?,
            }
            .join("AGENTS.md"),
            "claude" => match env::var_os("CLAUDE_CONFIG_DIR") {
                Some(path) => PathBuf::from(path),
                None => default_config_dir(".claude")?,
            }
            .join("CLAUDE.md"),
            _ => {
                return Err(DaloError::InvalidArgument {
                    reason: format!(
                        "target `{target_id}` has no verified native instruction-file mapping; use an explicit file instead"
                    ),
                });
            }
        };
        let path = store::comparable_path(&store::absolute_path(&path)?);
        destinations
            .entry(path)
            .or_default()
            .push(target_id.clone());
    }

    Ok(destinations
        .into_iter()
        .map(|(path, mut logical_targets)| {
            logical_targets.sort();
            logical_targets.dedup();
            InstructionFileDestination {
                logical_targets,
                path,
            }
        })
        .collect())
}

/// 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 = fs::symlink_metadata(&path).is_ok();

    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)?;
        let created_dirs = if existed_before {
            if !fs::metadata(&path).is_ok_and(|metadata| metadata.is_dir()) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::NotADirectory,
                    format!("target path `{}` is not a directory", path.display()),
                )
                .into());
            }
            Vec::new()
        } else {
            create_target_directories(&path)?
        };
        if let Err(error) = store::write_state(&paths, state) {
            remove_created_target_directories(&created_dirs);
            return Err(error);
        }
        status
    };

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

fn missing_target_directories(path: &Path) -> Vec<PathBuf> {
    let mut missing = Vec::new();
    let mut current = Some(path);
    while let Some(candidate) = current.filter(|path| !path.as_os_str().is_empty()) {
        if fs::symlink_metadata(candidate).is_ok() {
            break;
        }
        missing.push(candidate.to_path_buf());
        current = candidate.parent();
    }
    missing.reverse();
    missing
}

fn create_target_directories(path: &Path) -> DaloResult<Vec<PathBuf>> {
    let mut created = Vec::new();
    for candidate in missing_target_directories(path) {
        match fs::create_dir(&candidate) {
            Ok(()) => created.push(candidate),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(error) => {
                remove_created_target_directories(&created);
                return Err(error.into());
            }
        }
    }

    if !fs::metadata(path).is_ok_and(|metadata| metadata.is_dir()) {
        remove_created_target_directories(&created);
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotADirectory,
            format!("target path `{}` is not a directory", path.display()),
        )
        .into());
    }

    Ok(created)
}

fn remove_created_target_directories(created: &[PathBuf]) {
    for path in created.iter().rev() {
        // Removing only directories that this operation observed as missing
        // avoids touching pre-existing parents. Stop at the first non-empty
        // or otherwise unavailable directory so concurrent content is kept.
        if fs::remove_dir(path).is_err() {
            break;
        }
    }
}

/// 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 linked_target = state.and_then(|state| {
        state
            .targets
            .iter()
            .find(|target| target.id == entry.id && target.enabled)
    });
    let path = if let Some(target) = linked_target {
        Some(target.path.clone())
    } else {
        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 = linked_target.is_some();

    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::unknown_target(
                target_id,
                registry().iter().map(|entry| entry.id.to_owned()).collect(),
            )
        })
}

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", "cursor", "openclaw", "hermes", "opencode", "generic",
            ]
        );
    }

    #[test]
    fn cursor_target_should_use_the_verified_user_skill_directory() {
        let entry = registry_entry("cursor").expect("Cursor should be a built-in target");

        assert_eq!(entry.name, "Cursor");
        assert_eq!(entry.default_path, Some("~/.cursor/skills"));
        assert_eq!(entry.support, TargetSupport::Supported);
    }

    #[test]
    fn link_hint_should_name_every_builtin() {
        // The hints told people to run
        // The target link hint once lagged behind the built-in registry, so the command Dalo prints
        // has to be derived from the registry, not maintained beside it.
        let ids = registry().iter().map(|entry| entry.id).collect::<Vec<_>>();

        assert_eq!(
            LINK_HINT_TARGETS,
            ids.join("|"),
            "the target link hint fell behind the registry"
        );
        assert!(
            crate::cli::AFTER_LONG_HELP
                .contains(&format!("dalo target link <{LINK_HINT_TARGETS}> [path]")),
            "the CLI long help fell behind the registry"
        );
    }

    #[test]
    fn registry_should_ship_only_verified_targets() {
        for entry in registry() {
            assert_eq!(
                entry.support,
                TargetSupport::Supported,
                "target `{}` ships an unverified support level",
                entry.id
            );
        }
    }

    #[test]
    fn registry_should_give_every_agent_target_a_default_path() {
        for entry in registry().iter().filter(|entry| entry.id != "generic") {
            assert!(
                entry.default_path.is_some(),
                "target `{}` ships without a default skill path",
                entry.id
            );
        }
    }

    #[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 link_target_cleanup_should_remove_new_empty_ancestors_only() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let existing_parent = temp_dir.path().join("existing");
        let target = existing_parent.join("new/deep/skills");
        fs::create_dir_all(&existing_parent).expect("existing parent should be created");

        let created = missing_target_directories(&target);
        fs::create_dir_all(&target).expect("target hierarchy should be created");
        remove_created_target_directories(&created);

        assert!(existing_parent.is_dir());
        assert!(!target.exists());
        assert!(!existing_parent.join("new").exists());
    }

    #[test]
    fn link_target_should_reject_a_broken_symlink_without_recording_state() {
        let temp_dir = tempfile::tempdir().expect("tempdir should be created");
        let store_root = temp_dir.path().join("store");
        let target = temp_dir.path().join("broken-skills");
        store::init_store(store_root.clone(), false).expect("init should succeed");
        std::os::unix::fs::symlink(temp_dir.path().join("missing"), &target)
            .expect("broken target symlink should be created");

        let error = link_target(&store_root, "codex", Some(&target), false)
            .expect_err("broken target symlink should be rejected");

        assert!(error.to_string().contains("not a directory"));
        assert!(
            store::read_state(&StorePaths::new(store_root))
                .expect("state should remain readable")
                .targets
                .is_empty()
        );
    }

    #[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
    }
}