返回 CodeWhale
file_frecency.rs
根目录 / crates / tui / src / tui / file_frecency.rs
1 //! @-mention frecency tracking (#441).
2 //!
3 //! Records every file the user @-mentions with a timestamp and click count,
4 //! decays the score over time so a file that was hot last week ranks below
5 //! one mentioned 5 minutes ago, and re-orders mention-popup completions by
6 //! the resulting score. Persisted as a single JSONL file at
7 //! `$CODEWHALE_HOME/file-frecency.jsonl` (normally
8 //! `~/.codewhale/file-frecency.jsonl`) so frecency survives restarts.
9 //!
10 //! Append-only on the wire, rewritten when it grows: a background thread
11 //! replays each line into a `HashMap` keyed by workspace-scoped path, so
12 //! filesystem work stays off the UI thread. Unscoped older records remain
13 //! readable. We cap the in-memory map at 1000 entries and evict the
14 //! lowest-scored on overflow — same heuristic the OPENCODE source uses.
15
16 use std::collections::HashMap;
17 use std::collections::hash_map::Entry;
18 use std::fs::OpenOptions;
19 use std::io::{Read, Write};
20 use std::path::{Path, PathBuf};
21 use std::sync::atomic::{AtomicBool, Ordering};
22 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
23 use std::sync::{Mutex, OnceLock};
24 use std::time::{SystemTime, UNIX_EPOCH};
25
26 use serde::{Deserialize, Serialize};
27
28 /// Hard cap on the number of paths we track (the acceptance criterion for
29 /// #441). Older / lower-scored entries are evicted when the map exceeds
30 /// this.
31 const FRECENCY_CAP: usize = 1000;
32
33 /// Half-life of a frecency score, in seconds. After this many seconds the
34 /// score has decayed to ½ of its peak. 7 days is OPENCODE's default — long
35 /// enough that a commonly-edited file stays sticky across a workweek but
36 /// short enough that yesterday's deep-dive doesn't haunt you forever.
37 const HALF_LIFE_SECS: f64 = 7.0 * 24.0 * 60.0 * 60.0;
38
39 const MAX_FRECENCY_FILE_BYTES: u64 = 8 * 1024 * 1024;
40 const FRECENCY_COMPACT_BYTES: u64 = 512 * 1024;
41 const FRECENCY_QUEUE_CAPACITY: usize = 1024;
42
43 #[derive(Debug, Clone, Serialize, Deserialize)]
44 struct FrecencyRecord {
45 #[serde(default)]
46 workspace: String,
47 /// Workspace-relative path string.
48 path: String,
49 /// Total mentions over the lifetime of the entry.
50 count: u32,
51 /// Unix timestamp (seconds) of the last mention.
52 last_used: u64,
53 }
54
55 #[derive(Debug, Default)]
56 struct Store {
57 by_path: HashMap<String, FrecencyRecord>,
58 }
59
60 struct FrecencyWorker {
61 sender: SyncSender<FrecencyJob>,
62 }
63
64 struct FrecencyJob {
65 workspace: String,
66 path: String,
67 }
68
69 static LOADED_SIGNAL: AtomicBool = AtomicBool::new(false);
70
71 fn store() -> &'static Mutex<Store> {
72 static STORE: OnceLock<Mutex<Store>> = OnceLock::new();
73 STORE.get_or_init(|| Mutex::new(Store::default()))
74 }
75
76 fn worker() -> Option<&'static FrecencyWorker> {
77 static WORKER: OnceLock<Option<FrecencyWorker>> = OnceLock::new();
78 WORKER
79 .get_or_init(|| {
80 let path = default_path()?;
81 let (sender, receiver) = sync_channel(FRECENCY_QUEUE_CAPACITY);
82 let thread_store = store();
83 std::thread::Builder::new()
84 .name("codewhale-frecency".to_string())
85 .spawn(move || {
86 fn worker_main(store: &'static Mutex<Store>, path: PathBuf, jobs: Receiver<FrecencyJob>) {
87 merge_loaded_records(store, load_records(&path));
88 LOADED_SIGNAL.store(true, Ordering::Release);
89 for job in jobs {
90 persist_record(store, &path, &job.workspace, &job.path);
91 }
92 }
93
94 fn load_records(path: &Path) -> Vec<FrecencyRecord> {
95 if std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > MAX_FRECENCY_FILE_BYTES) {
96 tracing::debug!(target: "frecency", "ignoring oversized frecency store");
97 return Vec::new();
98 }
99 let Ok(file) = std::fs::File::open(path) else {
100 return Vec::new();
101 };
102 let mut bytes = Vec::new();
103 if file
104 .take(MAX_FRECENCY_FILE_BYTES + 1)
105 .read_to_end(&mut bytes)
106 .is_err()
107 {
108 return Vec::new();
109 }
110 if bytes.len() as u64 > MAX_FRECENCY_FILE_BYTES {
111 tracing::debug!(target: "frecency", "ignoring oversized frecency store");
112 return Vec::new();
113 }
114 let Ok(text) = String::from_utf8(bytes) else {
115 return Vec::new();
116 };
117 text.lines()
118 .filter_map(|line| serde_json::from_str(line).ok())
119 .collect()
120 }
121
122 fn merge_loaded_records(store: &'static Mutex<Store>, records: Vec<FrecencyRecord>) {
123 let mut loaded = HashMap::new();
124 for record in records {
125 loaded.insert(scoped_key(&record.workspace, &record.path), record);
126 }
127 let Ok(mut store) = store.lock() else {
128 return;
129 };
130 for (key, record) in loaded {
131 match store.by_path.entry(key) {
132 Entry::Occupied(mut entry) => {
133 let existing = entry.get_mut();
134 existing.count = existing.count.saturating_add(record.count);
135 existing.last_used = existing.last_used.max(record.last_used);
136 }
137 Entry::Vacant(entry) => {
138 entry.insert(record);
139 }
140 }
141 }
142 }
143
144 fn persist_record(store: &'static Mutex<Store>, store_path: &Path, workspace: &str, path: &str) {
145 let record = {
146 let Ok(store) = store.lock() else {
147 return;
148 };
149 let Some(record) = store.by_path.get(&scoped_key(workspace, path)) else {
150 return;
151 };
152 record.clone()
153 };
154 if let Err(err) = append_record_line(store_path, &record) {
155 tracing::debug!(target: "frecency", "persist failed: {err}");
156 return;
157 }
158 if std::fs::metadata(store_path).is_ok_and(|metadata| metadata.len() > FRECENCY_COMPACT_BYTES) {
159 compact_store(store, store_path);
160 }
161 }
162
163 fn compact_store(store: &'static Mutex<Store>, store_path: &Path) {
164 let records = {
165 let Ok(store) = store.lock() else {
166 return;
167 };
168 store.by_path.values().cloned().collect::<Vec<_>>()
169 };
170 let mut body = String::new();
171 for record in records {
172 let Ok(line) = serde_json::to_string(&record) else {
173 continue;
174 };
175 if body.len().saturating_add(line.len() + 1) > FRECENCY_COMPACT_BYTES as usize {
176 continue;
177 }
178 body.push_str(&line);
179 body.push('\n');
180 }
181 if let Err(err) = codewhale_util::utils::write_atomic(store_path, body.as_bytes()) {
182 tracing::debug!(target: "frecency", "compact failed: {err}");
183 }
184 }
185
186 worker_main(thread_store, path, receiver)
187 })
188 .map_err(|err| {
189 tracing::debug!(target: "frecency", "background store unavailable: {err}");
190 })
191 .ok()?;
192 Some(FrecencyWorker { sender })
193 })
194 .as_ref()
195 }
196
197 fn default_path() -> Option<PathBuf> {
198 // Unit tests exercise mention selection heavily and must never read from or
199 // append to a developer's real Codewhale home. Integration and release QA
200 // processes use an explicit isolated CODEWHALE_HOME instead.
201 #[cfg(test)]
202 {
203 None
204 }
205
206 #[cfg(not(test))]
207 {
208 codewhale_config::codewhale_home()
209 .ok()
210 .map(|home| home.join("file-frecency.jsonl"))
211 }
212 }
213
214 fn now_secs() -> u64 {
215 SystemTime::now()
216 .duration_since(UNIX_EPOCH)
217 .map(|d| d.as_secs())
218 .unwrap_or(0)
219 }
220
221 /// Time-decayed frecency score for a record, in arbitrary units. Mentions
222 /// count linearly; the whole sum is multiplied by an exponential decay
223 /// factor based on time since `last_used`. Records older than ~5 half-lives
224 /// score effectively zero.
225 fn decayed_score(record: &FrecencyRecord, now: u64) -> f64 {
226 let age_secs = now.saturating_sub(record.last_used) as f64;
227 let lambda = std::f64::consts::LN_2 / HALF_LIFE_SECS;
228 (record.count as f64) * (-lambda * age_secs).exp()
229 }
230
231 fn workspace_scope(workspace: &Path) -> String {
232 workspace.to_string_lossy().into_owned()
233 }
234
235 fn scoped_key(workspace: &str, path: &str) -> String {
236 if workspace.is_empty() {
237 path.to_string()
238 } else {
239 format!("{workspace}\u{0}{path}")
240 }
241 }
242
243 pub(crate) fn poll_loaded() -> bool {
244 LOADED_SIGNAL.swap(false, Ordering::AcqRel)
245 }
246
247 fn evict_to_cap(store: &mut Store, now: u64) {
248 if store.by_path.len() <= FRECENCY_CAP {
249 return;
250 }
251 let target = FRECENCY_CAP;
252 let mut scored: Vec<(String, f64)> = store
253 .by_path
254 .iter()
255 .map(|(k, v)| (k.clone(), decayed_score(v, now)))
256 .collect();
257 scored.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
258 let drop_count = store.by_path.len().saturating_sub(target);
259 for (key, _) in scored.iter().take(drop_count) {
260 store.by_path.remove(key);
261 }
262 }
263
264 fn append_record_line(path: &Path, record: &FrecencyRecord) -> std::io::Result<()> {
265 if let Some(parent) = path.parent() {
266 std::fs::create_dir_all(parent)?;
267 }
268 let mut file = OpenOptions::new().create(true).append(true).open(path)?;
269 let line = serde_json::to_string(record).map_err(std::io::Error::other)?;
270 writeln!(file, "{line}")?;
271 Ok(())
272 }
273
274 /// Record one mention of `path` (a workspace-relative path string). Updates
275 /// the in-memory store, queues a single JSONL line, and evicts the lowest-
276 /// scored entry if we just exceeded the cap. Best-effort: I/O failures are
277 /// logged and swallowed — losing a frecency datapoint is never worth
278 /// failing the user's `@` autocomplete.
279 pub fn record_mention(workspace: &Path, path: &str) {
280 if path.is_empty() {
281 return;
282 }
283 let worker = worker();
284 let store = store();
285 let Ok(mut store) = store.lock() else {
286 return;
287 };
288 let now = now_secs();
289 let scope = workspace_scope(workspace);
290 let key = scoped_key(&scope, path);
291 let legacy_count = if scope.is_empty() || store.by_path.contains_key(&key) {
292 0
293 } else {
294 store.by_path.get(path).map_or(0, |record| record.count)
295 };
296 let entry = store.by_path.entry(key).or_insert_with(|| FrecencyRecord {
297 workspace: scope.clone(),
298 path: path.to_string(),
299 count: legacy_count,
300 last_used: now,
301 });
302 entry.count = entry.count.saturating_add(1);
303 entry.last_used = now;
304 evict_to_cap(&mut store, now);
305 drop(store);
306 if let Some(worker) = worker {
307 let job = FrecencyJob {
308 workspace: scope,
309 path: path.to_string(),
310 };
311 if let Err(err) = worker.sender.try_send(job) {
312 tracing::debug!(target: "frecency", "persist queue: {err}");
313 }
314 }
315 }
316
317 /// Re-sort a candidate list by frecency score (highest first), preserving
318 /// the original order for ties so the underlying ranker's choices aren't
319 /// upended. Candidates the store has never seen score zero — they end up
320 /// at the bottom of the sort, which means a one-time mention will start
321 /// floating to the top after first use.
322 #[must_use]
323 pub fn rerank_by_frecency(workspace: &Path, candidates: Vec<String>) -> Vec<String> {
324 if candidates.len() <= 1 {
325 return candidates;
326 }
327 let _worker = worker();
328 let store = store();
329 let Ok(store) = store.lock() else {
330 return candidates;
331 };
332 let scope = workspace_scope(workspace);
333 let now = now_secs();
334 let mut scored: Vec<(usize, String, f64)> = candidates
335 .into_iter()
336 .enumerate()
337 .map(|(idx, path)| {
338 let score = store
339 .by_path
340 .get(&scoped_key(&scope, &path))
341 .or_else(|| store.by_path.get(&path))
342 .map(|record| decayed_score(record, now))
343 .unwrap_or(0.0);
344 (idx, path, score)
345 })
346 .collect();
347 // Stable sort on (-score, original-index): ties keep the underlying
348 // ranker's order.
349 scored.sort_by(|a, b| {
350 b.2.partial_cmp(&a.2)
351 .unwrap_or(std::cmp::Ordering::Equal)
352 .then_with(|| a.0.cmp(&b.0))
353 });
354 scored.into_iter().map(|(_, path, _)| path).collect()
355 }
356
357 #[cfg(test)]
358 mod tests {
359 use super::*;
360
361 /// Recently mentioned paths win against never-mentioned ones; never-mentioned
362 /// preserve their original ranker order.
363 #[test]
364 fn rerank_floats_recent_paths_to_the_top() {
365 // Use the global store; reset its state so we don't leak across tests.
366 let store = super::store();
367 let mut s = store.lock().unwrap();
368 s.by_path.clear();
369 let now = super::now_secs();
370 s.by_path.insert(
371 "src/popular.rs".into(),
372 FrecencyRecord {
373 workspace: String::new(),
374 path: "src/popular.rs".into(),
375 count: 8,
376 last_used: now,
377 },
378 );
379 drop(s);
380
381 let order = super::rerank_by_frecency(
382 std::path::Path::new("/workspace"),
383 vec![
384 "README.md".to_string(),
385 "src/popular.rs".to_string(),
386 "Cargo.toml".to_string(),
387 ],
388 );
389 assert_eq!(order[0], "src/popular.rs");
390 // README.md was first in original order; Cargo.toml second. Both score 0
391 // so the original relative order survives.
392 assert_eq!(order[1], "README.md");
393 assert_eq!(order[2], "Cargo.toml");
394 }
395
396 /// Decayed score drops below a freshly-used entry after enough half-lives
397 /// that count alone can't carry the older one. With a 7-day half-life,
398 /// 8 weeks gives 8 half-lives → ~256× decay; an entry mentioned twice
399 /// today comfortably beats one mentioned 50× two months ago.
400 #[test]
401 fn old_entries_decay_below_recent_ones() {
402 let now: u64 = 7 * 24 * 60 * 60 * 8; // 8 weeks (8 half-lives)
403 let stale = FrecencyRecord {
404 workspace: String::new(),
405 path: "x".into(),
406 count: 50,
407 last_used: 0,
408 };
409 let fresh = FrecencyRecord {
410 workspace: String::new(),
411 path: "y".into(),
412 count: 2,
413 last_used: now,
414 };
415 assert!(
416 super::decayed_score(&fresh, now) > super::decayed_score(&stale, now),
417 "fresh={}, stale={}",
418 super::decayed_score(&fresh, now),
419 super::decayed_score(&stale, now)
420 );
421 }
422 }
423
423 lines RUST