| 1 | //! Process-local cache for project context loading. |
| 2 | //! |
| 3 | //! The project-context loader sits on prompt/session hot paths and repeatedly |
| 4 | //! checks the same workspace, parent, global, constitution, and trust files. |
| 5 | //! This cache avoids rereading unchanged context while keeping the signature |
| 6 | //! broad enough for the loader's side effects and authority surfaces. |
| 7 | |
| 8 | use std::cell::RefCell; |
| 9 | use std::collections::{HashMap, VecDeque}; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | |
| 12 | use sha2::{Digest, Sha256}; |
| 13 | |
| 14 | use crate::project_context::ProjectContext; |
| 15 | |
| 16 | const DEFAULT_CAPACITY: usize = 8; |
| 17 | |
| 18 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 19 | pub struct CacheKey { |
| 20 | workspace: PathBuf, |
| 21 | signature: ContentSignature, |
| 22 | settings: String, |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] |
| 26 | struct ContentSignature { |
| 27 | entries: Vec<ContentEntry>, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 31 | struct ContentEntry { |
| 32 | path: PathBuf, |
| 33 | read_root: Option<PathBuf>, |
| 34 | canonical_path: Option<PathBuf>, |
| 35 | symlink_components: Vec<PathBuf>, |
| 36 | fingerprint: Option<String>, |
| 37 | } |
| 38 | |
| 39 | #[derive(Debug, Default)] |
| 40 | struct WorkspaceCache { |
| 41 | by_key: HashMap<CacheKey, ProjectContext>, |
| 42 | order: VecDeque<CacheKey>, |
| 43 | } |
| 44 | |
| 45 | thread_local! { |
| 46 | static CACHE: RefCell<WorkspaceCache> = RefCell::new(WorkspaceCache::default()); |
| 47 | } |
| 48 | |
| 49 | pub fn lookup(key: &CacheKey) -> Option<ProjectContext> { |
| 50 | CACHE.with(|cache| cache.borrow().by_key.get(key).cloned()) |
| 51 | } |
| 52 | |
| 53 | pub fn store(key: CacheKey, value: ProjectContext) { |
| 54 | CACHE.with(|cache| { |
| 55 | let mut cache = cache.borrow_mut(); |
| 56 | if cache.by_key.insert(key.clone(), value).is_none() { |
| 57 | cache.order.push_back(key); |
| 58 | } |
| 59 | while cache.by_key.len() > DEFAULT_CAPACITY { |
| 60 | let Some(oldest) = cache.order.pop_front() else { |
| 61 | break; |
| 62 | }; |
| 63 | cache.by_key.remove(&oldest); |
| 64 | } |
| 65 | }); |
| 66 | } |
| 67 | |
| 68 | /// Drop every cached entry. |
| 69 | /// |
| 70 | /// Used by tests. |
| 71 | #[cfg(any(test, feature = "test-support"))] |
| 72 | pub fn clear() { |
| 73 | CACHE.with(|cache| { |
| 74 | let mut cache = cache.borrow_mut(); |
| 75 | cache.by_key.clear(); |
| 76 | cache.order.clear(); |
| 77 | }); |
| 78 | } |
| 79 | |
| 80 | #[must_use] |
| 81 | #[cfg(any(test, feature = "test-support"))] |
| 82 | pub fn compute_cache_key(workspace: &Path, home_dir: Option<&Path>) -> CacheKey { |
| 83 | compute_cache_key_with_settings( |
| 84 | workspace, |
| 85 | &crate::project_context::InstructionSettings { |
| 86 | home: home_dir.map(Path::to_path_buf), |
| 87 | ..Default::default() |
| 88 | }, |
| 89 | ) |
| 90 | } |
| 91 | |
| 92 | pub fn compute_cache_key_with_settings( |
| 93 | workspace: &Path, |
| 94 | settings: &crate::project_context::InstructionSettings, |
| 95 | ) -> CacheKey { |
| 96 | let workspace = canonicalize_or_keep(workspace); |
| 97 | CacheKey { |
| 98 | signature: ContentSignature::for_loader(&workspace, settings.home.as_deref()), |
| 99 | workspace, |
| 100 | settings: format!("{settings:?}"), |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | impl ContentSignature { |
| 105 | fn for_loader(workspace: &Path, home_dir: Option<&Path>) -> Self { |
| 106 | let mut entries: Vec<ContentEntry> = |
| 107 | crate::project_context::project_context_cache_candidate_paths(workspace, home_dir) |
| 108 | .into_iter() |
| 109 | .map(|(path, read_root)| ContentEntry { |
| 110 | canonical_path: std::fs::canonicalize(&path).ok(), |
| 111 | symlink_components: path |
| 112 | .ancestors() |
| 113 | .filter(|component| { |
| 114 | std::fs::symlink_metadata(component) |
| 115 | .is_ok_and(|metadata| metadata.file_type().is_symlink()) |
| 116 | }) |
| 117 | .map(Path::to_path_buf) |
| 118 | .collect(), |
| 119 | fingerprint: file_fingerprint(&path, read_root.as_deref()), |
| 120 | path, |
| 121 | read_root, |
| 122 | }) |
| 123 | .collect(); |
| 124 | |
| 125 | entries.sort_by(|a, b| (&a.path, &a.read_root).cmp(&(&b.path, &b.read_root))); |
| 126 | entries.dedup_by(|a, b| a.path == b.path && a.read_root == b.read_root); |
| 127 | |
| 128 | Self { entries } |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// Largest candidate hashed by content. The context loader skips files over |
| 133 | /// its 8 MiB ceiling whatever they hold, so a larger candidate is |
| 134 | /// fingerprinted by length and mtime instead of being read on every refresh. |
| 135 | const FINGERPRINT_MAX_READ_BYTES: u64 = 8 * 1024 * 1024; |
| 136 | |
| 137 | fn file_fingerprint(path: &Path, read_root: Option<&Path>) -> Option<String> { |
| 138 | let file = match read_root.map_or_else( |
| 139 | || codewhale_util::fs_confined::open_user_read(path), |
| 140 | |root| codewhale_util::fs_confined::open_read_linked_within(root, path), |
| 141 | ) { |
| 142 | Ok(file) => file, |
| 143 | Err(error) => return Some(format!("unreadable:{error}")), |
| 144 | }; |
| 145 | let metadata = file.metadata().ok()?; |
| 146 | if !metadata.is_file() { |
| 147 | return Some("non-file".to_string()); |
| 148 | } |
| 149 | let modified = || { |
| 150 | metadata |
| 151 | .modified() |
| 152 | .ok() |
| 153 | .and_then(|mtime| mtime.duration_since(std::time::UNIX_EPOCH).ok()) |
| 154 | .map(|duration| format!("{}:{}", duration.as_secs(), duration.subsec_nanos())) |
| 155 | .unwrap_or_else(|| "unknown".to_string()) |
| 156 | }; |
| 157 | if metadata.len() > FINGERPRINT_MAX_READ_BYTES { |
| 158 | return Some(format!("oversize:{}:{}", metadata.len(), modified())); |
| 159 | } |
| 160 | |
| 161 | let read: std::io::Result<_> = (|| { |
| 162 | use std::io::Read as _; |
| 163 | let mut hasher = Sha256::new(); |
| 164 | let mut limited = file.take(FINGERPRINT_MAX_READ_BYTES + 1); |
| 165 | let mut buffer = [0u8; 64 * 1024]; |
| 166 | loop { |
| 167 | let read = limited.read(&mut buffer)?; |
| 168 | if read == 0 { |
| 169 | break; |
| 170 | } |
| 171 | hasher.update(&buffer[..read]); |
| 172 | } |
| 173 | Ok(hasher.finalize()) |
| 174 | })(); |
| 175 | match read { |
| 176 | Ok(digest) => Some(format!("sha256:{}", to_hex(&digest))), |
| 177 | Err(error) => Some(format!( |
| 178 | "unreadable:{}:{}:{error}", |
| 179 | metadata.len(), |
| 180 | modified() |
| 181 | )), |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | fn canonicalize_or_keep(path: &Path) -> PathBuf { |
| 186 | std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()) |
| 187 | } |
| 188 | |
| 189 | fn to_hex(bytes: &[u8]) -> String { |
| 190 | let mut out = String::with_capacity(bytes.len() * 2); |
| 191 | for byte in bytes { |
| 192 | use std::fmt::Write as _; |
| 193 | let _ = write!(&mut out, "{byte:02x}"); |
| 194 | } |
| 195 | out |
| 196 | } |
| 197 | |
| 198 | #[cfg(test)] |
| 199 | mod tests { |
| 200 | use super::*; |
| 201 | use std::fs; |
| 202 | use tempfile::tempdir; |
| 203 | |
| 204 | #[test] |
| 205 | fn cache_round_trip() { |
| 206 | clear(); |
| 207 | let key = CacheKey { |
| 208 | workspace: PathBuf::from("/tmp/context-cache-round-trip"), |
| 209 | signature: ContentSignature::default(), |
| 210 | settings: String::new(), |
| 211 | }; |
| 212 | let ctx = ProjectContext::empty(PathBuf::from("/tmp/context-cache-round-trip")); |
| 213 | |
| 214 | store(key.clone(), ctx.clone()); |
| 215 | |
| 216 | let got = lookup(&key).expect("cache hit"); |
| 217 | assert_eq!(got.project_root, ctx.project_root); |
| 218 | } |
| 219 | |
| 220 | #[test] |
| 221 | fn store_does_not_grow_unbounded() { |
| 222 | clear(); |
| 223 | for i in 0..(DEFAULT_CAPACITY + 4) { |
| 224 | let key = CacheKey { |
| 225 | workspace: PathBuf::from(format!("/tmp/workspace-{i}")), |
| 226 | signature: ContentSignature::default(), |
| 227 | settings: String::new(), |
| 228 | }; |
| 229 | store(key, ProjectContext::empty(PathBuf::from("/tmp"))); |
| 230 | } |
| 231 | |
| 232 | let count = CACHE.with(|cache| cache.borrow().by_key.len()); |
| 233 | assert!(count <= DEFAULT_CAPACITY, "cache held {count} entries"); |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn cache_key_canonicalizes_equivalent_workspace_paths() { |
| 238 | let workspace = tempdir().expect("workspace"); |
| 239 | let home = tempdir().expect("home"); |
| 240 | let plain = compute_cache_key(workspace.path(), Some(home.path())); |
| 241 | let dotted = compute_cache_key(&workspace.path().join("."), Some(home.path())); |
| 242 | |
| 243 | assert_eq!(plain.workspace, dotted.workspace); |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn signature_changes_when_agents_md_is_overwritten_same_length() { |
| 248 | let workspace = tempdir().expect("workspace"); |
| 249 | let home = tempdir().expect("home"); |
| 250 | fs::write(workspace.path().join("AGENTS.md"), "alpha").expect("write alpha"); |
| 251 | let before = compute_cache_key(workspace.path(), Some(home.path())); |
| 252 | |
| 253 | fs::write(workspace.path().join("AGENTS.md"), "bravo").expect("write bravo"); |
| 254 | let after = compute_cache_key(workspace.path(), Some(home.path())); |
| 255 | |
| 256 | assert_ne!(before, after); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn signature_changes_when_constitution_json_changes() { |
| 261 | let workspace = tempdir().expect("workspace"); |
| 262 | let home = tempdir().expect("home"); |
| 263 | fs::create_dir(workspace.path().join(".git")).expect("mkdir git"); |
| 264 | fs::create_dir(workspace.path().join(".codewhale")).expect("mkdir codewhale"); |
| 265 | let constitution = workspace |
| 266 | .path() |
| 267 | .join(".codewhale") |
| 268 | .join("constitution.json"); |
| 269 | fs::write(&constitution, r#"{"schema_version":1,"authority":["a"]}"#) |
| 270 | .expect("write constitution a"); |
| 271 | let before = compute_cache_key(workspace.path(), Some(home.path())); |
| 272 | |
| 273 | fs::write(&constitution, r#"{"schema_version":1,"authority":["b"]}"#) |
| 274 | .expect("write constitution b"); |
| 275 | let after = compute_cache_key(workspace.path(), Some(home.path())); |
| 276 | |
| 277 | assert_ne!(before, after); |
| 278 | } |
| 279 | |
| 280 | #[test] |
| 281 | fn signature_changes_when_rules_file_changes() { |
| 282 | let workspace = tempdir().expect("workspace"); |
| 283 | let home = tempdir().expect("home"); |
| 284 | let rules_dir = workspace.path().join(".codewhale/rules"); |
| 285 | fs::create_dir_all(&rules_dir).expect("mkdir rules"); |
| 286 | fs::write(rules_dir.join("rule.md"), "alpha").expect("write alpha"); |
| 287 | |
| 288 | let before = compute_cache_key(workspace.path(), Some(home.path())); |
| 289 | |
| 290 | fs::write(rules_dir.join("rule.md"), "bravo").expect("write bravo"); |
| 291 | let after = compute_cache_key(workspace.path(), Some(home.path())); |
| 292 | |
| 293 | assert_ne!( |
| 294 | before, after, |
| 295 | "cache key must change when rules file changes" |
| 296 | ); |
| 297 | } |
| 298 | |
| 299 | #[test] |
| 300 | fn signature_changes_when_rules_file_is_added_or_removed() { |
| 301 | let workspace = tempdir().expect("workspace"); |
| 302 | let home = tempdir().expect("home"); |
| 303 | let rules_dir = workspace.path().join(".codewhale/rules"); |
| 304 | fs::create_dir_all(&rules_dir).expect("mkdir rules"); |
| 305 | |
| 306 | // No rules yet |
| 307 | let before = compute_cache_key(workspace.path(), Some(home.path())); |
| 308 | |
| 309 | fs::write(rules_dir.join("new.md"), "content").expect("write new.md"); |
| 310 | let after = compute_cache_key(workspace.path(), Some(home.path())); |
| 311 | |
| 312 | assert_ne!( |
| 313 | before, after, |
| 314 | "cache key must change when rules file is added" |
| 315 | ); |
| 316 | } |
| 317 | |
| 318 | #[test] |
| 319 | fn signature_tracks_foreign_fragment_add_change_and_remove() { |
| 320 | let workspace = tempdir().expect("workspace"); |
| 321 | let home = tempdir().expect("home"); |
| 322 | let cursor_rules = workspace.path().join(".cursor/rules"); |
| 323 | fs::create_dir_all(cursor_rules.join("nested")).expect("mkdir cursor rules"); |
| 324 | |
| 325 | let before = compute_cache_key(workspace.path(), Some(home.path())); |
| 326 | |
| 327 | // Files the bounded fragment loader cannot select must not churn the |
| 328 | // project-context cache. |
| 329 | fs::write(cursor_rules.join("settings.json"), "{}").expect("write ignored settings"); |
| 330 | let ignored = compute_cache_key(workspace.path(), Some(home.path())); |
| 331 | assert_eq!(before, ignored, "non-Markdown fragment files are ignored"); |
| 332 | |
| 333 | let rule = cursor_rules.join("nested/law.md"); |
| 334 | fs::write(&rule, "alpha").expect("write cursor rule"); |
| 335 | let added = compute_cache_key(workspace.path(), Some(home.path())); |
| 336 | assert_ne!(ignored, added, "adding a loadable fragment must invalidate"); |
| 337 | |
| 338 | fs::write(&rule, "bravo").expect("change cursor rule"); |
| 339 | let changed = compute_cache_key(workspace.path(), Some(home.path())); |
| 340 | assert_ne!(added, changed, "changing a fragment must invalidate"); |
| 341 | |
| 342 | fs::remove_file(&rule).expect("remove cursor rule"); |
| 343 | let removed = compute_cache_key(workspace.path(), Some(home.path())); |
| 344 | assert_eq!( |
| 345 | ignored, removed, |
| 346 | "removing the fragment restores the prior key" |
| 347 | ); |
| 348 | } |
| 349 | |
| 350 | #[cfg(unix)] |
| 351 | #[test] |
| 352 | fn signature_does_not_follow_symlinked_foreign_fragment_directories() { |
| 353 | use std::os::unix::fs::symlink; |
| 354 | |
| 355 | let workspace = tempdir().expect("workspace"); |
| 356 | let home = tempdir().expect("home"); |
| 357 | let outside = tempdir().expect("outside"); |
| 358 | fs::write(outside.path().join("law.md"), "outside law").expect("write outside rule"); |
| 359 | fs::create_dir_all(workspace.path().join(".cursor")).expect("mkdir cursor"); |
| 360 | |
| 361 | let before = compute_cache_key(workspace.path(), Some(home.path())); |
| 362 | symlink(outside.path(), workspace.path().join(".cursor/rules")) |
| 363 | .expect("symlink outside rules"); |
| 364 | let after = compute_cache_key(workspace.path(), Some(home.path())); |
| 365 | |
| 366 | assert_eq!( |
| 367 | before, after, |
| 368 | "cache fingerprinting must not read through a rejected fragment-directory symlink" |
| 369 | ); |
| 370 | } |
| 371 | } |
| 372 |