claude-hindsight 2.4.0

20/20 hindsight for your Claude Code sessions
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
//! Agent & Skill discovery across global, per-project, and plugin directories.
//!
//! Scans:
//! 1. Global: `~/.claude/agents/*.md`, `~/.claude/agents/*/AGENTS.md`,
//!    `~/.claude/skills/*/SKILL.md`
//! 2. Per-project: For each encoded project dir in `claude_dirs`, decode to real path,
//!    then scan `.claude/agents/`, `.agents/agents/`, `.claude/skills/`, `.agents/skills/`
//!    (symlink-aware dedup via canonical paths)
//! 3. Plugins: `~/.claude/plugins/**/agents/*.md`, `~/.claude/plugins/**/skills/*/SKILL.md`

use super::parser::{self, AgentConfig, SkillConfig, SkillReference};
use serde::Serialize;
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

/// All copies of an agent that share the same name across different scopes.
#[derive(Serialize)]
pub struct AgentGroup {
    pub name: String,
    /// `true` when every copy has byte-identical body content.
    pub identical: bool,
    pub items: Vec<AgentConfig>,
}

/// All copies of a skill that share the same name across different scopes.
#[derive(Serialize)]
pub struct SkillGroup {
    pub name: String,
    /// `true` when every copy has byte-identical body content.
    pub identical: bool,
    pub items: Vec<SkillConfig>,
}

fn home_dir() -> Option<PathBuf> {
    dirs::home_dir()
}

fn claude_home() -> Option<PathBuf> {
    home_dir().map(|h| h.join(".claude"))
}

/// Decode an encoded directory name back to a real filesystem path.
///
/// Claude Code encodes paths by replacing `/` with `-`, so
/// `-Users-codestz-Documents-PersonalProjects-claude-hindsight`
/// means `/Users/codestz/Documents/PersonalProjects/claude-hindsight`.
///
/// Since directory names can contain literal dashes (e.g. `claude-hindsight`),
/// we can't just replace all dashes with `/`. Instead we greedily walk the
/// filesystem: at each segment boundary (dash) we check if extending the
/// current segment (keeping the dash literal) matches an existing directory,
/// or if starting a new path component matches. We prefer the longest existing
/// path.
fn decode_dir_name(encoded: &str) -> PathBuf {
    let stripped = match encoded.strip_prefix('-') {
        Some(s) => s,
        None => return PathBuf::from(encoded),
    };

    let parts: Vec<&str> = stripped.split('-').collect();
    if parts.is_empty() {
        return PathBuf::from(encoded);
    }

    // Greedy: build path by trying to join dashes into the current segment
    // when the slash interpretation doesn't lead to existing dirs.
    fn solve(parts: &[&str], idx: usize, current: &Path) -> Option<PathBuf> {
        if idx >= parts.len() {
            return if current.exists() { Some(current.to_path_buf()) } else { None };
        }

        // Try accumulating segments with dashes (literal dash in dir name)
        // from longest to shortest
        for end in (idx + 1..=parts.len()).rev() {
            let segment = parts[idx..end].join("-");
            let candidate = current.join(&segment);
            if candidate.exists() {
                if end == parts.len() {
                    return Some(candidate);
                }
                if let Some(result) = solve(parts, end, &candidate) {
                    return Some(result);
                }
            }
        }

        // Single segment as path component (may not exist yet — last resort)
        let candidate = current.join(parts[idx]);
        solve(parts, idx + 1, &candidate)
    }

    let root = PathBuf::from("/");
    solve(&parts, 0, &root).unwrap_or_else(|| {
        // Fallback: naive replacement (best effort)
        PathBuf::from(format!("/{}", stripped.replace('-', "/")))
    })
}

/// Scan a directory for agent definitions.
///
/// Supports two layouts:
/// - Flat files: `agents/*.md` (e.g. `agents/reviewer.md`)
/// - Subdirectories: `agents/*/AGENTS.md` (e.g. `agents/data-researcher/AGENTS.md`)
fn scan_agents_dir(dir: &Path, scope: &str, project_name: Option<&str>) -> Vec<AgentConfig> {
    let mut agents = Vec::new();
    let entries = match fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return agents,
    };

    for entry in entries.flatten() {
        let path = entry.path();

        if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("md") {
            // Flat file: agents/reviewer.md
            if let Ok(content) = fs::read_to_string(&path) {
                if let Some(agent) = parser::parse_agent(
                    &content,
                    &path.to_string_lossy(),
                    scope,
                    project_name,
                ) {
                    agents.push(agent);
                }
            }
        } else if path.is_dir() {
            // Subdirectory: agents/data-researcher/AGENTS.md
            let agent_file = path.join("AGENTS.md");
            if agent_file.is_file() {
                if let Ok(content) = fs::read_to_string(&agent_file) {
                    if let Some(agent) = parser::parse_agent(
                        &content,
                        &agent_file.to_string_lossy(),
                        scope,
                        project_name,
                    ) {
                        agents.push(agent);
                    }
                }
            }
        }
    }
    agents
}

