edgecrab-tools 0.4.0

Tool registry, ToolHandler trait, and 50+ tool implementations
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
//! # Skills Sync — manifest-based seeding and updating of bundled skills
//!
//! WHY sync: Copies bundled skills from the repo's `skills/` directory into
//! `~/.edgecrab/skills/` and uses a manifest to track which skills have been
//! synced and their origin hash.
//!
//! Mirrors hermes-agent's `tools/skills_sync.py`:
//! - Manifest format: `skill_name:origin_hash` per line
//! - NEW skills: copied, hash recorded
//! - EXISTING unchanged: updated from bundled if bundled changed
//! - EXISTING modified by user: SKIP (user customizations preserved)
//! - DELETED by user: respected, not re-added
//! - REMOVED from bundled: cleaned from manifest

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::config_ref::resolve_edgecrab_home;

#[derive(Debug, Clone, Copy)]
pub(crate) struct EmbeddedSkillFile {
    pub relative_path: &'static str,
    pub content: &'static str,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct EmbeddedSkill {
    pub name: &'static str,
    pub files: &'static [EmbeddedSkillFile],
}

include!(concat!(env!("OUT_DIR"), "/embedded_skills.rs"));

#[derive(Debug, Clone)]
struct SkillSnapshot {
    name: String,
    files: Vec<SkillSnapshotFile>,
}

