1use 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
43pub const PROJECT_CONFIG_DIR_NAME: &str = ".rpi";
45
46pub fn project_dir(cwd: &Path, sub: &str) -> PathBuf {
48 cwd.join(PROJECT_CONFIG_DIR_NAME).join(sub)
49}
50
51pub fn project_dirs(cwd: &Path, sub: &str) -> Vec<PathBuf> {
53 vec![project_dir(cwd, sub)]
54}
55
56pub fn global_dir(sub: &str) -> Option<PathBuf> {
60 global_dir_at(None, sub)
61}
62
63fn 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
70pub fn project_config_file(cwd: &Path, name: &str) -> PathBuf {
73 cwd.join(PROJECT_CONFIG_DIR_NAME).join(name)
74}
75
76pub fn project_config_files(cwd: &Path, name: &str) -> Vec<PathBuf> {
78 vec![project_config_file(cwd, name)]
79}
80
81pub fn global_config_file(name: &str) -> Option<PathBuf> {
83 global_config_file_at(None, name)
84}
85
86fn 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
93pub fn discover_system_prompt_file(cwd: &Path) -> Option<PathBuf> {
95 discover_system_prompt_file_at(None, cwd, true)
96}
97
98fn 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
114pub 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
122pub fn discover_append_system_prompt_file(cwd: &Path) -> Option<PathBuf> {
124 discover_append_system_prompt_file_at(None, cwd)
125}
126
127fn 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
137pub 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
172pub 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 path: t.name.clone(),
200 });
201 } else {
202 seen.insert(t.name.clone(), ());
203 out.push(t);
204 }
205 }
206 out
207}
208
209pub 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
232pub 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
252pub 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 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
279pub 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
299pub fn skill_dirs(cwd: &Path) -> Vec<PathBuf> {
304 skill_dirs_at(cwd, None)
305}
306
307fn 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
321pub fn project_skill_dirs(cwd: &Path) -> Vec<PathBuf> {
325 project_resource_dirs(cwd, "skills", ResourceKind::Skills)
326}
327
328pub fn global_skill_dirs() -> Vec<PathBuf> {
331 global_skill_dirs_at(None)
332}
333
334fn global_skill_dirs_at(agent_dir: Option<&Path>) -> Vec<PathBuf> {
336 global_resource_dirs_at(agent_dir, "skills", ResourceKind::Skills)
337}
338
339pub fn prompt_template_dirs(cwd: &Path) -> Vec<PathBuf> {
342 prompt_template_dirs_at(cwd, None)
343}
344
345fn 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
359pub 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
372pub fn extension_dirs(cwd: &Path) -> Vec<PathBuf> {
376 extension_dirs_at(cwd, None)
377}
378
379fn 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 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 pub fn global_dir(&self, sub: &str) -> Option<PathBuf> {
474 global_dir_at(self.explicit_path(), sub)
475 }
476
477 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 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 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 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}