1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
//! Sub-agent result caching.
//!
//! Caches sub-agent results keyed by `(agent_name, prompt_hash)` within a
//! session. On cache hit, returns the previous response immediately —
//! zero-cost retries for compaction-triggered re-planning.
//!
//! ## Why this exists
//!
//! After compaction, the model sometimes re-issues the same sub-agent
//! call (it forgot it already ran). Without caching, this burns tokens
//! and time re-running identical work. The cache makes this free.
//!
//! ## Invalidation
//!
//! Cache entries are invalidated when files are mutated (piggybacks on
//! `FileReadCache` mtime tracking via a generation counter). This ensures
//! stale results aren't served after the codebase changes.
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
/// Cache key: (agent_name, prompt_hash).
type CacheKey = (String, u64);
/// Shared sub-agent result cache.
///
/// Wrapped in `Arc<Mutex<>>` so parent and parallel sub-agents can share it.
#[derive(Clone, Debug)]
pub struct SubAgentCache {
inner: Arc<Mutex<CacheInner>>,
}
#[derive(Debug)]
struct CacheInner {
entries: HashMap<CacheKey, CachedResult>,
/// Monotonically increasing counter bumped on every file mutation.
/// Entries stored with a stale generation are considered invalid.
generation: u64,
}
#[derive(Debug, Clone)]
struct CachedResult {
response: String,
generation: u64,
}
impl SubAgentCache {
/// Create a new empty cache.
pub fn new() -> Self {
Self {
inner: Arc::new(Mutex::new(CacheInner {
entries: HashMap::new(),
generation: 0,
})),
}
}
/// Look up a cached result for the given agent + prompt.
///
/// Returns `Some(response)` on cache hit (and generation is current),
/// `None` on miss or stale entry.
pub fn get(&self, agent_name: &str, prompt: &str) -> Option<String> {
let key = make_key(agent_name, prompt);
let inner = self.inner.lock().ok()?;
let entry = inner.entries.get(&key)?;
if entry.generation == inner.generation {
Some(entry.response.clone())
} else {
None
}
}
/// Store a sub-agent result in the cache.
pub fn put(&self, agent_name: &str, prompt: &str, response: &str) {
let key = make_key(agent_name, prompt);
if let Ok(mut inner) = self.inner.lock() {
let current_gen = inner.generation;
inner.entries.insert(
key,
CachedResult {
response: response.to_string(),
generation: current_gen,
},
);
}
}
/// Invalidate all cache entries by bumping the generation counter.
///
/// Call this when any file mutation occurs (Write, Edit, Delete, Bash)
/// to ensure stale sub-agent results aren't reused.
pub fn invalidate(&self) {
if let Ok(mut inner) = self.inner.lock() {
inner.generation += 1;
}
}
/// Number of entries in the cache (for diagnostics/testing).
pub fn len(&self) -> usize {
self.inner
.lock()
.map(|inner| inner.entries.len())
.unwrap_or(0)
}
/// Whether the cache is empty.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Default for SubAgentCache {
fn default() -> Self {
Self::new()
}
}
/// Build the cache key from agent name + hash of the prompt.
fn make_key(agent_name: &str, prompt: &str) -> CacheKey {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
prompt.hash(&mut hasher);
(agent_name.to_string(), hasher.finish())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cache_hit_after_put() {
let cache = SubAgentCache::new();
cache.put("reviewer", "review this code", "looks good!");
assert_eq!(
cache.get("reviewer", "review this code"),
Some("looks good!".to_string())
);
}
#[test]
fn cache_miss_different_prompt() {
let cache = SubAgentCache::new();
cache.put("reviewer", "review this code", "looks good!");
assert_eq!(cache.get("reviewer", "review OTHER code"), None);
}
#[test]
fn cache_miss_different_agent() {
let cache = SubAgentCache::new();
cache.put("reviewer", "review this", "looks good!");
assert_eq!(cache.get("testgen", "review this"), None);
}
#[test]
fn invalidation_clears_stale_entries() {
let cache = SubAgentCache::new();
cache.put("reviewer", "prompt", "result");
assert!(cache.get("reviewer", "prompt").is_some());
cache.invalidate();
assert_eq!(cache.get("reviewer", "prompt"), None);
}
#[test]
fn entries_after_invalidation_are_fresh() {
let cache = SubAgentCache::new();
cache.put("reviewer", "old prompt", "old result");
cache.invalidate();
cache.put("reviewer", "new prompt", "new result");
// Old entry is stale
assert_eq!(cache.get("reviewer", "old prompt"), None);
// New entry is fresh
assert_eq!(
cache.get("reviewer", "new prompt"),
Some("new result".to_string())
);
}
#[test]
fn len_tracks_entries() {
let cache = SubAgentCache::new();
assert!(cache.is_empty());
cache.put("a", "p1", "r1");
cache.put("b", "p2", "r2");
assert_eq!(cache.len(), 2);
}
#[test]
fn shared_across_clones() {
let cache = SubAgentCache::new();
let clone = cache.clone();
cache.put("agent", "prompt", "result");
assert_eq!(clone.get("agent", "prompt"), Some("result".to_string()));
}
}