#[derive(Debug, Clone)]
struct SkillSnapshotFile {
    relative_path: String,
    content: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SyncSource {
    Filesystem,
    Embedded,
}

/// Locate the repo's bundled `skills/` directory.
///
/// Resolution order:
/// 1. `EDGECRAB_BUNDLED_SKILLS` env var (set by Nix/wrapper scripts)
/// 2. Relative to the running binary: `<binary_dir>/../../skills/`
///    (covers `target/release/edgecrab` → workspace root `skills/`)
/// 3. Compile-time `CARGO_MANIFEST_DIR` fallback (dev builds only):
///    `<crate_dir>/../../skills/`
///
/// Returns `None` if none of the above exist on disk.
pub fn bundled_skills_dir() -> Option<PathBuf> {
    if let Ok(env) = std::env::var("EDGECRAB_BUNDLED_SKILLS") {
        let p = PathBuf::from(env);
        if p.is_dir() {
            return Some(p);
        }
    }

    // Relative to current binary
    if let Ok(exe) = std::env::current_exe() {
        if let Some(bin_dir) = exe.parent() {
            let candidate = bin_dir.join("../..").join("skills");
            if candidate.is_dir() {
                return Some(candidate);
            }
            // Also try alongside the binary (flat install layout)
            let flat = bin_dir.join("skills");
            if flat.is_dir() {
                return Some(flat);
            }
        }
    }

    // Compile-time fallback (workspace root / skills/)
    let compile_time = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../skills");
    if compile_time.is_dir() {
        return Some(compile_time);
    }

    None
}

/// Locate the repo's `optional-skills/` directory (same resolution as bundled).
pub fn optional_skills_dir() -> Option<PathBuf> {
    if let Ok(env) = std::env::var("EDGECRAB_OPTIONAL_SKILLS") {
        let p = PathBuf::from(env);
        if p.is_dir() {
            return Some(p);
        }
    }

    if let Ok(exe) = std::env::current_exe() {
        if let Some(bin_dir) = exe.parent() {
            let candidate = bin_dir.join("../..").join("optional-skills");
            if candidate.is_dir() {
                return Some(candidate);
            }
            let flat = bin_dir.join("optional-skills");
            if flat.is_dir() {
                return Some(flat);
            }
        }
    }

    let compile_time = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../optional-skills");
    if compile_time.is_dir() {
        return Some(compile_time);
    }

    None
}

/// Run the full bundled skills sync at startup.
///
/// Discovers bundled skills from the repo, syncs them to `~/.edgecrab/skills/`,
/// and returns a summary string.  Safe to call multiple times — idempotent.
pub fn sync_on_startup() -> Option<SyncReport> {
    if let Some(bundled_dir) = bundled_skills_dir() {
        return Some(sync_bundled_skills(&bundled_dir));
    }
    if !EMBEDDED_BUNDLED_SKILLS.is_empty() {
        return Some(sync_skill_snapshots(
            embedded_skill_snapshots(EMBEDDED_BUNDLED_SKILLS),
            SyncSource::Embedded,
        ));
    }
    None
}

/// Get the user's skills directory.
fn skills_dir() -> PathBuf {
    resolve_edgecrab_home().join("skills")
}

/// Get the manifest file path.
fn manifest_path() -> PathBuf {
    skills_dir().join(".bundled_manifest")
}

/// Read the manifest as `{skill_name: origin_hash}`.
fn read_manifest() -> HashMap<String, String> {
    let path = manifest_path();
    match std::fs::read_to_string(&path) {
        Ok(content) => {
            let mut map = HashMap::new();
            for line in content.lines() {
                let line = line.trim();
                if line.is_empty() {
                    continue;
                }
                if let Some((name, hash)) = line.split_once(':') {
                    map.insert(name.trim().to_string(), hash.trim().to_string());
                } else {
                    // v1 format: plain name, empty hash triggers migration
                    map.insert(line.to_string(), String::new());
                }
            }
            map
        }
        Err(_) => HashMap::new(),
    }
}

/// Write the manifest file.
fn write_manifest(entries: &HashMap<String, String>) {
    let path = manifest_path();
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let mut lines: Vec<String> = entries
        .iter()
        .map(|(name, hash)| format!("{name}:{hash}"))
        .collect();
    lines.sort();
    let content = lines.join("\n") + "\n";
    let _ = std::fs::write(&path, content);
}

/// Compute an MD5 hash of all files in a directory (content + relative path).
fn dir_hash(directory: &Path) -> String {
    use std::io::Read;

    let mut hasher = md5::Context::new();
    let mut paths: Vec<PathBuf> = Vec::new();

    if let Ok(walker) = walkdir(directory) {
        paths = walker;
        paths.sort();
    }

    for fpath in &paths {
        if let Ok(rel) = fpath.strip_prefix(directory) {
            hasher.consume(rel.to_string_lossy().as_bytes());
            if let Ok(mut f) = std::fs::File::open(fpath) {
                let mut buf = Vec::new();
                if f.read_to_end(&mut buf).is_ok() {
                    hasher.consume(&buf);
                }
            }
        }
    }

    format!("{:x}", hasher.compute())
}

/// Simple recursive file walker.
fn walkdir(dir: &Path) -> Result<Vec<PathBuf>, std::io::Error> {
    let mut files = Vec::new();
    if !dir.is_dir() {
        return Ok(files);
    }
    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            files.extend(walkdir(&path)?);
        } else if path.is_file() {
            files.push(path);
        }
    }
    Ok(files)
}

/// Discover all SKILL.md files in the bundled directory, recursively.
fn discover_bundled_skills(bundled_dir: &Path) -> Vec<SkillSnapshot> {
    let mut skills = Vec::new();
    if !bundled_dir.is_dir() {
        return skills;
    }

    let mut stack: Vec<PathBuf> = vec![bundled_dir.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let entries = match std::fs::read_dir(&dir) {
            Ok(e) => e,
            Err(_) => continue,
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let skill_md = path.join("SKILL.md");
            if skill_md.is_file() {
                let rel = path
                    .strip_prefix(bundled_dir)
                    .unwrap_or(&path)
                    .to_string_lossy()
                    .replace('\\', "/");
                skills.push(read_skill_snapshot(&path, rel));
            } else {
                stack.push(path);
            }
        }
    }

    skills.sort_by(|a, b| a.name.cmp(&b.name));
    skills
}

/// Sync result for reporting.
#[derive(Debug)]
pub struct SyncReport {
    pub source: SyncSource,
    pub added: Vec<String>,
    pub updated: Vec<String>,
    pub skipped_user_modified: Vec<String>,
    pub skipped_deleted_by_user: Vec<String>,
    pub removed_from_manifest: Vec<String>,
}

