symforge 7.5.0

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
Documentation
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
//! Per-workspace frecency scoring for file ranking.
//!
//! Two complementary layers live here:
//!
//! 1. [`FrecencyStore`] — SQLite-backed, WAL mode, bumped on commitment tools
//!    (reads/edits of known files) and never on discovery tools (search).
//!    Decays on a 7-day half-life. This is the storage + scoring layer.
//! 2. [`bump`] — the call-site façade that commitment tools
//!    (`get_file_context`, `get_file_content`, `get_symbol`,
//!    `get_symbol_context`, the seven edit tools) invoke at the end of their
//!    happy path. Gated by `SYMFORGE_FRECENCY="1"`; opens the per-workspace
//!    SQLite store on demand and writes through to the underlying
//!    [`FrecencyStore`]. Infallible — every error is silently dropped so the
//!    feature cannot break the tools it hooks into.
//!
//! Discovery tools (`search_files`, `search_text`, `search_symbols`)
//! deliberately never call [`bump`] — see the spec §"Search tools deliberately
//! do NOT bump" for the positive-feedback-loop rationale.
//!
//! Spec: `wiki/concepts/SymForge Frecency-Weighted File Ranking.md`.

use rusqlite::{Connection, OptionalExtension, params};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;

/// Half-life for frecency decay, in seconds. 7 days.
pub const HALF_LIFE_SECS: i64 = 7 * 24 * 60 * 60;

/// Commit-distance thresholds for the graduated HEAD-change reset policy.
pub const RESET_NOOP_THRESHOLD: u32 = 50;
pub const RESET_HALVE_THRESHOLD: u32 = 500;

const META_LAST_HEAD: &str = "last_head_sha";

/// Env var that gates every call-site [`bump`]. `"1"` enables recording;
/// anything else (including unset) treats [`bump`] as a no-op.
pub const FRECENCY_FLAG_ENV: &str = "SYMFORGE_FRECENCY";

/// Outcome of applying the HEAD-change reset policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResetOutcome {
    /// No action taken (first session, same HEAD, or distance below threshold).
    NoOp,
    /// All `hit_count` values were halved.
    Halved,
    /// All `hit_count` values were zeroed.
    Zeroed,
}

/// A single frecency row as surfaced by `last_10_bumps` in health output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BumpEntry {
    pub path: PathBuf,
    pub last_access_ts: i64,
    pub hit_count: i64,
}

/// SQLite-backed per-workspace frecency store.
///
/// Persists to `.symforge/frecency.db` (see `paths::SYMFORGE_FRECENCY_DB_PATH`)
/// or an in-memory DB for tests. All access routes through an internal `Mutex`
/// so the store is `Sync` and safe to share across concurrent bump callers.
pub struct FrecencyStore {
    conn: Mutex<Connection>,
}

