Skip to main content

rpi_cli/
resource_dirs.rs

1//! Resource-directory resolution + **project-wins dedupe** for skills and
2//! prompt templates. Mirrors the precedence contract from pi's
3//! `DefaultResourceLoader`/`package-manager` (`resource-loader.ts:676-681`,
4//! `package-manager.ts:178-181`): resources are ranked project=0/1 < user=2/3
5//! < package=4, and `addSkills`/`dedupePrompts` are **first-registration-wins**
6//! on name → loading project *before* global means **project wins** on
7//! collision (skills.ts:399-428), with a collision diagnostic naming the winner
8//! (kept) and loser (dropped) paths.
9//!
10//! rpi's library loaders (`rpi_harness::skills::load_skills`,
11//! `rpi_harness::prompt_templates::load_prompt_templates`) are **append-only**
12//! (no dedup-by-name) — they correctly mirror pi's *per-directory* discovery
13//! (SKILL.md-first / root-.md / subdir recursion for skills; non-recursive `.md`
14//! children for prompts) but leave the cross-directory merge to the caller. This
15//! module is that caller-side merge: load project dir then global dir, then
16//! dedupe first-wins-by-name so project wins.
17//!
18//! **Trust gate (v1 divergence):** pi gates project `SYSTEM.md` /
19//! `APPEND_SYSTEM.md` (and some project resources) behind
20//! `settingsManager.isProjectTrusted()`. rpi v1 has **no trust prompt**
21//! (`config.rs:349`: "does not gate any project resources behind trust in v1"),
22//! so project resources are read unconditionally here. A copied `.rpi/`
23//! directory drops in and works (the documented intent). Full trust gating is
24//! deferred.
25//!
26//! **Deferred (documented):** `.agents/skills` + `~/.agents/skills`;
27//! shadowed-context-file dedup (`findShadowedContextFile`); full structured
28//! winner/loser collision diagnostics (rpi v1 encodes collisions as a
29//! `SkillDiagnostic`/`PromptTemplateDiagnostic` with a descriptive message).
30
31use std::collections::HashMap;
32use std::path::{Path, PathBuf};
33use std::sync::Arc;
34
35use rpi_harness::prompt_templates::{
36    load_prompt_templates, LoadPromptTemplatesResult, PromptTemplateDiagnostic,
37    PromptTemplateDiagnosticCode,
38};
39use rpi_harness::skills::{load_skills, LoadSkillsResult, SkillDiagnostic, SkillDiagnosticCode};
40use rpi_harness::types::{PromptTemplate, Skill};
41use rpi_tools::env::ExecutionEnv;
42
43/// The project-local rpi configuration directory.
44pub const PROJECT_CONFIG_DIR_NAME: &str = ".rpi";
45
46/// Resolve the preferred project-local resource subdir `<cwd>/.rpi/<sub>`.
47pub fn project_dir(cwd: &Path, sub: &str) -> PathBuf {
48    cwd.join(PROJECT_CONFIG_DIR_NAME).join(sub)
49}
50
51/// Resolve project-local resource dirs. Only `.rpi` is read.
52pub fn project_dirs(cwd: &Path, sub: &str) -> Vec<PathBuf> {
53    vec![project_dir(cwd, sub)]
54}
55
56/// Resolve the global resource subdir `<agent_dir>/<sub>` (e.g.
57/// `~/.rpi/agent/skills`). Returns `None` if the agent dir can't be resolved
58/// (no home dir + no `RPI_CODING_AGENT_DIR`) — callers then proceed project-only.
59pub fn global_dir(sub: &str) -> Option<PathBuf> {
60    global_dir_at(None, sub)
61}
62
63/// [`global_dir`] under an explicit agent home (`--agent-dir`).
64fn global_dir_at(agent_dir: Option<&Path>, sub: &str) -> Option<PathBuf> {
65    crate::config::agent_dir_at(agent_dir)
66        .ok()
67        .map(|d| d.join(sub))
68}
69
70/// The candidate context/SYSTEM/APPEND filenames live directly under
71/// `<cwd>/.rpi/` and `<agent_dir>/`.
72pub fn project_config_file(cwd: &Path, name: &str) -> PathBuf {
73    cwd.join(PROJECT_CONFIG_DIR_NAME).join(name)
74}
75
76/// Resolve project config files. Only `.rpi` is read.
77pub fn project_config_files(cwd: &Path, name: &str) -> Vec<PathBuf> {
78    vec![project_config_file(cwd, name)]
79}
80
81/// Global config file under `<agent_dir>/<name>` (`~/.rpi/agent/SYSTEM.md`).
82pub fn global_config_file(name: &str) -> Option<PathBuf> {
83    global_config_file_at(None, name)
84}
85
86/// [`global_config_file`] under an explicit agent home (`--agent-dir`).
87fn global_config_file_at(agent_dir: Option<&Path>, name: &str) -> Option<PathBuf> {
88    crate::config::agent_dir_at(agent_dir)
89        .ok()
90        .map(|d| d.join(name))
91}
92
93/// Discover `SYSTEM.md` from the project `.rpi/` directory or global agent dir.
94pub fn discover_system_prompt_file(cwd: &Path) -> Option<PathBuf> {
95    discover_system_prompt_file_at(None, cwd, true)
96}
97
98/// [`discover_system_prompt_file`] under an explicit agent home.
99fn discover_system_prompt_file_at(
100    agent_dir: Option<&Path>,
101    cwd: &Path,
102    project_trusted: bool,
103) -> Option<PathBuf> {
104    if project_trusted {
105        for project in project_config_files(cwd, "SYSTEM.md") {
106            if project.is_file() {
107                return Some(project);
108            }
109        }
110    }
111    global_config_file_at(agent_dir, "SYSTEM.md").filter(|p| p.is_file())
112}
113
114/// Discover `SYSTEM.md` with explicit project trust control.
115pub fn discover_system_prompt_file_with_trust(
116    cwd: &Path,
117    project_trusted: bool,
118) -> Option<PathBuf> {
119    discover_system_prompt_file_at(None, cwd, project_trusted)
120}
121
122/// Discover `APPEND_SYSTEM.md` using project-over-global precedence.
123pub fn discover_append_system_prompt_file(cwd: &Path) -> Option<PathBuf> {
124    discover_append_system_prompt_file_at(None, cwd)
125}
126
127/// [`discover_append_system_prompt_file`] under an explicit agent home.
128fn discover_append_system_prompt_file_at(agent_dir: Option<&Path>, cwd: &Path) -> Option<PathBuf> {
129    for project in project_config_files(cwd, "APPEND_SYSTEM.md") {
130        if project.is_file() {
131            return Some(project);
132        }
133    }
134    global_config_file_at(agent_dir, "APPEND_SYSTEM.md").filter(|p| p.is_file())
135}
136
137// ---------------------------------------------------------------------------
138// Dedupe: first-wins-by-name (project wins when loaded project→global)
139// ---------------------------------------------------------------------------
140
141/// Dedupe skills by name, **first-wins**. Mirrors pi `addSkills`
142/// (`skills.ts:399-428`): the first skill with a given name is kept; later
143/// duplicates emit a collision diagnostic naming the winner (kept) and loser
144/// (dropped) paths. Load dirs in **project→global** order so project wins.
145///
146/// **v1 divergence:** rpi's `SkillDiagnostic` has no structured
147/// `winnerPath`/`loserPath` fields (pi's `SkillCollisionDiagnostic`); the
148/// collision is encoded as an `InvalidMetadata` diagnostic with a descriptive
149/// message naming both paths and `path` set to the loser.
150pub fn dedupe_skills(skills: Vec<Skill>, diagnostics: &mut Vec<SkillDiagnostic>) -> Vec<Skill> {
151    let mut winner_path: HashMap<String, String> = HashMap::new();
152    let mut out: Vec<Skill> = Vec::with_capacity(skills.len());
153    for skill in skills {
154        if let Some(winner) = winner_path.get(&skill.name) {
155            diagnostics.push(SkillDiagnostic {
156                code: SkillDiagnosticCode::InvalidMetadata,
157                message: format!(
158                    "Skill name \"{}\" from {} is shadowed by {} \
159                     (first-registration wins; load project before global so project wins)",
160                    skill.name, skill.file_path, winner
161                ),
162                path: skill.file_path.clone(),
163            });
164        } else {
165            winner_path.insert(skill.name.clone(), skill.file_path.clone());
166            out.push(skill);
167        }
168    }
169    out
170}
171
172/// Dedupe prompt templates by name, **first-wins**. Mirrors pi `dedupePrompts`
173/// (`resource-loader.ts:969-993`): the first template with a given name is kept;
174/// later duplicates emit a collision diagnostic. Load paths in **project→global**
175/// order so project wins.
176///
177/// **v1 divergence:** `PromptTemplate` carries no `file_path` (only
178/// name/description/content), so the collision diagnostic's `path` is set to the
179/// colliding template **name** rather than a file path; and the code is
180/// `ParseFailed` (rpi has no dedicated collision code) with a descriptive
181/// message. Structured winner/loser diagnostics are deferred.
182pub fn dedupe_prompt_templates(
183    templates: Vec<PromptTemplate>,
184    diagnostics: &mut Vec<PromptTemplateDiagnostic>,
185) -> Vec<PromptTemplate> {
186    let mut seen: HashMap<String, ()> = HashMap::new();
187    let mut out: Vec<PromptTemplate> = Vec::with_capacity(templates.len());
188    for t in templates {
189        if seen.contains_key(&t.name) {
190            diagnostics.push(PromptTemplateDiagnostic {
191                code: PromptTemplateDiagnosticCode::ParseFailed,
192                message: format!(
193                    "Prompt template name \"{}\" is shadowed by an earlier registration \
194                     (first-registration wins; load project before global so project wins)",
195                    t.name
196                ),
197                // PromptTemplate carries no file path; the name is the collision
198                // key, so use it as the diagnostic path.
199                path: t.name.clone(),
200            });
201        } else {
202            seen.insert(t.name.clone(), ());
203            out.push(t);
204        }
205    }
206    out
207}
208
209/// Structured variant of [`dedupe_skills`]: emits a [`ResourceDiagnostic`] per
210/// shadowed skill (winner/loser path) instead of a stringly-typed diagnostic.
211/// Callers that want to surface collisions in the UI (e.g. `/reload`) use this.
212pub fn dedupe_skills_structured(
213    skills: Vec<Skill>,
214    diagnostics: &mut Vec<rpi_harness::diagnostics::ResourceDiagnostic>,
215) -> Vec<Skill> {
216    use rpi_harness::diagnostics::{dedupe_by_name, ResourceType};
217    let keys: Vec<(String, String)> = skills
218        .iter()
219        .map(|s| (s.name.clone(), s.file_path.clone()))
220        .collect();
221    let refs: Vec<(&str, &str)> = keys.iter().map(|(n, p)| (n.as_str(), p.as_str())).collect();
222    let (winners, diags) = dedupe_by_name(ResourceType::Skill, refs);
223    diagnostics.extend(diags);
224    let winner_set: std::collections::HashSet<usize> = winners.into_iter().collect();
225    skills
226        .into_iter()
227        .enumerate()
228        .filter_map(|(index, skill)| winner_set.contains(&index).then_some(skill))
229        .collect()
230}
231
232/// Structured variant of [`dedupe_prompt_templates`]. `PromptTemplate` carries
233/// no file path, so the collision loser/winner paths fall back to the template
234/// name (documented divergence).
235pub fn dedupe_prompt_templates_structured(
236    templates: Vec<PromptTemplate>,
237    diagnostics: &mut Vec<rpi_harness::diagnostics::ResourceDiagnostic>,
238) -> Vec<PromptTemplate> {
239    use rpi_harness::diagnostics::{dedupe_by_name, ResourceType};
240    let keys: Vec<String> = templates.iter().map(|t| t.name.clone()).collect();
241    let refs: Vec<(&str, &str)> = keys.iter().map(|n| (n.as_str(), n.as_str())).collect();
242    let (winners, diags) = dedupe_by_name(ResourceType::Prompt, refs);
243    diagnostics.extend(diags);
244    let winner_set: std::collections::HashSet<usize> = winners.into_iter().collect();
245    templates
246        .into_iter()
247        .enumerate()
248        .filter_map(|(index, t)| winner_set.contains(&index).then_some(t))
249        .collect()
250}
251
252// ---------------------------------------------------------------------------
253// Precedence-aware loaders: project dir → global dir → dedupe (project wins)
254// ---------------------------------------------------------------------------
255
256/// Load skills from `dirs` in order, then dedupe first-wins-by-name. Missing
257/// directories are skipped silently by the underlying loader (NotFound →
258/// `continue`, mirroring pi). Pass dirs in **project→global** order so project
259/// wins on name collisions.
260pub async fn load_skills_with_precedence(
261    env: &Arc<dyn ExecutionEnv>,
262    dirs: &[PathBuf],
263) -> LoadSkillsResult {
264    let dir_strs: Vec<String> = dirs
265        .iter()
266        .map(|d| d.to_string_lossy().into_owned())
267        .collect();
268    let mut result = load_skills(env, &dir_strs).await;
269    // Collect structured collisions from the pre-dedupe list so the UI can
270    // show winner/loser paths (native `ResourceDiagnostic`), then dedupe.
271    let mut structured = Vec::new();
272    let raw = std::mem::take(&mut result.skills);
273    let _ = dedupe_skills_structured(raw.clone(), &mut structured);
274    result.skills = dedupe_skills(raw, &mut result.diagnostics);
275    result.resource_diagnostics = structured;
276    result
277}
278
279/// Load prompt templates from `paths` (dirs or `.md` files) in order, then
280/// dedupe first-wins-by-name. Missing paths are skipped silently. Pass paths in
281/// **project→global** order so project wins on name collisions.
282pub async fn load_prompt_templates_with_precedence(
283    env: &Arc<dyn ExecutionEnv>,
284    paths: &[PathBuf],
285) -> LoadPromptTemplatesResult {
286    let path_strs: Vec<String> = paths
287        .iter()
288        .map(|p| p.to_string_lossy().into_owned())
289        .collect();
290    let mut result = load_prompt_templates(env, &path_strs).await;
291    let mut structured = Vec::new();
292    let raw = std::mem::take(&mut result.prompt_templates);
293    let _ = dedupe_prompt_templates_structured(raw.clone(), &mut structured);
294    result.prompt_templates = dedupe_prompt_templates(raw, &mut result.diagnostics);
295    result.resource_diagnostics = structured;
296    result
297}
298
299/// The ordered skill dirs for a project: configured project paths, then
300/// `[<cwd>/.rpi/skills, <agent_dir>/skills]`, followed by
301/// configured and conventional global paths.
302/// The global dir is omitted when `agent_dir()` can't be resolved (no home dir).
303pub fn skill_dirs(cwd: &Path) -> Vec<PathBuf> {
304    skill_dirs_at(cwd, None)
305}
306
307/// [`skill_dirs`] under an explicit agent home (`--agent-dir`).
308fn skill_dirs_at(cwd: &Path, agent_dir: Option<&Path>) -> Vec<PathBuf> {
309    let mut dirs = project_skill_dirs(cwd);
310    if let Some(g) = global_dir_at(agent_dir, "skills") {
311        dirs.extend(configured_global_dirs(
312            g.clone(),
313            ResourceKind::Skills,
314            agent_dir,
315        ));
316        dirs.push(g);
317    }
318    dirs
319}
320
321/// Project-only skill directories, excluding user/global configuration. This
322/// is used by `rpi dev-local` so the current extension can be debugged with
323/// the skills in the current checkout without importing unrelated skills.
324pub fn project_skill_dirs(cwd: &Path) -> Vec<PathBuf> {
325    project_resource_dirs(cwd, "skills", ResourceKind::Skills)
326}
327
328/// Resource directories that do not depend on the current project. Used when
329/// the project trust gate denies local configuration/resources.
330pub fn global_skill_dirs() -> Vec<PathBuf> {
331    global_skill_dirs_at(None)
332}
333
334/// [`global_skill_dirs`] under an explicit agent home.
335fn global_skill_dirs_at(agent_dir: Option<&Path>) -> Vec<PathBuf> {
336    global_resource_dirs_at(agent_dir, "skills", ResourceKind::Skills)
337}
338
339/// The ordered prompt-template paths for a project: configured paths, then
340/// `[<cwd>/.rpi/prompts, <agent_dir>/prompts]`.
341pub fn prompt_template_dirs(cwd: &Path) -> Vec<PathBuf> {
342    prompt_template_dirs_at(cwd, None)
343}
344
345/// [`prompt_template_dirs`] under an explicit agent home.
346fn prompt_template_dirs_at(cwd: &Path, agent_dir: Option<&Path>) -> Vec<PathBuf> {
347    let mut dirs = project_prompt_template_dirs(cwd);
348    if let Some(g) = global_dir_at(agent_dir, "prompts") {
349        dirs.extend(configured_global_dirs(
350            g.clone(),
351            ResourceKind::Prompts,
352            agent_dir,
353        ));
354        dirs.push(g);
355    }
356    dirs
357}
358
359/// Project-only prompt-template directories, excluding user/global settings.
360pub fn project_prompt_template_dirs(cwd: &Path) -> Vec<PathBuf> {
361    project_resource_dirs(cwd, "prompts", ResourceKind::Prompts)
362}
363
364pub fn global_prompt_template_dirs() -> Vec<PathBuf> {
365    global_prompt_template_dirs_at(None)
366}
367
368fn global_prompt_template_dirs_at(agent_dir: Option<&Path>) -> Vec<PathBuf> {
369    global_resource_dirs_at(agent_dir, "prompts", ResourceKind::Prompts)
370}
371
372/// The ordered Rust extension directories for a project. Configured paths are
373/// added before conventional directories so an explicit project path can be
374/// used for development while `.rpi` defaults stay lower precedence.
375pub fn extension_dirs(cwd: &Path) -> Vec<PathBuf> {
376    extension_dirs_at(cwd, None)
377}
378
379/// [`extension_dirs`] under an explicit agent home.
380fn extension_dirs_at(cwd: &Path, agent_dir: Option<&Path>) -> Vec<PathBuf> {
381    let mut dirs = project_resource_dirs(cwd, "extensions", ResourceKind::Extensions);
382    if let Some(g) = global_dir_at(agent_dir, "extensions") {
383        dirs.extend(configured_global_dirs(
384            g.clone(),
385            ResourceKind::Extensions,
386            agent_dir,
387        ));
388        dirs.push(g);
389    }
390    dirs
391}
392
393pub fn project_extension_dirs(cwd: &Path) -> Vec<PathBuf> {
394    project_resource_dirs(cwd, "extensions", ResourceKind::Extensions)
395}
396
397pub fn global_extension_dirs() -> Vec<PathBuf> {
398    global_extension_dirs_at(None)
399}
400
401fn global_extension_dirs_at(agent_dir: Option<&Path>) -> Vec<PathBuf> {
402    global_resource_dirs_at(agent_dir, "extensions", ResourceKind::Extensions)
403}
404
405#[derive(Clone, Copy)]
406enum ResourceKind {
407    Skills,
408    Prompts,
409    Extensions,
410}
411
412fn project_resource_dirs(cwd: &Path, sub: &str, kind: ResourceKind) -> Vec<PathBuf> {
413    let loaded = crate::settings::load_project_settings_with_paths(cwd);
414    let mut dirs = Vec::new();
415    for (_, settings) in loaded.iter() {
416        dirs.extend(configured_paths(settings, cwd, kind));
417    }
418    // Project packages are explicit, local resources. Keep configured project
419    // directories first, then package resources, then the conventional
420    // `.rpi/<sub>` directory so existing precedence remains stable.
421    let package_kind = match kind {
422        ResourceKind::Skills => "skills",
423        ResourceKind::Prompts => "prompts",
424        ResourceKind::Extensions => "extensions",
425    };
426    dirs.extend(crate::packages::project_package_dirs(cwd, package_kind));
427    dirs.push(project_dir(cwd, sub));
428    dirs
429}
430
431fn configured_global_dirs(
432    agent_dir: PathBuf,
433    kind: ResourceKind,
434    home: Option<&Path>,
435) -> Vec<PathBuf> {
436    crate::settings::load_settings_at(home)
437        .ok()
438        .into_iter()
439        .flat_map(|settings| configured_paths(&settings, &agent_dir, kind))
440        .collect()
441}
442
443fn global_resource_dirs_at(
444    agent_dir: Option<&Path>,
445    sub: &str,
446    kind: ResourceKind,
447) -> Vec<PathBuf> {
448    let Some(g) = global_dir_at(agent_dir, sub) else {
449        return Vec::new();
450    };
451    let mut dirs = configured_global_dirs(g.clone(), kind, agent_dir);
452    dirs.push(g);
453    dirs
454}
455
456fn configured_paths(
457    settings: &crate::settings::Settings,
458    base: &Path,
459    kind: ResourceKind,
460) -> Vec<PathBuf> {
461    let values = match kind {
462        ResourceKind::Skills => settings.skill_dirs.as_ref(),
463        ResourceKind::Prompts => settings.prompt_dirs.as_ref(),
464        ResourceKind::Extensions => settings.extension_dirs.as_ref(),
465    };
466    values
467        .map(|paths| crate::settings::resolve_configured_paths(base, paths))
468        .unwrap_or_default()
469}
470
471impl crate::config::AgentHome {
472    /// Global resource subdir `<home>/<sub>` (e.g. `<home>/skills`).
473    pub fn global_dir(&self, sub: &str) -> Option<PathBuf> {
474        global_dir_at(self.explicit_path(), sub)
475    }
476
477    /// Global config file under `<home>/<name>` (`<home>/SYSTEM.md`).
478    pub fn global_config_file(&self, name: &str) -> Option<PathBuf> {
479        global_config_file_at(self.explicit_path(), name)
480    }
481
482    pub fn discover_system_prompt_file(
483        &self,
484        cwd: &Path,
485        project_trusted: bool,
486    ) -> Option<PathBuf> {
487        discover_system_prompt_file_at(self.explicit_path(), cwd, project_trusted)
488    }
489
490    pub fn discover_append_system_prompt_file(&self, cwd: &Path) -> Option<PathBuf> {
491        discover_append_system_prompt_file_at(self.explicit_path(), cwd)
492    }
493
494    /// Ordered skill dirs for a project: project paths, then this home's
495    /// configured + conventional global paths.
496    pub fn skill_dirs(&self, cwd: &Path) -> Vec<PathBuf> {
497        skill_dirs_at(cwd, self.explicit_path())
498    }
499
500    pub fn global_skill_dirs(&self) -> Vec<PathBuf> {
501        global_skill_dirs_at(self.explicit_path())
502    }
503
504    pub fn prompt_template_dirs(&self, cwd: &Path) -> Vec<PathBuf> {
505        prompt_template_dirs_at(cwd, self.explicit_path())
506    }
507
508    pub fn global_prompt_template_dirs(&self) -> Vec<PathBuf> {
509        global_prompt_template_dirs_at(self.explicit_path())
510    }
511
512    pub fn extension_dirs(&self, cwd: &Path) -> Vec<PathBuf> {
513        extension_dirs_at(cwd, self.explicit_path())
514    }
515
516    pub fn global_extension_dirs(&self) -> Vec<PathBuf> {
517        global_extension_dirs_at(self.explicit_path())
518    }
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524
525    fn skill(name: &str, path: &str) -> Skill {
526        Skill {
527            name: name.to_string(),
528            description: "d".to_string(),
529            content: "c".to_string(),
530            file_path: path.to_string(),
531            disable_model_invocation: None,
532        }
533    }
534
535    fn tmpl(name: &str) -> PromptTemplate {
536        PromptTemplate {
537            name: name.to_string(),
538            description: None,
539            content: "c".to_string(),
540        }
541    }
542
543    #[test]
544    fn dedupe_skills_first_wins_keeps_project() {
545        // Project loaded first, global second; same name → project (first) wins.
546        let skills = vec![
547            skill("echo", "/proj/.rpi/skills/echo/SKILL.md"),
548            skill("echo", "/home/.rpi/agent/skills/echo/SKILL.md"),
549        ];
550        let mut diags = Vec::new();
551        let out = dedupe_skills(skills, &mut diags);
552        assert_eq!(out.len(), 1);
553        assert_eq!(out[0].file_path, "/proj/.rpi/skills/echo/SKILL.md");
554        assert_eq!(diags.len(), 1);
555        assert!(diags[0]
556            .message
557            .contains("/home/.rpi/agent/skills/echo/SKILL.md"));
558        assert!(diags[0].message.contains("/proj/.rpi/skills/echo/SKILL.md"));
559        assert_eq!(diags[0].path, "/home/.rpi/agent/skills/echo/SKILL.md");
560    }
561
562    #[test]
563    fn dedupe_skills_distinct_names_all_kept() {
564        let skills = vec![skill("a", "/p/a"), skill("b", "/p/b"), skill("c", "/g/c")];
565        let mut diags = Vec::new();
566        let out = dedupe_skills(skills, &mut diags);
567        assert_eq!(out.len(), 3);
568        assert!(diags.is_empty());
569    }
570
571    #[test]
572    fn dedupe_skills_third_duplicate_drops_against_first() {
573        let skills = vec![
574            skill("x", "/proj/x"),
575            skill("x", "/global/x"),
576            skill("x", "/pkg/x"),
577        ];
578        let mut diags = Vec::new();
579        let out = dedupe_skills(skills, &mut diags);
580        assert_eq!(out.len(), 1);
581        assert_eq!(out[0].file_path, "/proj/x");
582        // Both later duplicates emit a collision diagnostic vs the same winner.
583        assert_eq!(diags.len(), 2);
584    }
585
586    #[test]
587    fn dedupe_skills_empty_input() {
588        let mut diags = Vec::new();
589        let out = dedupe_skills(Vec::new(), &mut diags);
590        assert!(out.is_empty());
591        assert!(diags.is_empty());
592    }
593
594    #[test]
595    fn dedupe_prompts_first_wins() {
596        let templates = vec![tmpl("greet"), tmpl("greet")];
597        let mut diags = Vec::new();
598        let out = dedupe_prompt_templates(templates, &mut diags);
599        assert_eq!(out.len(), 1);
600        assert_eq!(out[0].name, "greet");
601        assert_eq!(diags.len(), 1);
602        assert_eq!(diags[0].path, "greet");
603    }
604
605    #[test]
606    fn dedupe_prompts_distinct_all_kept() {
607        let templates = vec![tmpl("a"), tmpl("b"), tmpl("c")];
608        let mut diags = Vec::new();
609        let out = dedupe_prompt_templates(templates, &mut diags);
610        assert_eq!(out.len(), 3);
611        assert!(diags.is_empty());
612    }
613
614    #[test]
615    fn project_dir_uses_rpi_name() {
616        let d = project_dir(Path::new("/proj"), "skills");
617        assert_eq!(d, PathBuf::from("/proj/.rpi/skills"));
618    }
619
620    #[test]
621    fn project_dirs_only_use_rpi_after_de_pi() {
622        let dirs = project_dirs(Path::new("/proj"), "extensions");
623        assert_eq!(dirs, vec![PathBuf::from("/proj/.rpi/extensions")]);
624    }
625
626    #[test]
627    fn project_config_files_only_use_rpi_after_de_pi() {
628        let p = project_config_file(Path::new("/proj"), "SYSTEM.md");
629        assert_eq!(p, PathBuf::from("/proj/.rpi/SYSTEM.md"));
630        assert_eq!(
631            project_config_files(Path::new("/proj"), "SYSTEM.md"),
632            vec![p]
633        );
634    }
635
636    #[test]
637    fn project_settings_add_configured_resource_paths() {
638        let tmp = tempfile::tempdir().unwrap();
639        std::fs::create_dir_all(tmp.path().join(".rpi")).unwrap();
640        std::fs::write(
641            tmp.path().join(".rpi/settings.json"),
642            r#"{"skills":["shared-skills"],"promptDirs":["prompt-pack"],"extensionDirs":["target/debug"]}"#,
643        )
644        .unwrap();
645
646        let skills = skill_dirs(tmp.path());
647        assert_eq!(skills[0], tmp.path().join("shared-skills"));
648        assert!(skills.contains(&tmp.path().join(".rpi/skills")));
649
650        let prompts = prompt_template_dirs(tmp.path());
651        assert_eq!(prompts[0], tmp.path().join("prompt-pack"));
652
653        let extensions = extension_dirs(tmp.path());
654        assert_eq!(extensions[0], tmp.path().join("target/debug"));
655        assert!(extensions.contains(&tmp.path().join(".rpi/extensions")));
656    }
657
658    #[test]
659    fn local_resource_dirs_exclude_global_paths() {
660        let tmp = tempfile::tempdir().unwrap();
661        std::fs::create_dir_all(tmp.path().join(".rpi")).unwrap();
662        std::fs::write(
663            tmp.path().join(".rpi/settings.json"),
664            r#"{"skills":["local-skills"],"promptDirs":["local-prompts"]}"#,
665        )
666        .unwrap();
667
668        let skills = project_skill_dirs(tmp.path());
669        let prompts = project_prompt_template_dirs(tmp.path());
670        assert!(skills.contains(&tmp.path().join("local-skills")));
671        assert!(skills.contains(&tmp.path().join(".rpi/skills")));
672        assert!(prompts.contains(&tmp.path().join("local-prompts")));
673        assert!(prompts.contains(&tmp.path().join(".rpi/prompts")));
674    }
675}