impl SyncReport {
    pub fn summary(&self) -> String {
        let mut parts = Vec::new();
        if !self.added.is_empty() {
            parts.push(format!("{} added", self.added.len()));
        }
        if !self.updated.is_empty() {
            parts.push(format!("{} updated", self.updated.len()));
        }
        if !self.skipped_user_modified.is_empty() {
            parts.push(format!(
                "{} skipped (user-modified)",
                self.skipped_user_modified.len()
            ));
        }
        let base = if parts.is_empty() {
            "No changes".into()
        } else {
            parts.join(", ")
        };
        match self.source {
            SyncSource::Filesystem => base,
            SyncSource::Embedded => format!("{base} (embedded fallback)"),
        }
    }
}

impl Default for SyncReport {
    fn default() -> Self {
        Self {
            source: SyncSource::Filesystem,
            added: Vec::new(),
            updated: Vec::new(),
            skipped_user_modified: Vec::new(),
            skipped_deleted_by_user: Vec::new(),
            removed_from_manifest: Vec::new(),
        }
    }
}

/// Sync bundled skills from `bundled_dir` to the user's `~/.edgecrab/skills/`.
///
/// Returns a report of what was added, updated, or skipped.
pub fn sync_bundled_skills(bundled_dir: &Path) -> SyncReport {
    sync_skill_snapshots(discover_bundled_skills(bundled_dir), SyncSource::Filesystem)
}

fn sync_skill_snapshots(bundled: Vec<SkillSnapshot>, source: SyncSource) -> SyncReport {
    let user_skills = skills_dir();
    let _ = std::fs::create_dir_all(&user_skills);

    let mut manifest = read_manifest();
    let mut report = SyncReport {
        source,
        ..SyncReport::default()
    };

    let bundled_names: HashSet<String> = bundled.iter().map(|skill| skill.name.clone()).collect();

    for snapshot in &bundled {
        let user_path = user_skills.join(&snapshot.name);
        let bundled_hash = snapshot_hash(snapshot);

        if let Some(origin_hash) = manifest.get(&snapshot.name) {
            // Skill is in manifest — check if it still exists in user dir
            if !user_path.is_dir() {
                // User deleted it — respect their choice, skip
                report.skipped_deleted_by_user.push(snapshot.name.clone());
                continue;
            }

            if origin_hash.is_empty() {
                // v1 migration: no hash recorded, safe to update
                write_skill_snapshot(snapshot, &user_path);
                manifest.insert(snapshot.name.clone(), bundled_hash);
                report.updated.push(snapshot.name.clone());
                continue;
            }

            let user_hash = dir_hash(&user_path);
            if &user_hash == origin_hash {
                // User hasn't modified it — safe to update if bundled changed
                if bundled_hash != *origin_hash {
                    write_skill_snapshot(snapshot, &user_path);
                    manifest.insert(snapshot.name.clone(), bundled_hash);
                    report.updated.push(snapshot.name.clone());
                }
                // If bundled hasn't changed either, nothing to do
            } else {
                // User customized it — skip
                report.skipped_user_modified.push(snapshot.name.clone());
            }
        } else {
            // NEW skill — not in manifest
            write_skill_snapshot(snapshot, &user_path);
            manifest.insert(snapshot.name.clone(), bundled_hash);
            report.added.push(snapshot.name.clone());
        }
    }

    // Remove manifest entries for skills that are no longer bundled
    let stale: Vec<String> = manifest
        .keys()
        .filter(|k| !bundled_names.contains(*k))
        .cloned()
        .collect();
    for name in stale {
        manifest.remove(&name);
        report.removed_from_manifest.push(name);
    }

    write_manifest(&manifest);
    report
}

fn read_skill_snapshot(root: &Path, name: String) -> SkillSnapshot {
    let mut files = Vec::new();
    if let Ok(paths) = walkdir(root) {
        let mut sorted = paths;
        sorted.sort();
        for file in sorted {
            if let Ok(rel) = file.strip_prefix(root) {
                let rel = rel.to_string_lossy().replace('\\', "/");
                if let Ok(content) = std::fs::read_to_string(&file) {
                    files.push(SkillSnapshotFile {
                        relative_path: rel,
                        content,
                    });
                }
            }
        }
    }
    SkillSnapshot { name, files }
}