impl FrecencyStore {
    /// Open a file-backed store, creating the DB and parent directory if missing.
    ///
    /// Sets `busy_timeout = 5s` as a circuit-breaker for cross-process contention
    /// (e.g. a parallel `symforge` subagent on the same workspace). Same-process
    /// contention is handled at a higher layer by the cached store registry, so
    /// in-process callers should never exercise this fallback.
    pub fn open(db_path: &Path) -> rusqlite::Result<Self> {
        if let Some(parent) = db_path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent)
                .map_err(|_| rusqlite::Error::InvalidPath(parent.to_path_buf()))?;
        }
        let conn = Connection::open(db_path)?;
        // Best-effort WAL; silently falls back on in-memory/read-only FS.
        let _ = conn.pragma_update(None, "journal_mode", "WAL");
        let _ = conn.busy_timeout(std::time::Duration::from_secs(5));
        let store = Self {
            conn: Mutex::new(conn),
        };
        store.migrate()?;
        Ok(store)
    }

    /// Open an in-memory store. For tests and ephemeral use.
    pub fn open_in_memory() -> rusqlite::Result<Self> {
        let conn = Connection::open_in_memory()?;
        let store = Self {
            conn: Mutex::new(conn),
        };
        store.migrate()?;
        Ok(store)
    }

    fn migrate(&self) -> rusqlite::Result<()> {
        let conn = self.conn.lock().expect("frecency mutex poisoned");
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS frecency (
                path TEXT PRIMARY KEY,
                last_access_ts INTEGER NOT NULL,
                hit_count INTEGER NOT NULL
             );
             CREATE TABLE IF NOT EXISTS meta (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
             );",
        )?;
        Ok(())
    }

    /// Bump the given paths at `now_ts`. Each path increments `hit_count` by 1
    /// and sets `last_access_ts = now_ts`. The caller is responsible for
    /// deduplicating within a single invocation (per the Implementation Notes
    /// §"Bump dedup per tool invocation").
    pub fn bump(&self, paths: &[PathBuf], now_ts: i64) -> rusqlite::Result<()> {
        if paths.is_empty() {
            return Ok(());
        }
        let mut conn = self.conn.lock().expect("frecency mutex poisoned");
        let tx = conn.transaction()?;
        {
            let mut stmt = tx.prepare_cached(
                "INSERT INTO frecency(path, last_access_ts, hit_count)
                 VALUES (?1, ?2, 1)
                 ON CONFLICT(path) DO UPDATE SET
                    last_access_ts = excluded.last_access_ts,
                    hit_count = frecency.hit_count + 1",
            )?;
            for p in paths {
                stmt.execute(params![normalize_path(p), now_ts])?;
            }
        }
        tx.commit()
    }

    /// Decayed frecency score for a single path. Missing paths return `0.0`.
    pub fn score(&self, path: &Path, now_ts: i64) -> rusqlite::Result<f64> {
        let conn = self.conn.lock().expect("frecency mutex poisoned");
        let row: Option<(i64, i64)> = conn
            .query_row(
                "SELECT last_access_ts, hit_count FROM frecency WHERE path = ?1",
                params![normalize_path(path)],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .optional()?;
        Ok(row
            .map(|(ts, hits)| decay_score(hits, now_ts, ts))
            .unwrap_or(0.0))
    }

    /// Batch-score many paths at once. Missing paths are omitted from the map.
    pub fn bulk_scores(
        &self,
        paths: &[&Path],
        now_ts: i64,
    ) -> rusqlite::Result<HashMap<PathBuf, f64>> {
        let mut out = HashMap::with_capacity(paths.len());
        if paths.is_empty() {
            return Ok(out);
        }
        let conn = self.conn.lock().expect("frecency mutex poisoned");
        let mut stmt = conn.prepare_cached(
            "SELECT last_access_ts, hit_count FROM frecency WHERE path = ?1",
        )?;
        for p in paths {
            let key = normalize_path(p);
            let row: Option<(i64, i64)> = stmt
                .query_row(params![key], |r| Ok((r.get(0)?, r.get(1)?)))
                .optional()?;
            if let Some((ts, hits)) = row {
                out.insert(PathBuf::from(&key), decay_score(hits, now_ts, ts));
            }
        }
        Ok(out)
    }

    /// Most-recently-bumped rows, newest first, capped at 10. For health output.
    pub fn last_10_bumps(&self) -> rusqlite::Result<Vec<BumpEntry>> {
        let conn = self.conn.lock().expect("frecency mutex poisoned");
        let mut stmt = conn.prepare(
            "SELECT path, last_access_ts, hit_count FROM frecency
             ORDER BY last_access_ts DESC LIMIT 10",
        )?;
        stmt.query_map([], |r| {
            Ok(BumpEntry {
                path: PathBuf::from(r.get::<_, String>(0)?),
                last_access_ts: r.get(1)?,
                hit_count: r.get(2)?,
            })
        })?
        .collect()
    }

    /// Top-N paths ordered by decayed score at `now_ts`. For health output.
    pub fn top_frecent(&self, n: usize, now_ts: i64) -> rusqlite::Result<Vec<(PathBuf, f64)>> {
        let conn = self.conn.lock().expect("frecency mutex poisoned");
        let mut stmt = conn.prepare("SELECT path, last_access_ts, hit_count FROM frecency")?;
        let rows = stmt
            .query_map([], |r| {
                Ok((
                    PathBuf::from(r.get::<_, String>(0)?),
                    r.get::<_, i64>(1)?,
                    r.get::<_, i64>(2)?,
                ))
            })?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        let mut scored: Vec<_> = rows
            .into_iter()
            .map(|(p, ts, hits)| (p, decay_score(hits, now_ts, ts)))
            .collect();
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        scored.truncate(n);
        Ok(scored)
    }

    /// Apply the graduated HEAD-change reset policy and persist `current_head`.
    ///
    /// Policy (Implementation Notes §"Reset-on-HEAD-change: graduated, not binary"):
    /// - `last_head` is `None` (first session) → no-op.
    /// - `current_head == last_head` → no-op.
    /// - `commit_distance == None` (unrelated history / branch change) → zero.
    /// - `commit_distance < 50` → no-op.
    /// - `50 <= commit_distance <= 500` → halve all `hit_count`.
    /// - `commit_distance > 500` → zero all `hit_count`.
    ///
    /// The stored `last_head` is updated to `current_head` in every outcome so
    /// subsequent sessions compare against the most recent reset point.
    ///
    /// Note: the `commit_distance` parameter is `Option<u32>` (not the `u32`
    /// the todo text specified). The spec requires "branch change → zero",
    /// which the `git::commit_distance` helper already signals by returning
    /// `Ok(None)` for unrelated histories. Flowing that through preserves the
    /// distinction without an out-of-band sentinel value.
    pub fn reset_or_halve_on_head_change(
        &self,
        last_head: Option<&str>,
        current_head: &str,
        commit_distance: Option<u32>,
    ) -> rusqlite::Result<ResetOutcome> {
        let mut conn = self.conn.lock().expect("frecency mutex poisoned");
        let tx = conn.transaction()?;
        let outcome = match (last_head, commit_distance) {
            (None, _) => ResetOutcome::NoOp,
            (Some(last), _) if last == current_head => ResetOutcome::NoOp,
            (Some(_), None) => {
                tx.execute("UPDATE frecency SET hit_count = 0", [])?;
                ResetOutcome::Zeroed
            }
            (Some(_), Some(d)) if d < RESET_NOOP_THRESHOLD => ResetOutcome::NoOp,
            (Some(_), Some(d)) if d <= RESET_HALVE_THRESHOLD => {
                tx.execute("UPDATE frecency SET hit_count = hit_count / 2", [])?;
                ResetOutcome::Halved
            }
            (Some(_), Some(_)) => {
                tx.execute("UPDATE frecency SET hit_count = 0", [])?;
                ResetOutcome::Zeroed
            }
        };
        tx.execute(
            "INSERT INTO meta(key, value) VALUES (?1, ?2)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            params![META_LAST_HEAD, current_head],
        )?;
        tx.commit()?;
        Ok(outcome)
    }

    /// Read the last HEAD SHA this store recorded.
    pub fn last_head(&self) -> rusqlite::Result<Option<String>> {
        let conn = self.conn.lock().expect("frecency mutex poisoned");
        conn.query_row(
            "SELECT value FROM meta WHERE key = ?1",
            params![META_LAST_HEAD],
            |r| r.get::<_, String>(0),
        )
        .optional()
    }
}

