1use std::collections::{BTreeMap, HashMap};
4use std::path::{Path, PathBuf};
5use std::sync::{OnceLock, RwLock};
6use std::time::{Duration, SystemTime};
7
8use serde::Deserialize;
9use tokio::fs;
10use tracing::warn;
11use vtcode_commons::VtCodePaths;
12
13const PROMPTS_DIR: &str = ".vtcode/prompts";
14const TEMPLATES_DIR: &str = "templates";
15const SYSTEM_PROMPT_FILENAME: &str = "system.md";
16const APPEND_SYSTEM_PROMPT_FILENAME: &str = "append-system.md";
17const PROMPT_RESOURCE_CACHE_TTL: Duration = Duration::from_secs(5 * 60);
18const PROMPT_RESOURCE_CACHE_MAX_ENTRIES: usize = 32;
19
20static SYSTEM_PROMPT_LAYERS_CACHE: OnceLock<RwLock<HashMap<PromptResourceCacheKey, CachedSystemPromptLayers>>> =
21 OnceLock::new();
22static PROMPT_TEMPLATES_CACHE: OnceLock<RwLock<HashMap<PromptResourceCacheKey, CachedPromptTemplates>>> =
23 OnceLock::new();
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct PromptTemplate {
27 pub name: String,
28 pub description: String,
29 pub body: String,
30 pub path: PathBuf,
31}
32
33#[derive(Debug, Clone, Default, PartialEq, Eq)]
34pub struct SystemPromptLayers {
35 pub override_body: Option<String>,
36 pub append_bodies: Vec<String>,
37}
38
39#[derive(Debug, Clone, Copy)]
40enum PromptResourceScope {
41 User,
42 Workspace,
43}
44
45#[derive(Debug, Clone)]
46struct PromptResourceOptions<'a> {
47 workspace_root: &'a Path,
48 home_dir: Option<PathBuf>,
49}
50
51#[derive(Debug, Clone, Default, Deserialize)]
52struct PromptTemplateFrontmatter {
53 description: Option<String>,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Hash)]
57struct PromptResourceCacheKey {
58 workspace_root: PathBuf,
59 home_dir: Option<PathBuf>,
60}
61
62impl PromptResourceCacheKey {
63 fn new(options: &PromptResourceOptions<'_>) -> Self {
64 Self {
65 workspace_root: normalize_cache_path(options.workspace_root),
66 home_dir: options.home_dir.as_deref().map(normalize_cache_path),
67 }
68 }
69}
70
71#[derive(Clone)]
72struct CachedPromptTemplates {
73 templates: Vec<PromptTemplate>,
74 timestamp: SystemTime,
75 source_mtime: SystemTime,
76 source_paths: (PathBuf, Option<PathBuf>),
77}
78
79impl CachedPromptTemplates {
80 fn is_expired(&self) -> bool {
81 self.timestamp.elapsed().unwrap_or(PROMPT_RESOURCE_CACHE_TTL) > PROMPT_RESOURCE_CACHE_TTL
82 }
83
84 fn is_source_stale(&self) -> bool {
85 let mut check: Vec<&Path> = vec![self.source_paths.0.as_path()];
86 if let Some(ref h) = self.source_paths.1 {
87 check.push(h.as_path());
88 }
89 newest_mtime(check) > self.source_mtime
90 }
91}
92
93#[derive(Clone)]
94struct CachedSystemPromptLayers {
95 layers: SystemPromptLayers,
96 timestamp: SystemTime,
97 source_mtime: SystemTime,
98}
99
100impl CachedSystemPromptLayers {
101 fn is_expired(&self) -> bool {
102 self.timestamp.elapsed().unwrap_or(PROMPT_RESOURCE_CACHE_TTL) > PROMPT_RESOURCE_CACHE_TTL
103 }
104
105 fn is_source_stale(&self, check_paths: &[&Path]) -> bool {
106 newest_mtime(check_paths.iter().copied()) > self.source_mtime
107 }
108}
109
110fn normalize_cache_path(path: &Path) -> PathBuf {
111 dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
112}
113
114pub(crate) fn user_prompts_dir(home: &Path) -> PathBuf {
115 if dirs::home_dir().as_deref() == Some(home)
116 && let Ok(paths) = VtCodePaths::resolve()
117 && let Ok(prompt_dir) = paths.config_path("prompts")
118 {
119 return prompt_dir;
120 }
121 home.join(PROMPTS_DIR)
122}
123
124fn newest_mtime<'a>(paths: impl IntoIterator<Item = &'a Path>) -> SystemTime {
127 let mut newest = SystemTime::UNIX_EPOCH;
128 for path in paths {
129 if let Ok(metadata) = std::fs::metadata(path) {
130 if let Ok(mtime) = metadata.modified() {
131 newest = newest.max(mtime);
132 }
133 }
134 }
135 newest
136}
137
138fn system_prompt_layers_cache() -> &'static RwLock<HashMap<PromptResourceCacheKey, CachedSystemPromptLayers>> {
139 SYSTEM_PROMPT_LAYERS_CACHE.get_or_init(|| RwLock::new(HashMap::new()))
140}
141
142fn prompt_templates_cache() -> &'static RwLock<HashMap<PromptResourceCacheKey, CachedPromptTemplates>> {
143 PROMPT_TEMPLATES_CACHE.get_or_init(|| RwLock::new(HashMap::new()))
144}
145
146trait ExpirableCacheEntry {
149 fn is_expired(&self) -> bool;
150 fn timestamp(&self) -> SystemTime;
151}
152
153impl ExpirableCacheEntry for CachedSystemPromptLayers {
154 fn is_expired(&self) -> bool {
155 self.is_expired()
156 }
157
158 fn timestamp(&self) -> SystemTime {
159 self.timestamp
160 }
161}
162
163impl ExpirableCacheEntry for CachedPromptTemplates {
164 fn is_expired(&self) -> bool {
165 self.is_expired()
166 }
167
168 fn timestamp(&self) -> SystemTime {
169 self.timestamp
170 }
171}
172
173fn get_cached<K, V>(cache: &RwLock<HashMap<K, V>>, key: &K, what: &str) -> Option<V>
175where
176 K: Eq + std::hash::Hash,
177 V: ExpirableCacheEntry + Clone,
178{
179 match cache.read() {
180 Ok(cache) => cache.get(key).filter(|cached| !cached.is_expired()).cloned(),
181 Err(_) => {
182 warn!("{what} cache lock poisoned while reading cache");
183 None
184 }
185 }
186}
187
188fn evict_if_full<K, V>(cache: &mut HashMap<K, V>, key: &K)
191where
192 K: Eq + std::hash::Hash + Clone,
193 V: ExpirableCacheEntry,
194{
195 if cache.len() < PROMPT_RESOURCE_CACHE_MAX_ENTRIES || cache.contains_key(key) {
196 return;
197 }
198 let expired: Vec<K> = cache
199 .iter()
200 .filter(|(_, value)| value.is_expired())
201 .map(|(cache_key, _)| cache_key.clone())
202 .collect();
203 for cache_key in expired {
204 cache.remove(&cache_key);
205 }
206
207 if cache.len() >= PROMPT_RESOURCE_CACHE_MAX_ENTRIES {
208 let oldest_key = cache
209 .iter()
210 .min_by_key(|(_, value)| value.timestamp())
211 .map(|(cache_key, _)| cache_key.clone());
212 if let Some(oldest_key) = oldest_key {
213 cache.remove(&oldest_key);
214 }
215 }
216}
217
218fn get_cached_system_prompt_layers(key: &PromptResourceCacheKey) -> Option<CachedSystemPromptLayers> {
219 get_cached(system_prompt_layers_cache(), key, "system prompt layers")
220}
221
222fn cache_system_prompt_layers(key: PromptResourceCacheKey, layers: &SystemPromptLayers) {
223 match system_prompt_layers_cache().write() {
224 Ok(mut cache) => {
225 evict_if_full(&mut cache, &key);
226
227 let mut source_paths = vec![
228 key.workspace_root.join(PROMPTS_DIR).join(SYSTEM_PROMPT_FILENAME),
229 key.workspace_root.join(PROMPTS_DIR).join(APPEND_SYSTEM_PROMPT_FILENAME),
230 ];
231 if let Some(ref home) = key.home_dir {
232 let prompt_dir = user_prompts_dir(home);
233 source_paths.push(prompt_dir.join(SYSTEM_PROMPT_FILENAME));
234 source_paths.push(prompt_dir.join(APPEND_SYSTEM_PROMPT_FILENAME));
235 }
236 let source_mtime = newest_mtime(source_paths.iter().map(PathBuf::as_path));
237
238 cache.insert(
239 key,
240 CachedSystemPromptLayers {
241 layers: layers.clone(),
242 timestamp: SystemTime::now(),
243 source_mtime,
244 },
245 );
246 }
247 Err(_) => warn!("system prompt layers cache lock poisoned while writing cache"),
248 }
249}
250
251fn get_cached_prompt_templates(key: &PromptResourceCacheKey) -> Option<CachedPromptTemplates> {
252 get_cached(prompt_templates_cache(), key, "prompt templates")
253}
254
255fn cache_prompt_templates(key: PromptResourceCacheKey, templates: &[PromptTemplate]) {
256 match prompt_templates_cache().write() {
257 Ok(mut cache) => {
258 evict_if_full(&mut cache, &key);
259
260 let source_paths = (
261 key.workspace_root.join(PROMPTS_DIR).join(TEMPLATES_DIR),
262 key.home_dir.as_ref().map(|h| user_prompts_dir(h).join(TEMPLATES_DIR)),
263 );
264 let mut mtime_paths = vec![source_paths.0.clone()];
265 if let Some(ref p) = source_paths.1 {
266 mtime_paths.push(p.clone());
267 }
268 let source_mtime = newest_mtime(mtime_paths.iter().map(PathBuf::as_path));
269
270 cache.insert(
271 key,
272 CachedPromptTemplates {
273 templates: templates.to_vec(),
274 timestamp: SystemTime::now(),
275 source_mtime,
276 source_paths,
277 },
278 );
279 }
280 Err(_) => warn!("prompt templates cache lock poisoned while writing cache"),
281 }
282}
283
284#[cfg(test)]
285fn clear_prompt_resource_caches() {
286 if let Ok(mut cache) = system_prompt_layers_cache().write() {
287 cache.clear();
288 }
289 if let Ok(mut cache) = prompt_templates_cache().write() {
290 cache.clear();
291 }
292}
293
294pub async fn resolve_system_prompt_layers(workspace_root: &Path) -> SystemPromptLayers {
295 resolve_system_prompt_layers_with_options(PromptResourceOptions::new(workspace_root)).await
296}
297
298pub async fn discover_prompt_templates(workspace_root: &Path) -> Vec<PromptTemplate> {
299 discover_prompt_templates_with_options(PromptResourceOptions::new(workspace_root)).await
300}
301
302pub async fn find_prompt_template(workspace_root: &Path, name: &str) -> Option<PromptTemplate> {
303 let normalized = name.trim();
304 if normalized.is_empty() {
305 return None;
306 }
307
308 find_prompt_template_with_options(PromptResourceOptions::new(workspace_root), normalized).await
309}
310
311impl SystemPromptLayers {
312 fn effective_override_body(&self) -> Option<&str> {
314 self.override_body.as_deref().map(str::trim).filter(|body| !body.is_empty())
315 }
316
317 fn effective_append_bodies(&self) -> impl Iterator<Item = &str> {
319 self.append_bodies
320 .iter()
321 .map(|body| body.trim())
322 .filter(|body| !body.is_empty())
323 }
324
325 pub fn applied_text(&self) -> String {
331 let mut text = String::new();
332 let bodies = self.effective_override_body().into_iter().chain(self.effective_append_bodies());
333 for body in bodies {
334 if !text.is_empty() {
335 text.push_str("\n\n");
336 }
337 text.push_str(body);
338 }
339 text
340 }
341}
342
343pub fn apply_system_prompt_layers(base_prompt: &str, layers: &SystemPromptLayers) -> String {
344 let mut prompt = String::new();
345
346 if let Some(override_body) = layers.effective_override_body() {
347 prompt.push_str(override_body);
348 } else {
349 prompt.push_str(base_prompt);
350 }
351
352 for append_body in layers.effective_append_bodies() {
353 if !prompt.is_empty() {
354 prompt.push_str("\n\n");
355 }
356 prompt.push_str(append_body);
357 }
358
359 prompt
360}
361
362pub fn expand_prompt_template(body: &str, args: &[String]) -> String {
363 let joined_args = args.join(" ");
364 let mut expanded = String::with_capacity(body.len() + joined_args.len());
365 let chars: Vec<char> = body.chars().collect();
366 let mut index = 0;
367
368 while index < chars.len() {
369 if chars[index] != '$' {
370 expanded.push(chars[index]);
371 index += 1;
372 continue;
373 }
374
375 if index + 1 >= chars.len() {
376 expanded.push('$');
377 index += 1;
378 continue;
379 }
380
381 match chars[index + 1] {
382 '@' => {
383 expanded.push_str(&joined_args);
384 index += 2;
385 }
386 'A' => {
387 const ARGUMENTS_TOKEN: &str = "ARGUMENTS";
388 let remaining: String = chars[index + 1..].iter().collect();
389 if remaining.starts_with(ARGUMENTS_TOKEN) {
390 expanded.push_str(&joined_args);
391 index += ARGUMENTS_TOKEN.chars().count() + 1;
392 } else {
393 expanded.push('$');
394 index += 1;
395 }
396 }
397 digit if digit.is_ascii_digit() => {
398 let mut cursor = index + 1;
399 while cursor < chars.len() && chars[cursor].is_ascii_digit() {
400 cursor += 1;
401 }
402 let ordinal: String = chars[index + 1..cursor].iter().collect();
403 let replacement = ordinal
404 .parse::<usize>()
405 .ok()
406 .and_then(|value| value.checked_sub(1))
407 .and_then(|position| args.get(position))
408 .map(String::as_str)
409 .unwrap_or("");
410 expanded.push_str(replacement);
411 index = cursor;
412 }
413 _ => {
414 expanded.push('$');
415 index += 1;
416 }
417 }
418 }
419
420 expanded
421}
422
423impl<'a> PromptResourceOptions<'a> {
424 fn new(workspace_root: &'a Path) -> Self {
425 #[cfg(test)]
426 let home_dir = None;
427
428 #[cfg(not(test))]
429 let home_dir = dirs::home_dir();
430
431 Self { workspace_root, home_dir }
432 }
433}
434
435async fn resolve_system_prompt_layers_with_options(options: PromptResourceOptions<'_>) -> SystemPromptLayers {
436 let cache_key = PromptResourceCacheKey::new(&options);
437 if let Some(cached) = get_cached_system_prompt_layers(&cache_key) {
438 let check_paths = [
439 options.workspace_root.join(PROMPTS_DIR).join(SYSTEM_PROMPT_FILENAME),
440 options
441 .home_dir
442 .as_ref()
443 .map(|h| user_prompts_dir(h).join(SYSTEM_PROMPT_FILENAME))
444 .unwrap_or_default(),
445 options.workspace_root.join(PROMPTS_DIR).join(APPEND_SYSTEM_PROMPT_FILENAME),
446 options
447 .home_dir
448 .as_ref()
449 .map(|h| user_prompts_dir(h).join(APPEND_SYSTEM_PROMPT_FILENAME))
450 .unwrap_or_default(),
451 ];
452 let check_refs: Vec<_> = check_paths.iter().map(|p| p.as_path()).collect();
453 if !cached.is_source_stale(&check_refs) {
454 return cached.layers;
455 }
456 }
457
458 let layers = resolve_system_prompt_layers_uncached(&options).await;
459 cache_system_prompt_layers(cache_key, &layers);
460 layers
461}
462
463async fn resolve_system_prompt_layers_uncached(options: &PromptResourceOptions<'_>) -> SystemPromptLayers {
464 let mut layers = SystemPromptLayers::default();
465
466 let user_system_path = options
467 .home_dir
468 .as_ref()
469 .map(|home| user_prompts_dir(home).join(SYSTEM_PROMPT_FILENAME));
470 let workspace_system_path = options.workspace_root.join(PROMPTS_DIR).join(SYSTEM_PROMPT_FILENAME);
471
472 if let Some(path) = user_system_path.as_ref() {
473 layers.override_body = read_optional_markdown(path).await;
474 }
475
476 if let Some(workspace_override) = read_optional_markdown(&workspace_system_path).await {
477 layers.override_body = Some(workspace_override);
478 }
479
480 if let Some(path) = options
481 .home_dir
482 .as_ref()
483 .map(|home| user_prompts_dir(home).join(APPEND_SYSTEM_PROMPT_FILENAME))
484 && let Some(contents) = read_optional_markdown(&path).await
485 {
486 layers.append_bodies.push(contents);
487 }
488
489 let workspace_append = options.workspace_root.join(PROMPTS_DIR).join(APPEND_SYSTEM_PROMPT_FILENAME);
490 if let Some(contents) = read_optional_markdown(&workspace_append).await {
491 layers.append_bodies.push(contents);
492 }
493
494 layers
495}
496
497async fn discover_prompt_templates_with_options(options: PromptResourceOptions<'_>) -> Vec<PromptTemplate> {
498 let cache_key = PromptResourceCacheKey::new(&options);
499 if let Some(cached) = get_cached_prompt_templates(&cache_key) {
500 if !cached.is_source_stale() {
501 return cached.templates;
502 }
503 }
504
505 let templates = discover_prompt_templates_uncached(&options).await;
506 cache_prompt_templates(cache_key, &templates);
507 templates
508}
509
510async fn discover_prompt_templates_uncached(options: &PromptResourceOptions<'_>) -> Vec<PromptTemplate> {
511 let mut discovered = BTreeMap::new();
512
513 if let Some(home) = options.home_dir.as_deref() {
514 let user_templates = user_prompts_dir(home).join(TEMPLATES_DIR);
515 merge_prompt_templates(&mut discovered, &user_templates, PromptResourceScope::User).await;
516 }
517
518 let workspace_templates = options.workspace_root.join(PROMPTS_DIR).join(TEMPLATES_DIR);
519 merge_prompt_templates(&mut discovered, &workspace_templates, PromptResourceScope::Workspace).await;
520
521 discovered.into_values().collect()
522}
523
524async fn find_prompt_template_with_options(options: PromptResourceOptions<'_>, name: &str) -> Option<PromptTemplate> {
525 if !is_safe_template_name(name) {
526 return None;
527 }
528
529 discover_prompt_templates_with_options(options)
530 .await
531 .into_iter()
532 .find(|template| template.name == name)
533}
534
535async fn merge_prompt_templates(
536 discovered: &mut BTreeMap<String, PromptTemplate>,
537 directory: &Path,
538 scope: PromptResourceScope,
539) {
540 let Ok(mut entries) = fs::read_dir(directory).await else {
541 return;
542 };
543
544 let mut markdown_files = Vec::new();
545 loop {
546 match entries.next_entry().await {
547 Ok(Some(entry)) => {
548 let path = entry.path();
549 if path.extension().and_then(|ext| ext.to_str()) == Some("md") {
550 markdown_files.push(path);
551 }
552 }
553 Ok(None) => break,
554 Err(err) => {
555 warn!("failed to read prompt templates directory {}: {}", directory.display(), err);
556 break;
557 }
558 }
559 }
560
561 markdown_files.sort();
562
563 for path in markdown_files {
564 let Some(name) = path
565 .file_stem()
566 .and_then(|stem| stem.to_str())
567 .map(str::trim)
568 .filter(|stem| !stem.is_empty())
569 .map(str::to_string)
570 else {
571 continue;
572 };
573
574 match load_prompt_template(&path, name.clone()).await {
575 Some(template) => {
576 if matches!(scope, PromptResourceScope::Workspace) {
577 discovered.insert(name, template);
578 } else {
579 discovered.entry(name).or_insert(template);
580 }
581 }
582 None => continue,
583 }
584 }
585}
586
587async fn load_prompt_template(path: &Path, name: String) -> Option<PromptTemplate> {
588 let raw = read_optional_markdown(path).await?;
589 let normalized = normalize_newlines(&raw);
590 let (frontmatter, body) = parse_frontmatter(&normalized);
591 let description = frontmatter
592 .description
593 .filter(|value| !value.trim().is_empty())
594 .unwrap_or_else(|| derive_template_description(&body, &name));
595
596 Some(PromptTemplate {
597 name,
598 description,
599 body: body.trim().to_string(),
600 path: path.to_path_buf(),
601 })
602}
603
604async fn read_optional_markdown(path: &Path) -> Option<String> {
605 match fs::read_to_string(path).await {
606 Ok(contents) => Some(contents),
607 Err(err) if err.kind() == std::io::ErrorKind::NotFound => None,
608 Err(err) => {
609 warn!("failed to read prompt resource {}: {}", path.display(), err);
610 None
611 }
612 }
613}
614
615fn parse_frontmatter(content: &str) -> (PromptTemplateFrontmatter, String) {
616 if !content.starts_with("---\n") {
617 return (PromptTemplateFrontmatter::default(), content.to_string());
618 }
619
620 let Some(frontmatter_end) = content[4..].find("\n---\n").map(|idx| idx + 4) else {
621 return (PromptTemplateFrontmatter::default(), content.to_string());
622 };
623
624 let yaml = &content[4..frontmatter_end];
625 let body_start = frontmatter_end + 5;
626 let body = if body_start < content.len() {
627 content[body_start..].to_string()
628 } else {
629 String::new()
630 };
631
632 let metadata = match serde_saphyr::from_str::<PromptTemplateFrontmatter>(yaml.trim()) {
633 Ok(value) => value,
634 Err(err) => {
635 warn!("failed to parse prompt template frontmatter: {}", err);
636 PromptTemplateFrontmatter::default()
637 }
638 };
639
640 (metadata, body)
641}
642
643fn derive_template_description(body: &str, name: &str) -> String {
644 for line in body.lines().map(str::trim) {
645 if line.is_empty() {
646 continue;
647 }
648 if let Some(heading) = line.strip_prefix('#') {
649 let trimmed = heading.trim_start_matches('#').trim();
650 if !trimmed.is_empty() {
651 return trimmed.to_string();
652 }
653 }
654 return line.to_string();
655 }
656
657 format!("Prompt template `{name}`")
658}
659
660fn normalize_newlines(content: &str) -> String {
661 content.replace("\r\n", "\n")
662}
663
664fn is_safe_template_name(name: &str) -> bool {
665 !name.is_empty() && !name.contains('/') && !name.contains('\\') && !name.contains("..")
666}
667
668#[cfg(test)]
669mod tests {
670 use super::*;
671 use serial_test::serial;
672
673 async fn discover_with_roots(workspace: &Path, home: Option<&Path>) -> Vec<PromptTemplate> {
674 discover_prompt_templates_with_options(PromptResourceOptions {
675 workspace_root: workspace,
676 home_dir: home.map(Path::to_path_buf),
677 })
678 .await
679 }
680
681 async fn layers_with_roots(workspace: &Path, home: Option<&Path>) -> SystemPromptLayers {
682 resolve_system_prompt_layers_with_options(PromptResourceOptions {
683 workspace_root: workspace,
684 home_dir: home.map(Path::to_path_buf),
685 })
686 .await
687 }
688
689 async fn find_with_roots(workspace: &Path, home: Option<&Path>, name: &str) -> Option<PromptTemplate> {
690 find_prompt_template_with_options(
691 PromptResourceOptions {
692 workspace_root: workspace,
693 home_dir: home.map(Path::to_path_buf),
694 },
695 name,
696 )
697 .await
698 }
699
700 #[tokio::test]
701 #[serial]
702 async fn system_layers_reuse_process_wide_cache_until_cleared() {
703 clear_prompt_resource_caches();
704
705 let workspace = tempfile::TempDir::new().expect("workspace");
706 let home = tempfile::TempDir::new().expect("home");
707 let workspace_prompts = workspace.path().join(PROMPTS_DIR);
708 std::fs::create_dir_all(&workspace_prompts).expect("workspace prompts");
709 std::fs::write(workspace_prompts.join(SYSTEM_PROMPT_FILENAME), "workspace system override")
710 .expect("write workspace system");
711
712 let first = layers_with_roots(workspace.path(), Some(home.path())).await;
713 assert_eq!(first.override_body.as_deref(), Some("workspace system override"));
714
715 std::fs::remove_file(workspace_prompts.join(SYSTEM_PROMPT_FILENAME)).expect("remove workspace system");
716
717 let second = layers_with_roots(workspace.path(), Some(home.path())).await;
718 assert_eq!(second.override_body.as_deref(), Some("workspace system override"));
719
720 clear_prompt_resource_caches();
721
722 let third = layers_with_roots(workspace.path(), Some(home.path())).await;
723 assert_eq!(third.override_body, None);
724 }
725
726 #[tokio::test]
727 #[serial]
728 async fn prompt_template_discovery_reuses_process_wide_cache_until_cleared() {
729 clear_prompt_resource_caches();
730
731 let workspace = tempfile::TempDir::new().expect("workspace");
732 let home = tempfile::TempDir::new().expect("home");
733 let workspace_templates = workspace.path().join(PROMPTS_DIR).join(TEMPLATES_DIR);
734 std::fs::create_dir_all(&workspace_templates).expect("workspace templates");
735 std::fs::write(workspace_templates.join("cache-test.md"), "# Cache test\n\nBody")
736 .expect("write workspace template");
737
738 let first = discover_with_roots(workspace.path(), Some(home.path())).await;
739 assert!(first.iter().any(|template| template.name == "cache-test"));
740
741 std::fs::remove_file(workspace_templates.join("cache-test.md")).expect("remove workspace template");
742
743 let second = discover_with_roots(workspace.path(), Some(home.path())).await;
744 assert!(!second.iter().any(|template| template.name == "cache-test"));
745 assert!(
746 find_with_roots(workspace.path(), Some(home.path()), "cache-test")
747 .await
748 .is_none()
749 );
750
751 clear_prompt_resource_caches();
752
753 let third = discover_with_roots(workspace.path(), Some(home.path())).await;
754 assert!(!third.iter().any(|template| template.name == "cache-test"));
755 assert!(
756 find_with_roots(workspace.path(), Some(home.path()), "cache-test")
757 .await
758 .is_none()
759 );
760 }
761
762 #[tokio::test]
763 async fn system_layers_prefer_workspace_override_and_append_user_then_workspace() {
764 let workspace = tempfile::TempDir::new().expect("workspace");
765 let home = tempfile::TempDir::new().expect("home");
766
767 let user_prompts = home.path().join(PROMPTS_DIR);
768 let workspace_prompts = workspace.path().join(PROMPTS_DIR);
769 std::fs::create_dir_all(&user_prompts).expect("user prompts");
770 std::fs::create_dir_all(&workspace_prompts).expect("workspace prompts");
771
772 std::fs::write(user_prompts.join(SYSTEM_PROMPT_FILENAME), "user system override").expect("write user system");
773 std::fs::write(workspace_prompts.join(SYSTEM_PROMPT_FILENAME), "workspace system override")
774 .expect("write workspace system");
775 std::fs::write(user_prompts.join(APPEND_SYSTEM_PROMPT_FILENAME), "user append").expect("write user append");
776 std::fs::write(workspace_prompts.join(APPEND_SYSTEM_PROMPT_FILENAME), "workspace append")
777 .expect("write workspace append");
778
779 let layers = layers_with_roots(workspace.path(), Some(home.path())).await;
780 assert_eq!(layers.override_body.as_deref(), Some("workspace system override"));
781 assert_eq!(layers.append_bodies, vec!["user append".to_string(), "workspace append".to_string()]);
782
783 let composed = apply_system_prompt_layers("fallback base", &layers);
784 assert_eq!(composed, "workspace system override\n\nuser append\n\nworkspace append");
785 }
786
787 #[test]
788 fn applied_text_matches_spliced_layer_bodies() {
789 let layers = SystemPromptLayers {
790 override_body: Some(" workspace override ".to_string()),
791 append_bodies: vec![
792 " ".to_string(),
793 "user append".to_string(),
794 " workspace append ".to_string(),
795 ],
796 };
797 assert_eq!(layers.applied_text(), "workspace override\n\nuser append\n\nworkspace append");
798 assert_eq!(apply_system_prompt_layers("fallback base", &layers), layers.applied_text());
800 }
801
802 #[test]
803 fn applied_text_appends_follow_base_without_override() {
804 let layers = SystemPromptLayers {
805 override_body: None,
806 append_bodies: vec!["first append".to_string(), "second append".to_string()],
807 };
808 assert_eq!(layers.applied_text(), "first append\n\nsecond append");
809 let composed = apply_system_prompt_layers("BASE", &layers);
810 assert_eq!(composed, "BASE\n\nfirst append\n\nsecond append");
811 }
812
813 #[test]
814 fn applied_text_is_empty_without_effective_layers() {
815 let layers = SystemPromptLayers {
816 override_body: Some(" ".to_string()),
817 append_bodies: vec![" ".to_string()],
818 };
819 assert!(layers.applied_text().is_empty());
820 assert_eq!(apply_system_prompt_layers("fallback base", &layers), "fallback base");
821 assert!(SystemPromptLayers::default().applied_text().is_empty());
822 }
823
824 #[tokio::test]
825 async fn template_discovery_prefers_workspace_and_derives_descriptions() {
826 let workspace = tempfile::TempDir::new().expect("workspace");
827 let home = tempfile::TempDir::new().expect("home");
828 let user_templates = home.path().join(PROMPTS_DIR).join(TEMPLATES_DIR);
829 let workspace_templates = workspace.path().join(PROMPTS_DIR).join(TEMPLATES_DIR);
830 std::fs::create_dir_all(&user_templates).expect("user templates");
831 std::fs::create_dir_all(&workspace_templates).expect("workspace templates");
832
833 std::fs::write(user_templates.join("review.md"), "---\ndescription: User review template\n---\nReview $1")
834 .expect("user review");
835 std::fs::write(workspace_templates.join("review.md"), "# Workspace review\n\nReview workspace $1")
836 .expect("workspace review");
837 std::fs::write(workspace_templates.join("audit.md"), "First non-empty line becomes description.\n\nAudit $@")
838 .expect("workspace audit");
839
840 let templates = discover_with_roots(workspace.path(), Some(home.path())).await;
841 assert_eq!(templates.len(), 2);
842 assert_eq!(templates[0].name, "audit");
843 assert_eq!(templates[0].description, "First non-empty line becomes description.");
844 assert_eq!(templates[1].name, "review");
845 assert_eq!(templates[1].description, "Workspace review");
846 assert_eq!(templates[1].body, "# Workspace review\n\nReview workspace $1");
847 }
848
849 #[tokio::test]
850 async fn direct_template_lookup_uses_workspace_precedence() {
851 let workspace = tempfile::TempDir::new().expect("workspace");
852 let home = tempfile::TempDir::new().expect("home");
853 let user_templates = home.path().join(PROMPTS_DIR).join(TEMPLATES_DIR);
854 let workspace_templates = workspace.path().join(PROMPTS_DIR).join(TEMPLATES_DIR);
855 std::fs::create_dir_all(&user_templates).expect("user templates");
856 std::fs::create_dir_all(&workspace_templates).expect("workspace templates");
857
858 std::fs::write(user_templates.join("review.md"), "User review body").expect("user template");
859 std::fs::write(workspace_templates.join("review.md"), "Workspace review body").expect("workspace template");
860
861 let template = find_with_roots(workspace.path(), Some(home.path()), "review")
862 .await
863 .expect("template");
864 assert_eq!(template.body, "Workspace review body");
865 }
866
867 #[tokio::test]
868 async fn direct_template_lookup_rejects_unsafe_names() {
869 let workspace = tempfile::TempDir::new().expect("workspace");
870 let home = tempfile::TempDir::new().expect("home");
871
872 let template = find_with_roots(workspace.path(), Some(home.path()), "../escape").await;
873 assert!(template.is_none());
874 }
875
876 #[test]
877 fn template_expansion_supports_positional_and_all_arguments() {
878 let expanded = expand_prompt_template(
879 "Review $1 against $2.\nArgs: $@\nAgain: $ARGUMENTS\nMissing: '$3'",
880 &["src/lib.rs".to_string(), "main".to_string()],
881 );
882
883 assert_eq!(
884 expanded,
885 "Review src/lib.rs against main.\nArgs: src/lib.rs main\nAgain: src/lib.rs main\nMissing: ''"
886 );
887 }
888
889 struct TestEntry {
890 timestamp: SystemTime,
891 expired: bool,
892 }
893
894 impl ExpirableCacheEntry for TestEntry {
895 fn is_expired(&self) -> bool {
896 self.expired
897 }
898
899 fn timestamp(&self) -> SystemTime {
900 self.timestamp
901 }
902 }
903
904 fn full_live_cache(now: SystemTime) -> HashMap<u32, TestEntry> {
905 (0..PROMPT_RESOURCE_CACHE_MAX_ENTRIES as u32)
906 .map(|i| {
907 (
908 i,
909 TestEntry {
910 timestamp: now - Duration::from_secs((i + 1) as u64 * 60),
912 expired: false,
913 },
914 )
915 })
916 .collect()
917 }
918
919 #[test]
920 fn evict_if_full_removes_oldest_live_entry_at_budget() {
921 let now = SystemTime::now();
922 let mut cache = full_live_cache(now);
923 assert_eq!(cache.len(), PROMPT_RESOURCE_CACHE_MAX_ENTRIES);
924
925 evict_if_full(&mut cache, &u32::MAX);
926 assert_eq!(cache.len(), PROMPT_RESOURCE_CACHE_MAX_ENTRIES - 1);
927 assert!(!cache.contains_key(&(PROMPT_RESOURCE_CACHE_MAX_ENTRIES as u32 - 1)));
929 assert!(cache.contains_key(&0));
930 }
931
932 #[test]
933 fn evict_if_full_prefers_expired_over_oldest_live_and_keeps_present_keys() {
934 let now = SystemTime::now();
935 let mut cache = full_live_cache(now);
936 cache.insert(0, TestEntry { timestamp: now, expired: true });
938
939 evict_if_full(&mut cache, &u32::MAX);
940 assert!(!cache.contains_key(&0));
941 assert!(cache.contains_key(&(PROMPT_RESOURCE_CACHE_MAX_ENTRIES as u32 - 1)));
942
943 let mut full = full_live_cache(now);
945 evict_if_full(&mut full, &0);
946 assert_eq!(full.len(), PROMPT_RESOURCE_CACHE_MAX_ENTRIES);
947
948 full.remove(&0);
950 evict_if_full(&mut full, &u32::MAX);
951 assert_eq!(full.len(), PROMPT_RESOURCE_CACHE_MAX_ENTRIES - 1);
952 assert!(full.contains_key(&1));
953 }
954
955 #[test]
956 fn newest_mtime_is_order_independent_and_ignores_missing_paths() {
957 let dir = tempfile::TempDir::new().expect("tempdir");
958 let older = dir.path().join("older.md");
959 let newer = dir.path().join("newer.md");
960 std::fs::write(&older, "old").expect("write older");
961 std::fs::write(&newer, "new").expect("write newer");
962 let base = SystemTime::now();
963 std::fs::File::options()
964 .write(true)
965 .open(&older)
966 .expect("open older")
967 .set_modified(base - Duration::from_secs(100))
968 .expect("set older mtime");
969 std::fs::File::options()
970 .write(true)
971 .open(&newer)
972 .expect("open newer")
973 .set_modified(base)
974 .expect("set newer mtime");
975 let missing = dir.path().join("missing.md");
976
977 let forward = newest_mtime([older.as_path(), newer.as_path()]);
979 let reversed = newest_mtime([newer.as_path(), older.as_path()]);
980 assert_eq!(forward, reversed);
981 assert!(forward > base - Duration::from_secs(100));
982
983 assert_eq!(newest_mtime([missing.as_path(), older.as_path(), newer.as_path()]), forward);
986 assert_eq!(newest_mtime([missing.as_path()]), SystemTime::UNIX_EPOCH);
987 assert_eq!(newest_mtime(Vec::<&Path>::new()), SystemTime::UNIX_EPOCH);
988 }
989}