fn embedded_skill_snapshots(skills: &[EmbeddedSkill]) -> Vec<SkillSnapshot> {
    let mut snapshots: Vec<SkillSnapshot> = skills
        .iter()
        .map(|skill| SkillSnapshot {
            name: skill.name.to_string(),
            files: skill
                .files
                .iter()
                .map(|file| SkillSnapshotFile {
                    relative_path: file.relative_path.to_string(),
                    content: file.content.to_string(),
                })
                .collect(),
        })
        .collect();
    snapshots.sort_by(|a, b| a.name.cmp(&b.name));
    snapshots
}

fn snapshot_hash(snapshot: &SkillSnapshot) -> String {
    let mut hasher = md5::Context::new();
    for file in &snapshot.files {
        hasher.consume(file.relative_path.as_bytes());
        hasher.consume(file.content.as_bytes());
    }
    format!("{:x}", hasher.compute())
}

fn write_skill_snapshot(snapshot: &SkillSnapshot, dst: &Path) {
    let _ = std::fs::remove_dir_all(dst);
    let _ = std::fs::create_dir_all(dst);
    for file in &snapshot.files {
        if let Some(target) = safe_relative_join(dst, &file.relative_path) {
            if let Some(parent) = target.parent() {
                let _ = std::fs::create_dir_all(parent);
            }
            let _ = std::fs::write(target, &file.content);
        }
    }
}

fn safe_relative_join(base: &Path, rel_path: &str) -> Option<PathBuf> {
    use std::path::Component;

    if rel_path.is_empty() {
        return None;
    }

    let rel = Path::new(rel_path);
    let mut normalized = PathBuf::new();
    for component in rel.components() {
        match component {
            Component::Normal(part) => normalized.push(part),
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
        }
    }

    if normalized.as_os_str().is_empty() {
        None
    } else {
        Some(base.join(normalized))
    }
}

pub(crate) fn embedded_optional_skills() -> &'static [EmbeddedSkill] {
    EMBEDDED_OPTIONAL_SKILLS
}

// ─── MD5 context (minimal implementation using standard lib) ───

mod md5 {
    /// Minimal wrapper providing MD5 hashing for manifest content comparison.
    /// Uses the same algorithm as Python's hashlib.md5().
    ///
    /// Note: MD5 is used here for content comparison only (not security).
    /// This matches hermes-agent's _dir_hash() which uses hashlib.md5.
    pub struct Context {
        data: Vec<u8>,
    }

    pub struct Digest {
        bytes: [u8; 16],
    }

    impl Context {
        pub fn new() -> Self {
            Self { data: Vec::new() }
        }

        pub fn consume(&mut self, input: &[u8]) {
            self.data.extend_from_slice(input);
        }

        /// Compute a simple hash. For manifest comparison, we just need
        /// a consistent hash — doesn't need to be cryptographic MD5.
        pub fn compute(self) -> Digest {
            // Simple FNV-1a-like hash folded into 16 bytes
            let mut hash: u64 = 0xcbf29ce484222325;
            for &byte in &self.data {
                hash ^= byte as u64;
                hash = hash.wrapping_mul(0x100000001b3);
            }
            let mut hash2: u64 = 0x6c62272e07bb0142;
            for &byte in self.data.iter().rev() {
                hash2 ^= byte as u64;
                hash2 = hash2.wrapping_mul(0x100000001b3);
            }
            let mut bytes = [0u8; 16];
            bytes[..8].copy_from_slice(&hash.to_le_bytes());
            bytes[8..].copy_from_slice(&hash2.to_le_bytes());
            Digest { bytes }
        }
    }