/// Decay formula: `hit_count * exp(-ln(2) * (now - last) / HALF_LIFE_SECS)`.
/// Clamps a future `last_ts` (clock skew) to "no decay" rather than amplifying.
#[inline]
fn decay_score(hit_count: i64, now_ts: i64, last_ts: i64) -> f64 {
    let dt = (now_ts - last_ts).max(0) as f64;
    (hit_count as f64) * (-std::f64::consts::LN_2 * dt / HALF_LIFE_SECS as f64).exp()
}

/// Normalize paths to forward-slash form so Windows and Unix key the same row.
/// Mirrors the pattern in `src/git.rs::collect_diff_paths`.
fn normalize_path(p: &Path) -> String {
    p.to_string_lossy().replace('\\', "/")
}

// ---------------------------------------------------------------------------
// Call-site bump façade
// ---------------------------------------------------------------------------
//
// `bump(repo_root, paths)` is the stable surface commitment-tool handlers call
// at the end of their happy path. It opens the per-workspace SQLite store on
// demand and writes the bumps through. SQLite open + a single upsert is sub-ms
// in WAL mode; the call sites are not hot paths.

/// Record that the given paths were accessed by a commitment tool.
///
/// No-op when `SYMFORGE_FRECENCY` is unset or not `"1"`. Infallible — callers
/// never need to handle errors; failure to record a bump is silently dropped
/// so the feature cannot break the tool it hooks into.
///
/// `paths` is expected to already be deduplicated (batch tools collect into a
/// `HashSet<PathBuf>` before calling). Looks up a process-cached
/// [`FrecencyStore`] keyed by the per-workspace database path; same-process
/// callers serialize through the store's internal connection mutex with no
/// SQLite-level lock contention. Cross-process contention falls back to the
/// 5-second `busy_timeout` set in [`FrecencyStore::open`].
pub fn bump(repo_root: &Path, paths: &[PathBuf]) {
    if std::env::var(FRECENCY_FLAG_ENV).as_deref() != Ok("1") {
        return;
    }
    if paths.is_empty() {
        return;
    }
    let Some(store) = cached_store_for(repo_root) else {
        return;
    };
    let now_ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    let _ = store.bump(paths, now_ts);
}