/// Scan a skill directory for `references/` and `rules/` subdirectories containing `.md` files.
fn scan_skill_references(skill_dir: &Path) -> Vec<SkillReference> {
    let mut refs = Vec::new();
    for (subdir, category) in &[("references", "reference"), ("rules", "rule")] {
        let dir = skill_dir.join(subdir);
        if dir.is_dir() {
            if let Ok(entries) = fs::read_dir(&dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("md") {
                        if let Ok(content) = fs::read_to_string(&path) {
                            let name = path
                                .file_stem()
                                .and_then(|s| s.to_str())
                                .unwrap_or("unknown")
                                .to_string();
                            refs.push(SkillReference {
                                name,
                                path: path.to_string_lossy().to_string(),
                                content,
                                category: category.to_string(),
                            });
                        }
                    }
                }
            }
        }
    }
    refs.sort_by(|a, b| a.name.cmp(&b.name));
    refs
}

/// Scan a directory for `*/SKILL.md` files and parse each as a skill.
fn scan_skills_dir(dir: &Path, scope: &str, project_name: Option<&str>) -> Vec<SkillConfig> {
    let mut skills = Vec::new();
    let entries = match fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return skills,
    };

    for entry in entries.flatten() {
        let skill_dir = entry.path();
        if skill_dir.is_dir() {
            let skill_file = skill_dir.join("SKILL.md");
            if skill_file.is_file() {
                if let Ok(content) = fs::read_to_string(&skill_file) {
                    if let Some(mut skill) = parser::parse_skill(
                        &content,
                        &skill_file.to_string_lossy(),
                        scope,
                        project_name,
                    ) {
                        skill.references = scan_skill_references(&skill_dir);
                        skills.push(skill);
                    }
                }
            }
        }
    }
    skills
}

/// Discover all agents from global, per-project, and plugin directories.
pub fn discover_agents() -> Vec<AgentConfig> {
    let mut all = Vec::new();

    let Some(claude) = claude_home() else {
        return all;
    };

    // 1. Global agents: ~/.claude/agents/*.md
    let global_agents = claude.join("agents");
    all.extend(scan_agents_dir(&global_agents, "global", None));

    // 2. Per-project agents
    let config = crate::config::Config::load().unwrap_or_default();
    let home = home_dir().unwrap_or_default();

    for dir_cfg in &config.paths.claude_dirs {
        let expanded = if let Some(stripped) = dir_cfg.path.strip_prefix("~/") {
            home.join(stripped)
        } else {
            PathBuf::from(&dir_cfg.path)
        };

        let entries = match fs::read_dir(&expanded) {
            Ok(e) => e,
            Err(_) => continue,
        };

        for entry in entries.flatten() {
            let project_dir = entry.path();
            if !project_dir.is_dir() {
                continue;
            }

            let dir_name = project_dir
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or("");

            // Decode encoded dir name to real path
            let real_path = decode_dir_name(dir_name);

            // Extract short project name (last segment)
            let project_name = real_path
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or(dir_name);

            // Scan <real_project_path>/.claude/agents/ and .agents/agents/
            // Deduplicate by canonical path (handles symlinks)
            let mut seen_paths: HashSet<PathBuf> = HashSet::new();
            for agents_dir in &[
                real_path.join(".claude").join("agents"),
                real_path.join(".agents").join("agents"),
            ] {
                let canonical = agents_dir.canonicalize().unwrap_or_else(|_| agents_dir.clone());
                if seen_paths.insert(canonical) {
                    all.extend(scan_agents_dir(agents_dir, project_name, Some(project_name)));
                }
            }
        }
    }

    // 3. Plugin agents: ~/.claude/plugins/*/agents/*.md
    let plugins_dir = claude.join("plugins");
    if plugins_dir.is_dir() {
        if let Ok(entries) = fs::read_dir(&plugins_dir) {
            for entry in entries.flatten() {
                let plugin_dir = entry.path();
                if plugin_dir.is_dir() {
                    let plugin_name = plugin_dir
                        .file_name()
                        .and_then(|s| s.to_str())
                        .unwrap_or("unknown");
                    let agents_dir = plugin_dir.join("agents");
                    all.extend(scan_agents_dir(&agents_dir, &format!("plugin:{plugin_name}"), None));
                }
            }
        }
    }

    // Dedup by canonical file path so that the same physical file reached via
    // different symlinks or duplicate claude_dirs entries is only kept once.
    let mut seen: HashSet<PathBuf> = HashSet::new();
    all.retain(|item| {
        let canonical = fs::canonicalize(&item.file_path)
            .unwrap_or_else(|_| PathBuf::from(&item.file_path));
        seen.insert(canonical)
    });

    // Sort by name for consistent output
    all.sort_by(|a, b| a.name.cmp(&b.name));
    all
}