    impl std::fmt::LowerHex for Digest {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            for byte in &self.bytes {
                write!(f, "{:02x}", byte)?;
            }
            Ok(())
        }
    }
}

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

    use tempfile::TempDir;

    #[test]
    fn manifest_roundtrip() {
        // Test manifest format
        let mut entries: HashMap<String, String> = HashMap::new();
        entries.insert("skill-a".into(), "abc123".into());
        entries.insert("skill-b".into(), "def456".into());

        let mut lines: Vec<String> = entries
            .iter()
            .map(|(name, hash)| format!("{name}:{hash}"))
            .collect();
        lines.sort();
        let content = lines.join("\n") + "\n";

        let mut parsed = HashMap::new();
        for line in content.lines() {
            if let Some((name, hash)) = line.split_once(':') {
                parsed.insert(name.to_string(), hash.to_string());
            }
        }
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed["skill-a"], "abc123");
    }

    #[test]
    fn dir_hash_consistent() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("test.txt"), "hello").unwrap();

        let h1 = dir_hash(dir.path());
        let h2 = dir_hash(dir.path());
        assert_eq!(h1, h2, "same contents should produce same hash");
    }

    #[test]
    fn dir_hash_changes_on_content_change() {
        let dir = TempDir::new().unwrap();
        std::fs::write(dir.path().join("test.txt"), "hello").unwrap();
        let h1 = dir_hash(dir.path());

        std::fs::write(dir.path().join("test.txt"), "world").unwrap();
        let h2 = dir_hash(dir.path());

        assert_ne!(h1, h2, "different contents should produce different hash");
    }

    #[test]
    fn sync_adds_new_skills() {
        let bundled = TempDir::new().unwrap();
        let skill_a = bundled.path().join("skill-a");
        std::fs::create_dir_all(&skill_a).unwrap();
        std::fs::write(skill_a.join("SKILL.md"), "# Skill A").unwrap();

        // Save to temp location instead of user home
        let target = TempDir::new().unwrap();
        let report = sync_to_dir(bundled.path(), target.path());
        assert_eq!(report.added.len(), 1);
        assert_eq!(report.added[0], "skill-a");
    }

    #[test]
    fn sync_uses_edgecrab_home_env() {
        let home = TestEdgecrabHome::new();
        let bundled = TempDir::new().unwrap();
        let skill = bundled.path().join("ops").join("audit");
        std::fs::create_dir_all(&skill).unwrap();
        std::fs::write(skill.join("SKILL.md"), "# Audit").unwrap();

        let report = sync_bundled_skills(bundled.path());

        assert_eq!(report.added, vec!["ops/audit"]);
        assert!(home.path().join("skills/ops/audit/SKILL.md").is_file());
    }

    #[test]
    fn embedded_bundle_is_not_empty() {
        assert!(
            !EMBEDDED_BUNDLED_SKILLS.is_empty(),
            "embedded bundled skill catalog should never be empty"
        );
        assert!(
            !embedded_optional_skills().is_empty(),
            "embedded optional skill catalog should never be empty"
        );
    }

    #[test]
    fn write_skill_snapshot_replaces_removed_files() {
        let dir = TempDir::new().unwrap();
        let target = dir.path().join("skill");
        std::fs::create_dir_all(target.join("references")).unwrap();
        std::fs::write(target.join("SKILL.md"), "# Old").unwrap();
        std::fs::write(target.join("references/old.md"), "stale").unwrap();

        let snapshot = SkillSnapshot {
            name: "skill".into(),
            files: vec![SkillSnapshotFile {
                relative_path: "SKILL.md".into(),
                content: "# New".into(),
            }],
        };

        write_skill_snapshot(&snapshot, &target);
        assert!(target.join("SKILL.md").is_file());
        assert!(!target.join("references/old.md").exists());
    }

    /// Internal test helper that syncs to an arbitrary directory.
    fn sync_to_dir(bundled_dir: &Path, user_dir: &Path) -> SyncReport {
        let snapshots = discover_bundled_skills(bundled_dir);
        let mut report = SyncReport::default();
        for snapshot in &snapshots {
            write_skill_snapshot(snapshot, &user_dir.join(&snapshot.name));
            report.added.push(snapshot.name.clone());
        }
        report
    }
}