/// Look up (or lazily create) the cached [`FrecencyStore`] for `repo_root`.
///
/// All same-process callers for a given workspace share the same `Arc` and
/// thus the same connection mutex. Returns `None` if the store cannot be
/// opened — bump is infallible at the call site, so we just drop the bump.
fn cached_store_for(repo_root: &Path) -> Option<std::sync::Arc<FrecencyStore>> {
    use std::collections::HashMap;
    use std::sync::{Arc, OnceLock};
    static CACHE: OnceLock<Mutex<HashMap<PathBuf, Arc<FrecencyStore>>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    let key = repo_root.join(crate::paths::SYMFORGE_FRECENCY_DB_PATH);
    let mut guard = cache.lock().ok()?;
    if let Some(existing) = guard.get(&key) {
        return Some(Arc::clone(existing));
    }
    let store = Arc::new(FrecencyStore::open(&key).ok()?);
    guard.insert(key, Arc::clone(&store));
    Some(store)
}

/// [`EditHook`] implementation that records a frecency bump after every
/// successful edit commit. Delegates to [`bump`], so the
/// `SYMFORGE_FRECENCY` flag check happens there — registering the hook is
/// itself unconditional.
pub struct FrecencyBumpHook;

impl crate::protocol::edit_hooks::EditHook for FrecencyBumpHook {
    fn after_edit_committed(
        &self,
        ctx: &crate::protocol::edit_hooks::EditContext,
        _resolved_path: &Path,
    ) {
        bump(ctx.repo_root, &[PathBuf::from(ctx.relative_path)]);
    }
}

/// Register [`FrecencyBumpHook`] on the process-wide edit-hook registry exactly
/// once. Safe to call from every `LiveIndex::load` — the inner [`OnceLock`]
/// dedupes. The hook body itself gates on `SYMFORGE_FRECENCY=1`, so registering
/// unconditionally costs nothing when the flag is off.
pub fn ensure_bump_hook_registered() {
    use std::sync::OnceLock;
    static REGISTERED: OnceLock<()> = OnceLock::new();
    REGISTERED.get_or_init(|| {
        crate::protocol::edit_hooks::register(Box::new(FrecencyBumpHook));
    });
}