/// Discover all skills from global, per-project, and plugin directories.
pub fn discover_skills() -> Vec<SkillConfig> {
    let mut all = Vec::new();

    let Some(claude) = claude_home() else {
        return all;
    };

    // 1. Global skills: ~/.claude/skills/*/SKILL.md
    let global_skills = claude.join("skills");
    all.extend(scan_skills_dir(&global_skills, "global", None));

    // 2. Per-project skills
    let config = crate::config::Config::load().unwrap_or_default();
    let home = home_dir().unwrap_or_default();

    for dir_cfg in &config.paths.claude_dirs {
        let expanded = if let Some(stripped) = dir_cfg.path.strip_prefix("~/") {
            home.join(stripped)
        } else {
            PathBuf::from(&dir_cfg.path)
        };

        let entries = match fs::read_dir(&expanded) {
            Ok(e) => e,
            Err(_) => continue,
        };

        for entry in entries.flatten() {
            let project_dir = entry.path();
            if !project_dir.is_dir() {
                continue;
            }

            let dir_name = project_dir
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or("");

            let real_path = decode_dir_name(dir_name);
            let project_name = real_path
                .file_name()
                .and_then(|s| s.to_str())
                .unwrap_or(dir_name);

            // Scan <real_project_path>/.claude/skills/ and .agents/skills/
            // Deduplicate by canonical path (handles symlinks)
            let mut seen_paths: HashSet<PathBuf> = HashSet::new();
            for skills_dir in &[
                real_path.join(".claude").join("skills"),
                real_path.join(".agents").join("skills"),
            ] {
                let canonical = skills_dir.canonicalize().unwrap_or_else(|_| skills_dir.clone());
                if seen_paths.insert(canonical) {
                    all.extend(scan_skills_dir(skills_dir, project_name, Some(project_name)));
                }
            }
        }
    }

    // 3. Plugin skills: ~/.claude/plugins/*/skills/*/SKILL.md
    let plugins_dir = claude.join("plugins");
    if plugins_dir.is_dir() {
        if let Ok(entries) = fs::read_dir(&plugins_dir) {
            for entry in entries.flatten() {
                let plugin_dir = entry.path();
                if plugin_dir.is_dir() {
                    let plugin_name = plugin_dir
                        .file_name()
                        .and_then(|s| s.to_str())
                        .unwrap_or("unknown");
                    let skills_dir = plugin_dir.join("skills");
                    all.extend(scan_skills_dir(&skills_dir, &format!("plugin:{plugin_name}"), None));
                }
            }
        }
    }

    // Dedup by canonical file path so that the same physical file reached via
    // different symlinks or duplicate claude_dirs entries is only kept once.
    let mut seen: HashSet<PathBuf> = HashSet::new();
    all.retain(|item| {
        let canonical = fs::canonicalize(&item.file_path)
            .unwrap_or_else(|_| PathBuf::from(&item.file_path));
        seen.insert(canonical)
    });

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

/// Group a flat (already-sorted, already-deduped) list of agents by name.
pub fn group_agents(agents: Vec<AgentConfig>) -> Vec<AgentGroup> {
    let mut groups: Vec<AgentGroup> = Vec::new();
    for agent in agents {
        if let Some(g) = groups.last_mut().filter(|g| g.name == agent.name) {
            g.items.push(agent);
        } else {
            groups.push(AgentGroup { name: agent.name.clone(), identical: true, items: vec![agent] });
        }
    }
    // Compute identical flag now that all items per group are collected
    for g in &mut groups {
        g.identical = g.items.windows(2).all(|w| w[0].body == w[1].body);
    }
    groups
}

/// Group a flat (already-sorted, already-deduped) list of skills by name.
pub fn group_skills(skills: Vec<SkillConfig>) -> Vec<SkillGroup> {
    let mut groups: Vec<SkillGroup> = Vec::new();
    for skill in skills {
        if let Some(g) = groups.last_mut().filter(|g| g.name == skill.name) {
            g.items.push(skill);
        } else {
            groups.push(SkillGroup { name: skill.name.clone(), identical: true, items: vec![skill] });
        }
    }
    for g in &mut groups {
        g.identical = g.items.windows(2).all(|w| w[0].body == w[1].body);
    }
    groups
}

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

    #[test]
    fn test_decode_dir_name_no_prefix() {
        let decoded = decode_dir_name("my-project");
        assert_eq!(decoded, PathBuf::from("my-project"));
    }

    #[test]
    fn test_decode_dir_name_fallback() {
        // When path doesn't exist on disk, falls back to naive replacement
        let decoded = decode_dir_name("-nonexistent-path-here");
        assert_eq!(decoded, PathBuf::from("/nonexistent/path/here"));
    }
}