Skip to main content

vtcode_core/prompts/
few_shot.rs

1//! Minimal few-shot example infrastructure.
2//!
3//! Implements a keyword-based selector with token-budget enforcement
4//! per Section 18.3.3 of the agentic-AI guide:
5//!
6//! > Few-shot examples improve reliability but consume tokens. The harness
7//! > should select relevant examples using embedding similarity to the
8//! > current query, rotate examples to avoid overfitting, budget examples
9//! > within the model allocation, and cache embeddings of the example
10//! > library to avoid recomputation.
11//!
12//! This module ships the keyword-based selector (no embedding provider
13//! dependency) and the token-budget enforcement (via
14//! [`vtcode_commons::tokens::estimate_tokens`]). Embedding-based selection
15//! and embedding-cache can layer on top later without changing the API.
16//!
17//! ## Example file format
18//!
19//! Examples live under `<workspace>/.vtcode/prompts/examples/*.md` or
20//! the canonical user config prompts directory's `examples/*.md`. The filename stem is the
21//! stable id; the file body uses YAML frontmatter for metadata:
22//!
23//! ```markdown
24//! ---
25//! id: read-then-edit-large-file
26//! tags: [read, edit, large-file, patch]
27//! summary: Read a large file in chunks, then patch with apply_patch.
28//! ---
29//! # User
30//! Refactor src/foo.rs to use the new API.
31//!
32//! # Assistant
33//! (the example body showing expected tool sequence)
34//! ```
35//!
36//! Both `tags` and `summary` are optional; the loader derives sensible
37//! defaults when they are absent.
38
39use std::collections::HashMap;
40use std::path::{Path, PathBuf};
41use std::sync::{Arc, OnceLock};
42
43use compact_str::CompactString;
44use serde::Deserialize;
45use tracing::warn;
46use vtcode_commons::tokens::estimate_tokens;
47
48use super::resource_cache::{ResourceCache, canonical_cache_path, fingerprint_markdown_directories};
49
50const EXAMPLES_DIR: &str = "examples";
51const PROMPTS_PARENT: &str = ".vtcode/prompts";
52const MIN_TOKEN_BUDGET: usize = 16;
53
54fn user_examples_dir(home: &Path) -> PathBuf {
55    super::resources::user_prompts_dir(home).join(EXAMPLES_DIR)
56}
57
58/// Default token budget for the `[Few-Shot Examples]` block. ~10% of an 8K
59/// context window, leaving the remainder for the base prompt, tools,
60/// history, and the model's response.
61pub const DEFAULT_FEW_SHOT_BUDGET_TOKENS: usize = 800;
62
63/// First line of every rendered few-shot block. The runloop persists the
64/// block in history once per user turn and recognizes it by this header.
65pub const FEW_SHOT_SECTION_HEADER: &str = "[Few-Shot Examples]";
66
67/// A single few-shot example loaded from disk.
68///
69/// The `id` field is the filename stem (e.g. `read-then-edit-large-file`).
70/// `tags` drive keyword selection; `summary` is for debug logs; `body` is
71/// the raw markdown body that flows verbatim into the prompt. `token_count`
72/// is filled on load and refreshed lazily on first selection.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct FewShotExample {
75    pub id: String,
76    pub tags: Vec<String>,
77    pub summary: String,
78    pub body: String,
79    pub token_count: usize,
80    pub source_path: PathBuf,
81}
82
83/// YAML frontmatter schema. All fields are optional so authoring mistakes
84/// fail soft (loader falls back to derived defaults).
85#[derive(Debug, Clone, Default, Deserialize)]
86struct FewShotFrontmatter {
87    #[serde(default)]
88    id: Option<String>,
89    #[serde(default)]
90    tags: Option<Vec<String>>,
91    #[serde(default)]
92    summary: Option<String>,
93}
94
95/// Library of few-shot examples discovered from disk.
96///
97/// Construct via [`FewShotStore::load`] to read from both the workspace
98/// `.vtcode/prompts/examples/` and the canonical user config prompts directory
99/// directories. The constructor is fail-soft: unreadable files or bad
100/// frontmatter are skipped with a warning, not a panic.
101#[derive(Debug, Clone, Default)]
102pub struct FewShotStore {
103    examples: Vec<FewShotExample>,
104    normalized_tags: Vec<Vec<CompactString>>,
105}
106
107impl FewShotStore {
108    /// Load all examples from the workspace + home directories. The
109    /// workspace directory takes precedence on `id` collision (the home
110    /// copy is skipped with a warning).
111    ///
112    /// Pass `workspace_root = Some("/path")` and `home_dir = None` to
113    /// load only the workspace; pass `home_dir = Some("/home/user")` to
114    /// also pull user-global examples.
115    ///
116    /// The returned store shares the cached allocation: warm loads bump a
117    /// refcount instead of cloning every example body.
118    pub fn load(workspace_root: Option<&Path>, home_dir: Option<&Path>) -> Arc<Self> {
119        let key = FewShotCacheKey::new(workspace_root, home_dir);
120        load_cached_sync(key, workspace_root.map(Path::to_path_buf), home_dir.map(Path::to_path_buf))
121    }
122
123    /// Load examples without performing cache-key or cache-miss filesystem
124    /// work on a Tokio worker. Warm loads still use the blocking pool because
125    /// canonicalizing a new source path may touch the filesystem.
126    pub async fn load_async(workspace_root: Option<&Path>, home_dir: Option<&Path>) -> Arc<Self> {
127        let workspace_root = workspace_root.map(Path::to_path_buf);
128        let home_dir = home_dir.map(Path::to_path_buf);
129        match tokio::task::spawn_blocking(move || {
130            // Canonicalization may touch the filesystem for a first-time
131            // source path, so keep key construction on the blocking pool too.
132            let key = FewShotCacheKey::new(workspace_root.as_deref(), home_dir.as_deref());
133            load_cached_sync(key, workspace_root, home_dir)
134        })
135        .await
136        {
137            Ok(store) => store,
138            Err(error) => {
139                warn!(%error, "few-shot resource load task failed");
140                Arc::new(Self::default())
141            }
142        }
143    }
144
145    /// Construct a store from an in-memory list. Useful for tests and for
146    /// loading examples that come from somewhere other than disk.
147    pub fn from_examples(examples: Vec<FewShotExample>) -> Self {
148        let mut sorted = examples;
149        sorted.sort_by(|a, b| a.id.cmp(&b.id));
150        let normalized_tags = sorted.iter().map(|example| normalize_tags(&example.tags)).collect();
151        Self { examples: sorted, normalized_tags }
152    }
153
154    /// Number of loaded examples.
155    pub fn len(&self) -> usize {
156        self.examples.len()
157    }
158
159    pub fn is_empty(&self) -> bool {
160        self.examples.is_empty()
161    }
162
163    /// Select examples whose tags overlap with the query, capped at
164    /// `budget_tokens`. Returns examples in score-descending order
165    /// (ties broken by id ascending).
166    ///
167    /// Scoring rule:
168    /// - +1.0 for each exact match between a tag and a query word
169    /// - +0.5 for each tag that appears as a substring of the query
170    ///
171    /// `budget_tokens` of 0 (or any value smaller than the smallest
172    /// example) returns an empty selection. Examples whose token_count
173    /// alone exceeds the budget are skipped.
174    pub fn select(&self, query: &str, budget_tokens: usize) -> Vec<&FewShotExample> {
175        if self.examples.is_empty() || budget_tokens < MIN_TOKEN_BUDGET {
176            return Vec::new();
177        }
178
179        let query_words = tokenize(query);
180        if query_words.is_empty() {
181            return Vec::new();
182        }
183        let query_lower = query.to_ascii_lowercase();
184
185        let mut scored: Vec<(f64, &FewShotExample)> = self
186            .examples
187            .iter()
188            .zip(&self.normalized_tags)
189            .filter_map(|(example, normalized_tags)| {
190                let score = score_example(normalized_tags, &query_words, &query_lower);
191                if score <= 0.0 {
192                    return None;
193                }
194                Some((score, example))
195            })
196            .collect();
197
198        // Stable ordering: score desc, then id asc.
199        scored.sort_by(|a, b| {
200            b.0.partial_cmp(&a.0)
201                .unwrap_or(std::cmp::Ordering::Equal)
202                .then_with(|| a.1.id.cmp(&b.1.id))
203        });
204
205        let mut chosen: Vec<&FewShotExample> = Vec::new();
206        let mut used = 0usize;
207        for (_, example) in scored {
208            if example.token_count == 0 {
209                // Defensive: skip examples that failed to size on load.
210                continue;
211            }
212            if used.saturating_add(example.token_count) > budget_tokens {
213                continue;
214            }
215            chosen.push(example);
216            used = used.saturating_add(example.token_count);
217        }
218
219        chosen
220    }
221}
222
223/// Render selected examples into the prompt section body. Returns an
224/// empty string when `examples` is empty so callers can `writeln!` it
225/// unconditionally.
226pub fn render_few_shot_section(examples: &[&FewShotExample]) -> String {
227    if examples.is_empty() {
228        return String::new();
229    }
230
231    let mut out = String::new();
232    out.push_str(FEW_SHOT_SECTION_HEADER);
233    out.push_str("\nThe following examples illustrate expected behavior for similar tasks.\n\n");
234    for example in examples {
235        let _ = std::fmt::Write::write_fmt(&mut out, format_args!("### {}\n", example.id));
236        if !example.summary.is_empty() {
237            let _ = std::fmt::Write::write_fmt(&mut out, format_args!("_{}_\n\n", example.summary));
238        }
239        let _ = std::fmt::Write::write_fmt(&mut out, format_args!("{}\n\n", example.body.trim_end()));
240    }
241    out
242}
243
244// ---------------------------------------------------------------------------
245// Internals
246// ---------------------------------------------------------------------------
247
248#[derive(Debug, Clone, PartialEq, Eq, Hash)]
249struct FewShotCacheKey {
250    workspace_examples_dir: Option<PathBuf>,
251    home_examples_dir: Option<PathBuf>,
252}
253
254impl FewShotCacheKey {
255    fn new(workspace_root: Option<&Path>, home_dir: Option<&Path>) -> Self {
256        Self {
257            workspace_examples_dir: workspace_root
258                .map(|root| canonical_cache_path(&root.join(PROMPTS_PARENT).join(EXAMPLES_DIR))),
259            home_examples_dir: home_dir.map(|home| canonical_cache_path(&user_examples_dir(home))),
260        }
261    }
262}
263
264static FEW_SHOT_CACHE: OnceLock<ResourceCache<FewShotCacheKey, FewShotStore>> = OnceLock::new();
265
266fn few_shot_cache() -> &'static ResourceCache<FewShotCacheKey, FewShotStore> {
267    FEW_SHOT_CACHE.get_or_init(ResourceCache::default)
268}
269
270fn load_cached_sync(
271    key: FewShotCacheKey,
272    workspace_root: Option<PathBuf>,
273    home_dir: Option<PathBuf>,
274) -> Arc<FewShotStore> {
275    if let Some(cached) = few_shot_cache().fast_get(&key) {
276        return cached;
277    }
278
279    few_shot_cache().with_load_gate(|| {
280        if let Some(cached) = few_shot_cache().fast_get(&key) {
281            return cached;
282        }
283
284        let source_dirs = key
285            .workspace_examples_dir
286            .iter()
287            .chain(key.home_examples_dir.iter())
288            .map(PathBuf::as_path)
289            .collect::<Vec<_>>();
290        let fingerprint = fingerprint_markdown_directories(&source_dirs);
291        if let Some(cached) = few_shot_cache().get_if_unchanged(&key, &fingerprint) {
292            return cached;
293        }
294
295        let store = load_uncached(workspace_root.as_deref(), home_dir.as_deref());
296        few_shot_cache().insert(key, store.clone(), fingerprint);
297        Arc::new(store)
298    })
299}
300
301fn load_uncached(workspace_root: Option<&Path>, home_dir: Option<&Path>) -> FewShotStore {
302    let mut by_id: HashMap<String, FewShotExample> = HashMap::new();
303
304    // Keep the workspace copy when an id collides with a user-global copy.
305    if let Some(workspace) = workspace_root {
306        merge_from_dir(&mut by_id, &workspace.join(PROMPTS_PARENT).join(EXAMPLES_DIR));
307    }
308
309    if let Some(home) = home_dir {
310        merge_from_dir(&mut by_id, &user_examples_dir(home));
311    }
312
313    FewShotStore::from_examples(by_id.into_values().collect())
314}
315
316fn merge_from_dir(by_id: &mut HashMap<String, FewShotExample>, dir: &Path) {
317    let entries = match std::fs::read_dir(dir) {
318        Ok(entries) => entries,
319        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return,
320        Err(err) => {
321            warn!("few_shot: failed to read directory {}: {err}", dir.display());
322            return;
323        }
324    };
325
326    let mut paths: Vec<PathBuf> = entries
327        .filter_map(Result::ok)
328        .map(|entry| entry.path())
329        .filter(|path| {
330            path.is_file()
331                && path
332                    .extension()
333                    .and_then(|ext| ext.to_str())
334                    .map(|ext| ext.eq_ignore_ascii_case("md"))
335                    .unwrap_or(false)
336        })
337        .collect();
338    paths.sort();
339
340    for path in paths {
341        let Some(stem) = path
342            .file_stem()
343            .and_then(|s| s.to_str())
344            .map(str::trim)
345            .filter(|s| !s.is_empty())
346        else {
347            continue;
348        };
349
350        let Ok(raw) = std::fs::read_to_string(&path) else {
351            warn!("few_shot: could not read {}", path.display());
352            continue;
353        };
354
355        if let Some(existing) = by_id.get(stem) {
356            warn!(
357                "few_shot: duplicate id '{stem}' ({}); keeping earlier {}",
358                path.display(),
359                existing.source_path.display()
360            );
361            continue;
362        }
363
364        match parse_example(stem, &raw, &path) {
365            Ok(example) => {
366                by_id.insert(stem.to_string(), example);
367            }
368            Err(err) => {
369                warn!("few_shot: failed to parse {}: {err}", path.display());
370            }
371        }
372    }
373}
374
375fn parse_example(fallback_id: &str, raw: &str, source_path: &Path) -> Result<FewShotExample, String> {
376    let (frontmatter, body) = parse_frontmatter(raw);
377    let id = frontmatter
378        .id
379        .map(|value| value.trim().to_string())
380        .filter(|value| !value.is_empty())
381        .unwrap_or_else(|| fallback_id.to_string());
382    let tags = frontmatter.tags.unwrap_or_default();
383    let summary = frontmatter.summary.map(|value| value.trim().to_string()).unwrap_or_default();
384    let body = body.trim().to_string();
385    let token_count = estimate_tokens(&body);
386
387    Ok(FewShotExample {
388        id,
389        tags,
390        summary,
391        body,
392        token_count,
393        source_path: source_path.to_path_buf(),
394    })
395}
396
397fn parse_frontmatter(raw: &str) -> (FewShotFrontmatter, String) {
398    let trimmed = raw.trim_start_matches('\u{feff}');
399    if !trimmed.starts_with("---\n") {
400        return (FewShotFrontmatter::default(), raw.to_string());
401    }
402    let Some(end_rel) = trimmed[4..].find("\n---") else {
403        return (FewShotFrontmatter::default(), raw.to_string());
404    };
405    let yaml = &trimmed[4..4 + end_rel];
406    let body_start = 4 + end_rel + "\n---".len();
407    let body = trimmed[body_start..].trim_start_matches('\n').to_string();
408
409    let frontmatter = match serde_saphyr::from_str::<FewShotFrontmatter>(yaml) {
410        Ok(value) => value,
411        Err(err) => {
412            warn!("few_shot: frontmatter parse failed: {err}");
413            FewShotFrontmatter::default()
414        }
415    };
416
417    (frontmatter, body)
418}
419
420fn tokenize(query: &str) -> Vec<String> {
421    query
422        .split(|c: char| !c.is_alphanumeric() && c != '_' && c != '-')
423        .filter(|token| !token.is_empty())
424        .map(|token| token.to_ascii_lowercase())
425        .collect()
426}
427
428fn normalize_tags(tags: &[String]) -> Vec<CompactString> {
429    tags.iter().map(|tag| CompactString::from(tag.to_ascii_lowercase())).collect()
430}
431
432fn score_example(normalized_tags: &[CompactString], query_words: &[String], query_lower: &str) -> f64 {
433    let mut score = 0.0;
434    for tag in normalized_tags {
435        if query_words.iter().any(|word| word == tag.as_str()) {
436            score += 1.0;
437            continue;
438        }
439        if query_lower.contains(tag.as_str()) {
440            score += 0.5;
441        }
442    }
443    score
444}
445
446// ---------------------------------------------------------------------------
447// Tests
448// ---------------------------------------------------------------------------
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453    use std::path::PathBuf;
454
455    fn example(id: &str, tags: &[&str], body: &str) -> FewShotExample {
456        let token_count = estimate_tokens(body);
457        FewShotExample {
458            id: id.to_string(),
459            tags: tags.iter().map(|s| s.to_string()).collect(),
460            summary: String::new(),
461            body: body.to_string(),
462            token_count,
463            source_path: PathBuf::from(format!("/tmp/{id}.md")),
464        }
465    }
466
467    #[test]
468    fn empty_store_returns_empty_selection() {
469        let store = FewShotStore::default();
470        assert!(store.select("anything", 1000).is_empty());
471    }
472
473    #[test]
474    fn zero_budget_returns_empty() {
475        let store = FewShotStore::from_examples(vec![example("edit", &["edit"], "do an edit")]);
476        assert!(store.select("edit a file", 0).is_empty());
477        assert!(store.select("edit a file", 8).is_empty());
478    }
479
480    #[test]
481    fn matching_tag_is_selected() {
482        let store = FewShotStore::from_examples(vec![
483            example("edit", &["edit"], "an edit example"),
484            example("search", &["search"], "a search example"),
485        ]);
486        let chosen = store.select("please edit foo.rs", 1000);
487        assert_eq!(chosen.len(), 1);
488        assert_eq!(chosen[0].id, "edit");
489    }
490
491    #[test]
492    fn no_overlap_returns_empty() {
493        let store = FewShotStore::from_examples(vec![example("deploy", &["deploy", "kubernetes"], "a deploy example")]);
494        let chosen = store.select("read a local file", 1000);
495        assert!(chosen.is_empty());
496    }
497
498    #[test]
499    fn example_exceeding_budget_is_skipped() {
500        // Two examples, both 50 tokens. Budget = 60 keeps only one.
501        let store = FewShotStore::from_examples(vec![
502            example("a", &["foo"], &"foo ".repeat(50)),
503            example("b", &["foo"], &"foo ".repeat(50)),
504        ]);
505        let chosen = store.select("foo bar", 60);
506        assert_eq!(chosen.len(), 1);
507        assert_eq!(chosen[0].id, "a"); // id-asc tiebreak
508    }
509
510    #[test]
511    fn multiple_matches_sorted_by_score_then_id() {
512        let store = FewShotStore::from_examples(vec![
513            // "git" matches as both a word and substring, plus "commit".
514            example("git-commit", &["git", "commit"], "git commit example"),
515            // Only one tag matches.
516            example("git-only", &["git"], "git only example"),
517            // Different id but same score as git-only.
518            example("zzz-other", &["git"], "git other example"),
519        ]);
520        let chosen = store.select("git commit message", 5000);
521        // git-commit scores highest (git + commit).
522        assert_eq!(chosen[0].id, "git-commit");
523        // The remaining two tie on score, sorted by id asc.
524        let rest: Vec<&str> = chosen.iter().skip(1).map(|e| e.id.as_str()).collect();
525        assert_eq!(rest, vec!["git-only", "zzz-other"]);
526    }
527
528    #[test]
529    fn parse_frontmatter_extracts_metadata() {
530        let raw = "---\nid: read-then-edit\ntags: [read, edit]\nsummary: read first\n---\nbody here\n";
531        let (fm, body) = parse_frontmatter(raw);
532        assert_eq!(fm.id.as_deref(), Some("read-then-edit"));
533        assert_eq!(fm.tags, Some(vec!["read".to_string(), "edit".to_string()]));
534        assert_eq!(fm.summary.as_deref(), Some("read first"));
535        // Body keeps a trailing newline (callers should .trim() if needed);
536        // parse_example does that for FewShotExample.body.
537        assert_eq!(body, "body here\n");
538    }
539
540    #[test]
541    fn parse_frontmatter_without_metadata_returns_body() {
542        let raw = "no frontmatter here\nbody text\n";
543        let (fm, body) = parse_frontmatter(raw);
544        assert!(fm.id.is_none());
545        assert_eq!(body, raw);
546    }
547
548    #[test]
549    fn render_section_is_empty_when_no_examples() {
550        assert!(render_few_shot_section(&[]).is_empty());
551    }
552
553    #[test]
554    fn render_section_includes_id_and_body() {
555        let store =
556            FewShotStore::from_examples(vec![example("demo", &["hi", "demo"], "user said hi\nassistant said hello")]);
557        let chosen = store.select("hi there", 1000);
558        let rendered = render_few_shot_section(&chosen);
559        assert!(rendered.starts_with(FEW_SHOT_SECTION_HEADER));
560        assert!(rendered.contains("[Few-Shot Examples]\nThe following examples illustrate"));
561        assert!(rendered.contains("### demo"));
562        assert!(rendered.contains("user said hi"));
563    }
564
565    #[test]
566    fn load_discovers_examples_from_disk() {
567        let workspace = tempfile::tempdir().expect("workspace");
568        let examples_dir = workspace.path().join(".vtcode/prompts/examples");
569        std::fs::create_dir_all(&examples_dir).expect("mkdir");
570        std::fs::write(examples_dir.join("demo.md"), "---\ntags: [demo]\nsummary: a demo\n---\nDemo body\n")
571            .expect("write");
572
573        let store = FewShotStore::load(Some(workspace.path()), None);
574        assert_eq!(store.len(), 1);
575        let only = &store.examples[0];
576        assert_eq!(only.id, "demo");
577        assert_eq!(only.tags, vec!["demo".to_string()]);
578        assert_eq!(only.summary, "a demo");
579        assert!(only.body.contains("Demo body"));
580        assert!(only.token_count > 0);
581    }
582
583    #[test]
584    fn load_silently_skips_missing_directories() {
585        // No directories exist; load must succeed with zero examples.
586        let store = FewShotStore::load(Some(Path::new("/does/not/exist/anywhere")), None);
587        assert!(store.is_empty());
588    }
589
590    #[test]
591    #[serial_test::serial]
592    fn warm_loads_share_the_cached_store_without_cloning() {
593        // Asymmetric: the cold load parses (its Arc is fresh), but consecutive
594        // warm loads must hand out the same allocation (ptr_eq), not a deep
595        // clone of every example body. The per-turn caller only borrows a
596        // budgeted selection, so sharing is the whole point of the cache.
597        few_shot_cache().clear();
598        let workspace = tempfile::tempdir().expect("workspace");
599        let examples_dir = workspace.path().join(PROMPTS_PARENT).join(EXAMPLES_DIR);
600        std::fs::create_dir_all(&examples_dir).expect("mkdir");
601        std::fs::write(examples_dir.join("demo.md"), "---\ntags: [demo]\n---\nDemo body\n").expect("write");
602
603        let first = FewShotStore::load(Some(workspace.path()), None);
604        assert_eq!(first.len(), 1);
605        let second = FewShotStore::load(Some(workspace.path()), None);
606        let third = FewShotStore::load(Some(workspace.path()), None);
607        assert_eq!(second.len(), 1);
608        assert!(Arc::ptr_eq(&second, &third), "warm loads must share the cached store");
609    }
610
611    #[test]
612    #[serial_test::serial]
613    fn load_preserves_workspace_precedence_and_refreshes_edits() {
614        few_shot_cache().clear();
615        let workspace = tempfile::tempdir().expect("workspace");
616        let home = tempfile::tempdir().expect("home");
617        let workspace_dir = workspace.path().join(PROMPTS_PARENT).join(EXAMPLES_DIR);
618        let home_dir = home.path().join(PROMPTS_PARENT).join(EXAMPLES_DIR);
619        std::fs::create_dir_all(&workspace_dir).expect("workspace examples");
620        std::fs::create_dir_all(&home_dir).expect("home examples");
621        std::fs::write(home_dir.join("review.md"), "---\ntags: [review]\n---\nhome\n").expect("home example");
622        std::fs::write(workspace_dir.join("review.md"), "---\ntags: [review]\n---\nworkspace\n")
623            .expect("workspace example");
624
625        let first = FewShotStore::load(Some(workspace.path()), Some(home.path()));
626        assert_eq!(first.examples[0].body, "workspace");
627
628        std::fs::write(workspace_dir.join("review.md"), "---\ntags: [review]\n---\nupdated\n").expect("edit example");
629        few_shot_cache().force_metadata_poll();
630        let second = FewShotStore::load(Some(workspace.path()), Some(home.path()));
631        assert_eq!(second.examples[0].body, "updated");
632    }
633
634    #[test]
635    #[serial_test::serial]
636    fn cache_detects_additions_deletions_and_missing_sources() {
637        few_shot_cache().clear();
638        let workspace = tempfile::tempdir().expect("workspace");
639        let examples_dir = workspace.path().join(PROMPTS_PARENT).join(EXAMPLES_DIR);
640
641        assert!(FewShotStore::load(Some(workspace.path()), None).is_empty());
642        std::fs::create_dir_all(&examples_dir).expect("examples directory");
643        std::fs::write(examples_dir.join("one.md"), "---\ntags: [one]\n---\none\n").expect("one example");
644        few_shot_cache().force_metadata_poll();
645        assert_eq!(FewShotStore::load(Some(workspace.path()), None).len(), 1);
646
647        std::fs::remove_file(examples_dir.join("one.md")).expect("remove example");
648        few_shot_cache().force_metadata_poll();
649        assert!(FewShotStore::load(Some(workspace.path()), None).is_empty());
650    }
651
652    #[test]
653    #[serial_test::serial]
654    fn expired_cache_entry_reparses_even_when_metadata_is_unchanged() {
655        few_shot_cache().clear();
656        let workspace = tempfile::tempdir().expect("workspace");
657        let examples_dir = workspace.path().join(PROMPTS_PARENT).join(EXAMPLES_DIR);
658        std::fs::create_dir_all(&examples_dir).expect("examples directory");
659        std::fs::write(examples_dir.join("ttl.md"), "---\ntags: [ttl]\n---\nold\n").expect("old example");
660
661        let first = FewShotStore::load(Some(workspace.path()), None);
662        assert_eq!(first.examples[0].body, "old");
663        std::fs::write(examples_dir.join("ttl.md"), "---\ntags: [ttl]\n---\nnew\n").expect("new example");
664        few_shot_cache().force_expiration();
665        let second = FewShotStore::load(Some(workspace.path()), None);
666        assert_eq!(second.examples[0].body, "new");
667    }
668
669    #[test]
670    #[serial_test::serial]
671    fn cache_hit_preserves_rendered_few_shot_prompt() {
672        few_shot_cache().clear();
673        let workspace = tempfile::tempdir().expect("workspace");
674        let examples_dir = workspace.path().join(PROMPTS_PARENT).join(EXAMPLES_DIR);
675        std::fs::create_dir_all(&examples_dir).expect("examples directory");
676        std::fs::write(
677            examples_dir.join("render.md"),
678            "---\ntags: [render]\nsummary: Stable output\n---\nRender this example.\n",
679        )
680        .expect("render example");
681
682        let cold = FewShotStore::load(Some(workspace.path()), None);
683        let cold_selected = cold.select("render", DEFAULT_FEW_SHOT_BUDGET_TOKENS);
684        let cold_rendered = render_few_shot_section(&cold_selected);
685
686        let warm = FewShotStore::load(Some(workspace.path()), None);
687        let warm_selected = warm.select("render", DEFAULT_FEW_SHOT_BUDGET_TOKENS);
688        let warm_rendered = render_few_shot_section(&warm_selected);
689        assert_eq!(cold_rendered, warm_rendered);
690    }
691
692    #[tokio::test(flavor = "current_thread")]
693    #[serial_test::serial]
694    async fn concurrent_cache_misses_share_the_parsed_store() {
695        few_shot_cache().clear();
696        let workspace = tempfile::tempdir().expect("workspace");
697        let examples_dir = workspace.path().join(PROMPTS_PARENT).join(EXAMPLES_DIR);
698        std::fs::create_dir_all(&examples_dir).expect("examples directory");
699        std::fs::write(examples_dir.join("concurrent.md"), "---\ntags: [concurrent]\n---\nbody\n").expect("example");
700
701        let (first, second) = tokio::join!(
702            FewShotStore::load_async(Some(workspace.path()), None),
703            FewShotStore::load_async(Some(workspace.path()), None),
704        );
705        assert_eq!(first.examples, second.examples);
706    }
707}