/// Drain and return every path recorded by [`bump`] since the last drain/clear.
///
/// Intended for wiring tests that need to observe whether a tool handler
/// actually called [`bump`]. Kept `pub` (behind `#[doc(hidden)]`) because the
/// integration-test crate lives outside the library crate and cannot use
/// `#[cfg(test)]`-gated items.
#[doc(hidden)]
/// Clear the test-observability sink without returning its contents.
#[doc(hidden)]
#[cfg(test)]
mod tests {
    use super::*;

    // -----------------------------------------------------------------
    // FrecencyStore tests (storage layer — from swarm-1)
    // -----------------------------------------------------------------

    fn make_store() -> FrecencyStore {
        FrecencyStore::open_in_memory().expect("open in-memory frecency store")
    }

    fn norm(p: &Path) -> PathBuf {
        PathBuf::from(normalize_path(p))
    }

    #[test]
    fn bump_inserts_new_path_with_hit_count_one() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 1_000).unwrap();
        assert_eq!(store.score(&p, 1_000).unwrap(), 1.0);
    }

    #[test]
    fn bump_increments_existing_path() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 1_000).unwrap();
        store.bump(&[p.clone()], 2_000).unwrap();
        store.bump(&[p.clone()], 3_000).unwrap();
        assert_eq!(store.score(&p, 3_000).unwrap(), 3.0);
    }

    #[test]
    fn bump_updates_last_access_ts() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 1_000).unwrap();
        store.bump(&[p.clone()], 5_000).unwrap();
        let entries = store.last_10_bumps().unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].last_access_ts, 5_000);
        assert_eq!(entries[0].hit_count, 2);
    }

    #[test]
    fn bump_multiple_paths_in_single_call() {
        let store = make_store();
        let paths = vec![
            PathBuf::from("src/a.rs"),
            PathBuf::from("src/b.rs"),
            PathBuf::from("src/c.rs"),
        ];
        store.bump(&paths, 1_000).unwrap();
        for p in &paths {
            assert_eq!(store.score(p, 1_000).unwrap(), 1.0);
        }
    }

    #[test]
    fn empty_bump_is_noop() {
        let store = make_store();
        store.bump(&[], 0).unwrap();
        assert!(store.top_frecent(10, 0).unwrap().is_empty());
    }

    #[test]
    fn score_returns_zero_for_missing_path() {
        let store = make_store();
        assert_eq!(store.score(Path::new("nope.rs"), 1_000).unwrap(), 0.0);
    }

    #[test]
    fn score_decays_by_half_at_one_half_life() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 0).unwrap();
        let score = store.score(&p, HALF_LIFE_SECS).unwrap();
        assert!(
            (score - 0.5).abs() < 1e-9,
            "expected ~0.5 at 1 half-life, got {score}"
        );
    }

    #[test]
    fn score_decays_to_quarter_at_two_half_lives() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 0).unwrap();
        let score = store.score(&p, HALF_LIFE_SECS * 2).unwrap();
        assert!(
            (score - 0.25).abs() < 1e-9,
            "expected ~0.25 at 2 half-lives, got {score}"
        );
    }

    #[test]
    fn score_is_stable_when_now_equals_last_access() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 12_345).unwrap();
        assert_eq!(store.score(&p, 12_345).unwrap(), 1.0);
    }

    #[test]
    fn score_does_not_amplify_on_clock_skew() {
        // If now_ts < last_access_ts (clock skew), score should not exceed hit_count.
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 10_000).unwrap();
        assert_eq!(store.score(&p, 9_000).unwrap(), 1.0);
    }

    #[test]
    fn fusion_property_recent_outranks_ancient_with_many_hits() {
        // "File touched 5 min ago outranks file touched 6 months ago with 10× hits."
        let store = make_store();
        let ancient = PathBuf::from("src/ancient.rs");
        let recent = PathBuf::from("src/recent.rs");
        let six_months: i64 = 60 * 60 * 24 * 30 * 6;
        for _ in 0..10 {
            store.bump(&[ancient.clone()], 0).unwrap();
        }
        store.bump(&[recent.clone()], six_months - 300).unwrap();
        let now = six_months;
        assert!(store.score(&recent, now).unwrap() > store.score(&ancient, now).unwrap());
    }

    #[test]
    fn bulk_scores_matches_per_path_score() {
        let store = make_store();
        let a = PathBuf::from("src/a.rs");
        let b = PathBuf::from("src/b.rs");
        let missing = PathBuf::from("src/missing.rs");
        store.bump(&[a.clone()], 0).unwrap();
        store.bump(&[b.clone()], 0).unwrap();
        store.bump(&[b.clone()], 0).unwrap();
        let now = HALF_LIFE_SECS;
        let paths: Vec<&Path> = vec![a.as_path(), b.as_path(), missing.as_path()];
        let bulk = store.bulk_scores(&paths, now).unwrap();
        assert_eq!(bulk.len(), 2, "missing path must be omitted from bulk map");
        assert!((bulk[&norm(&a)] - store.score(&a, now).unwrap()).abs() < 1e-9);
        assert!((bulk[&norm(&b)] - store.score(&b, now).unwrap()).abs() < 1e-9);
    }

    #[test]
    fn bulk_scores_empty_input_is_empty_map() {
        let store = make_store();
        let paths: Vec<&Path> = vec![];
        assert!(store.bulk_scores(&paths, 0).unwrap().is_empty());
    }

    #[test]
    fn last_10_bumps_returns_most_recent_first() {
        let store = make_store();
        for i in 0..15 {
            store
                .bump(&[PathBuf::from(format!("src/f_{i}.rs"))], i as i64 * 1_000)
                .unwrap();
        }
        let entries = store.last_10_bumps().unwrap();
        assert_eq!(entries.len(), 10);
        assert_eq!(entries[0].last_access_ts, 14_000);
        assert_eq!(entries[9].last_access_ts, 5_000);
    }

    #[test]
    fn top_frecent_orders_by_decayed_score() {
        let store = make_store();
        let hot = PathBuf::from("hot.rs");
        let warm = PathBuf::from("warm.rs");
        let cold = PathBuf::from("cold.rs");
        // Same last_access_ts; hit counts differ.
        store.bump(&[hot.clone()], 100).unwrap();
        store.bump(&[hot.clone()], 100).unwrap();
        store.bump(&[warm.clone()], 100).unwrap();
        // Cold: 1 hit, but decayed by 5 half-lives.
        store.bump(&[cold.clone()], 100 - HALF_LIFE_SECS * 5).unwrap();
        let top = store.top_frecent(3, 100).unwrap();
        assert_eq!(top.len(), 3);
        assert_eq!(top[0].0, hot);
        assert_eq!(top[1].0, warm);
        assert_eq!(top[2].0, cold);
    }

    #[test]
    fn top_frecent_respects_n_limit() {
        let store = make_store();
        for i in 0..20 {
            store
                .bump(&[PathBuf::from(format!("f{i}.rs"))], 0)
                .unwrap();
        }
        assert_eq!(store.top_frecent(5, 0).unwrap().len(), 5);
    }

    #[test]
    fn reset_first_session_noops_and_stores_head() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 0).unwrap();
        let outcome = store
            .reset_or_halve_on_head_change(None, "abc123", Some(1_000))
            .unwrap();
        assert_eq!(outcome, ResetOutcome::NoOp);
        assert_eq!(store.score(&p, 0).unwrap(), 1.0);
        assert_eq!(store.last_head().unwrap().as_deref(), Some("abc123"));
    }

    #[test]
    fn reset_same_head_noops() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        store.bump(&[p.clone()], 0).unwrap();
        let outcome = store
            .reset_or_halve_on_head_change(Some("sha"), "sha", Some(0))
            .unwrap();
        assert_eq!(outcome, ResetOutcome::NoOp);
        assert_eq!(store.score(&p, 0).unwrap(), 1.0);
    }

    #[test]
    fn reset_below_50_commits_noops() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        for _ in 0..4 {
            store.bump(&[p.clone()], 0).unwrap();
        }
        let outcome = store
            .reset_or_halve_on_head_change(Some("old"), "new", Some(49))
            .unwrap();
        assert_eq!(outcome, ResetOutcome::NoOp);
        assert_eq!(store.score(&p, 0).unwrap(), 4.0);
    }

    #[test]
    fn reset_at_50_halves_hits() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        for _ in 0..10 {
            store.bump(&[p.clone()], 0).unwrap();
        }
        let outcome = store
            .reset_or_halve_on_head_change(Some("old"), "new", Some(50))
            .unwrap();
        assert_eq!(outcome, ResetOutcome::Halved);
        assert_eq!(store.score(&p, 0).unwrap(), 5.0);
    }

    #[test]
    fn reset_at_500_halves_hits() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        for _ in 0..10 {
            store.bump(&[p.clone()], 0).unwrap();
        }
        let outcome = store
            .reset_or_halve_on_head_change(Some("old"), "new", Some(500))
            .unwrap();
        assert_eq!(outcome, ResetOutcome::Halved);
        assert_eq!(store.score(&p, 0).unwrap(), 5.0);
    }

    #[test]
    fn reset_above_500_zeros_hits() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        for _ in 0..10 {
            store.bump(&[p.clone()], 0).unwrap();
        }
        let outcome = store
            .reset_or_halve_on_head_change(Some("old"), "new", Some(501))
            .unwrap();
        assert_eq!(outcome, ResetOutcome::Zeroed);
        assert_eq!(store.score(&p, 0).unwrap(), 0.0);
    }

    #[test]
    fn reset_unrelated_history_zeros_hits() {
        let store = make_store();
        let p = PathBuf::from("src/foo.rs");
        for _ in 0..10 {
            store.bump(&[p.clone()], 0).unwrap();
        }
        let outcome = store
            .reset_or_halve_on_head_change(Some("old"), "new", None)
            .unwrap();
        assert_eq!(outcome, ResetOutcome::Zeroed);
        assert_eq!(store.score(&p, 0).unwrap(), 0.0);
    }

    #[test]
    fn reset_updates_stored_head_across_outcomes() {
        let store = make_store();
        store.bump(&[PathBuf::from("src/foo.rs")], 0).unwrap();
        store
            .reset_or_halve_on_head_change(Some("a"), "b", Some(10))
            .unwrap();
        assert_eq!(store.last_head().unwrap().as_deref(), Some("b"));
        store
            .reset_or_halve_on_head_change(Some("b"), "c", Some(200))
            .unwrap();
        assert_eq!(store.last_head().unwrap().as_deref(), Some("c"));
        store
            .reset_or_halve_on_head_change(Some("c"), "d", Some(10_000))
            .unwrap();
        assert_eq!(store.last_head().unwrap().as_deref(), Some("d"));
    }

    #[test]
    fn path_normalization_treats_backslash_and_forward_slash_as_same_row() {
        let store = make_store();
        let windows = PathBuf::from("src\\foo.rs");
        let unix = PathBuf::from("src/foo.rs");
        store.bump(&[windows], 0).unwrap();
        store.bump(&[unix.clone()], 1_000).unwrap();
        assert_eq!(store.score(&unix, 1_000).unwrap(), 2.0);
        assert_eq!(store.last_10_bumps().unwrap().len(), 1);
    }

    #[test]
    fn open_file_backed_creates_db_and_parent_dir_and_persists() {
        let tmp = tempfile::TempDir::new().unwrap();
        let nested = tmp.path().join("nested").join("frecency.db");
        {
            let store = FrecencyStore::open(&nested).unwrap();
            store.bump(&[PathBuf::from("src/foo.rs")], 0).unwrap();
        }
        assert!(nested.exists(), "db file should be created");
        let store2 = FrecencyStore::open(&nested).unwrap();
        assert_eq!(store2.score(Path::new("src/foo.rs"), 0).unwrap(), 1.0);
    }

    // -----------------------------------------------------------------
    // Call-site bump() façade tests
    //
    // The façade now opens the per-workspace SQLite store on demand and
    // writes directly. Verifying behavior means querying the store after
    // the call rather than draining a sink. Tests serialize on ENV_LOCK
    // because they mutate `SYMFORGE_FRECENCY`.
    // -----------------------------------------------------------------

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    fn set_flag_on() {
        // SAFETY: tests hold ENV_LOCK and run with --test-threads=1; no
        // concurrent env readers can observe the transition.
        unsafe { std::env::set_var(FRECENCY_FLAG_ENV, "1") };
    }

    fn clear_flag() {
        // SAFETY: see set_flag_on.
        unsafe { std::env::remove_var(FRECENCY_FLAG_ENV) };
    }

    fn db_path_for(root: &Path) -> PathBuf {
        root.join(crate::paths::SYMFORGE_FRECENCY_DB_PATH)
    }

    #[test]
    fn module_bump_is_noop_when_flag_unset() {
        let _g = ENV_LOCK.lock().unwrap();
        clear_flag();
        let tmp = tempfile::tempdir().expect("tempdir");
        super::bump(tmp.path(), &[PathBuf::from("src/lib.rs")]);
        // Flag off: the database file must not even be created.
        assert!(
            !db_path_for(tmp.path()).exists(),
            "bump with flag unset must not touch disk"
        );
    }

    #[test]
    fn module_bump_is_noop_when_flag_not_one() {
        let _g = ENV_LOCK.lock().unwrap();
        // SAFETY: see set_flag_on.
        unsafe { std::env::set_var(FRECENCY_FLAG_ENV, "0") };
        let tmp = tempfile::tempdir().expect("tempdir");
        super::bump(tmp.path(), &[PathBuf::from("src/lib.rs")]);
        clear_flag();
        assert!(
            !db_path_for(tmp.path()).exists(),
            "bump with flag != 1 must not touch disk"
        );
    }

    #[test]
    fn module_bump_records_paths_when_flag_on() {
        let _g = ENV_LOCK.lock().unwrap();
        set_flag_on();
        let tmp = tempfile::tempdir().expect("tempdir");
        super::bump(
            tmp.path(),
            &[PathBuf::from("src/a.rs"), PathBuf::from("src/b.rs")],
        );
        clear_flag();
        let store = FrecencyStore::open(&db_path_for(tmp.path())).unwrap();
        let entries = store.last_10_bumps().unwrap();
        let mut paths: Vec<PathBuf> = entries.iter().map(|e| e.path.clone()).collect();
        paths.sort();
        assert_eq!(
            paths,
            vec![PathBuf::from("src/a.rs"), PathBuf::from("src/b.rs")],
            "bump with flag on must persist every supplied path"
        );
    }

    #[test]
    fn module_bump_empty_slice_is_noop_when_flag_on() {
        let _g = ENV_LOCK.lock().unwrap();
        set_flag_on();
        let tmp = tempfile::tempdir().expect("tempdir");
        super::bump(tmp.path(), &[]);
        clear_flag();
        // Empty slice: short-circuit before opening the store.
        assert!(
            !db_path_for(tmp.path()).exists(),
            "empty bump must not touch disk even with flag on"
        );
    }

    #[test]
    fn module_bump_increments_existing_path() {
        let _g = ENV_LOCK.lock().unwrap();
        set_flag_on();
        let tmp = tempfile::tempdir().expect("tempdir");
        super::bump(tmp.path(), &[PathBuf::from("src/lib.rs")]);
        super::bump(tmp.path(), &[PathBuf::from("src/lib.rs")]);
        clear_flag();
        let store = FrecencyStore::open(&db_path_for(tmp.path())).unwrap();
        let entries = store.last_10_bumps().unwrap();
        assert_eq!(entries.len(), 1, "single path collapses into one row");
        assert_eq!(entries[0].hit_count, 2);
    }
}