1use std::collections::HashMap;
17
18use md5::{Digest, Md5};
19
20#[derive(Debug, Clone)]
22pub struct CacheableSection {
23 pub id: String,
24 pub content: String,
25 pub hash: String,
26 pub priority: SectionPriority,
27 pub stable: bool,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
31pub enum SectionPriority {
32 System = 0,
33 ProjectStructure = 1,
34 TypeDefinitions = 2,
35 Dependencies = 3,
36 RecentContext = 4,
37 CurrentTask = 5,
38}
39
40#[derive(Debug)]
42pub struct ProviderCacheState {
43 sent_hashes: HashMap<String, String>,
44 cache_hits: u64,
45 cache_misses: u64,
46}
47
48impl ProviderCacheState {
49 pub fn new() -> Self {
50 Self {
51 sent_hashes: HashMap::new(),
52 cache_hits: 0,
53 cache_misses: 0,
54 }
55 }
56
57 pub fn needs_update(&self, section: &CacheableSection) -> bool {
59 match self.sent_hashes.get(§ion.id) {
60 Some(prev_hash) => prev_hash != §ion.hash,
61 None => true,
62 }
63 }
64
65 pub fn mark_sent(&mut self, section: &CacheableSection) {
67 self.sent_hashes
68 .insert(section.id.clone(), section.hash.clone());
69 }
70
71 pub fn filter_changed<'a>(
74 &mut self,
75 sections: &'a [CacheableSection],
76 ) -> Vec<&'a CacheableSection> {
77 let mut result = Vec::new();
78 for section in sections {
79 if self.needs_update(section) {
80 self.cache_misses += 1;
81 result.push(section);
82 } else {
83 self.cache_hits += 1;
84 }
85 }
86 result
87 }
88
89 pub fn cache_hit_rate(&self) -> f64 {
90 let total = self.cache_hits + self.cache_misses;
91 if total == 0 {
92 return 0.0;
93 }
94 self.cache_hits as f64 / total as f64
95 }
96
97 pub fn reset(&mut self) {
98 self.sent_hashes.clear();
99 self.cache_hits = 0;
100 self.cache_misses = 0;
101 }
102}
103
104impl Default for ProviderCacheState {
105 fn default() -> Self {
106 Self::new()
107 }
108}
109
110impl CacheableSection {
111 pub fn new(id: &str, content: String, priority: SectionPriority, stable: bool) -> Self {
112 let hash = content_hash(&content);
113 Self {
114 id: id.to_string(),
115 content,
116 hash,
117 priority,
118 stable,
119 }
120 }
121}
122
123pub fn order_for_caching(mut sections: Vec<CacheableSection>) -> Vec<CacheableSection> {
127 sections.sort_by(|a, b| {
128 a.stable
129 .cmp(&b.stable)
130 .reverse()
131 .then(a.priority.cmp(&b.priority))
132 });
133 sections
134}
135
136pub fn render_with_cache_hints(sections: &[CacheableSection]) -> String {
138 let mut output = String::new();
139 let mut last_stable = true;
140
141 for section in sections {
142 if last_stable && !section.stable {
143 output.push_str("\n--- dynamic context ---\n");
144 }
145 output.push_str(§ion.content);
146 output.push('\n');
147 last_stable = section.stable;
148 }
149
150 output
151}
152
153fn content_hash(content: &str) -> String {
154 let mut hasher = Md5::new();
155 hasher.update(content.as_bytes());
156 crate::core::agent_identity::hex_encode(&hasher.finalize())
157}
158
159#[cfg(test)]
160pub mod tests {
161 use super::*;
162
163 #[test]
164 fn section_hash_deterministic() {
165 let s1 = CacheableSection::new("id", "content".into(), SectionPriority::System, true);
166 let s2 = CacheableSection::new("id", "content".into(), SectionPriority::System, true);
167 assert_eq!(s1.hash, s2.hash);
168 }
169
170 #[test]
171 fn section_hash_changes_with_content() {
172 let s1 = CacheableSection::new("id", "content_v1".into(), SectionPriority::System, true);
173 let s2 = CacheableSection::new("id", "content_v2".into(), SectionPriority::System, true);
174 assert_ne!(s1.hash, s2.hash);
175 }
176
177 #[test]
178 fn needs_update_new_section() {
179 let state = ProviderCacheState::new();
180 let section =
181 CacheableSection::new("test", "content".into(), SectionPriority::System, true);
182 assert!(state.needs_update(§ion));
183 }
184
185 #[test]
186 fn needs_update_unchanged() {
187 let mut state = ProviderCacheState::new();
188 let section =
189 CacheableSection::new("test", "content".into(), SectionPriority::System, true);
190 state.mark_sent(§ion);
191 assert!(!state.needs_update(§ion));
192 }
193
194 #[test]
195 fn needs_update_changed() {
196 let mut state = ProviderCacheState::new();
197 let s1 = CacheableSection::new("test", "v1".into(), SectionPriority::System, true);
198 state.mark_sent(&s1);
199 let s2 = CacheableSection::new("test", "v2".into(), SectionPriority::System, true);
200 assert!(state.needs_update(&s2));
201 }
202
203 #[test]
204 fn filter_changed_tracks_hits() {
205 let mut state = ProviderCacheState::new();
206 let s1 = CacheableSection::new("a", "stable".into(), SectionPriority::System, true);
207 state.mark_sent(&s1);
208
209 let sections = vec![
210 s1.clone(),
211 CacheableSection::new("b", "new".into(), SectionPriority::CurrentTask, false),
212 ];
213 let changed = state.filter_changed(§ions);
214 assert_eq!(changed.len(), 1);
215 assert_eq!(changed[0].id, "b");
216 assert!((state.cache_hit_rate() - 0.5).abs() < 1e-6);
217 }
218
219 #[test]
220 fn order_stable_first() {
221 let sections = vec![
222 CacheableSection::new(
223 "task",
224 "current".into(),
225 SectionPriority::CurrentTask,
226 false,
227 ),
228 CacheableSection::new("system", "system".into(), SectionPriority::System, true),
229 CacheableSection::new(
230 "types",
231 "types".into(),
232 SectionPriority::TypeDefinitions,
233 true,
234 ),
235 ];
236 let ordered = order_for_caching(sections);
237 assert!(ordered[0].stable);
238 assert!(ordered[1].stable);
239 assert!(!ordered[2].stable);
240 assert_eq!(ordered[0].id, "system");
241 assert_eq!(ordered[1].id, "types");
242 }
243
244 #[test]
245 fn render_marks_dynamic_boundary() {
246 let sections = vec![
247 CacheableSection::new("sys", "system prompt".into(), SectionPriority::System, true),
248 CacheableSection::new(
249 "task",
250 "current task".into(),
251 SectionPriority::CurrentTask,
252 false,
253 ),
254 ];
255 let output = render_with_cache_hints(§ions);
256 assert!(output.contains("--- dynamic context ---"));
257 assert!(output.contains("system prompt"));
258 assert!(output.contains("current task"));
259 }
260}