Skip to main content

lean_ctx/core/
bounce_tracker.rs

1use std::collections::HashMap;
2use std::sync::{Mutex, OnceLock};
3
4const BOUNCE_WINDOW: u64 = 5;
5const BOUNCE_RATE_THRESHOLD: f64 = 0.30;
6/// Seq-tick window during which a full read is treated as *edit-forced* rather
7/// than a compression bounce. Must match the window `should_force_full` uses to
8/// escalate post-edit reads to `full`, so the read we forced is never blamed on
9/// the compression arm (GL #622).
10const EDIT_FORCE_WINDOW: u64 = 10;
11/// Outer-map retention: a path whose newest activity is older than this many seq ticks
12/// can no longer satisfy BOUNCE_WINDOW (5) or the edit-force window (10), so it is inert
13/// and safe to evict. Kept well above both windows to never change detection outcomes.
14const TRACKED_PATH_TTL_SEQ: u64 = 64;
15
16#[derive(Debug, Clone)]
17struct ReadEvent {
18    _mode: String,
19    tokens_sent: usize,
20    _original_tokens: usize,
21    seq: u64,
22    view: ReadView,
23    /// File mtime when a compressed view was served. A later full read of a
24    /// file whose mtime moved re-reads *changed* content — an edit (a host's
25    /// native Edit/Write included, which never reaches `record_edit`), not a
26    /// compression failure.
27    mtime: Option<std::time::SystemTime>,
28    /// Scope and task the read ran under; a bounce is that task's signal.
29    origin: Option<crate::core::context_store::task_signals::Origin>,
30}
31
32fn file_mtime(path: &str) -> Option<std::time::SystemTime> {
33    std::fs::metadata(path).and_then(|m| m.modified()).ok()
34}
35
36/// What a read showed of the file, for correction (bounce) accounting.
37///
38/// A correction is a lossy [`Compressed`](ReadView::Compressed) view
39/// followed by the [`Full`](ReadView::Full) content. A
40/// [`Partial`](ReadView::Partial) read — a line window, `head`/`tail`, a
41/// `sed -n` range, a `diff` delta — is precise reading: it neither starts nor
42/// completes a correction, and it ends the one a preceding compressed view
43/// could have started (that view did its job: it pointed at the window).
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum ReadView {
46    Compressed,
47    Full,
48    Partial,
49}
50
51impl ReadView {
52    /// Classify a resolved `ctx_read` mode string.
53    ///
54    /// `anchored` (whole file) is verbatim plus per-line anchors, so it is
55    /// full content like `full`/`raw`/`full-compact`; `anchored:N-M` is a
56    /// window. Unknown strings are `Partial`: an unrecognised mode must never
57    /// fabricate a correction.
58    #[must_use]
59    pub fn of_mode(mode: &str) -> Self {
60        use crate::tools::ctx_read::ReadMode;
61        match mode.parse::<ReadMode>() {
62            Ok(
63                ReadMode::Full | ReadMode::FullCompact | ReadMode::Raw | ReadMode::Anchored(None),
64            ) => ReadView::Full,
65            Ok(
66                ReadMode::Anchored(Some(_))
67                | ReadMode::Lines(_)
68                | ReadMode::LinesMulti(_)
69                | ReadMode::LinesTail(_)
70                | ReadMode::Diff,
71            )
72            | Err(_) => ReadView::Partial,
73            Ok(
74                ReadMode::Signatures
75                | ReadMode::Map
76                | ReadMode::Aggressive
77                | ReadMode::Entropy
78                | ReadMode::Cognitive
79                | ReadMode::Mdl
80                | ReadMode::Task
81                | ReadMode::Reference
82                | ReadMode::Auto
83                | ReadMode::Density(_),
84            ) => ReadView::Compressed,
85        }
86    }
87}
88
89#[derive(Debug, Default)]
90struct BounceStats {
91    total_reads: u64,
92    bounces: u64,
93    wasted_tokens: usize,
94}
95
96/// A detected compressed→full re-read that is not yet booked as a bounce.
97///
98/// Reading a file compressed for orientation, then in full, then editing it is
99/// the normal edit flow (map to orient, full to edit), not a compression
100/// failure. A bounce therefore stays provisional for `EDIT_FORCE_WINDOW` seq
101/// ticks: an edit of the path inside that window cancels it, otherwise it is
102/// committed (ledger entry, path memory, quality signal, scent).
103#[derive(Debug, Clone)]
104struct PendingBounce {
105    path: String,
106    /// Seq tick of the full read that triggered the detection.
107    seq: u64,
108    wasted: usize,
109    origin: Option<crate::core::context_store::task_signals::Origin>,
110    /// Wall-clock detection time, compared against host edits other
111    /// processes report through the edit beacon.
112    detected_unix_ms: u64,
113    /// The request project at detection. The bounce is booked later (after
114    /// the edit window, or by the shutdown flush) outside that request.
115    project_root: Option<String>,
116    /// The read mode of the compressed view the full read corrected.
117    mode: String,
118}
119
120#[derive(Debug, Default)]
121pub struct BounceTracker {
122    recent_reads: HashMap<String, Vec<ReadEvent>>,
123    per_extension: HashMap<String, BounceStats>,
124    recently_edited: HashMap<String, u64>,
125    pending: Vec<PendingBounce>,
126    seq_counter: u64,
127    total_bounces: u64,
128    total_wasted_tokens: usize,
129    /// When true (only for the process-global tracker), detected bounces are appended to
130    /// the persistent savings ledger so a fresh `gain` process sees historical bounce.
131    /// Local trackers in unit tests leave this `false` to avoid touching the real ledger.
132    persist: bool,
133}
134
135/// Upper bound on provisional bounces kept in memory; the oldest is committed
136/// early when a burst exceeds it, so the queue can never grow without limit.
137const MAX_PENDING_BOUNCES: usize = 256;
138
139fn extension_of(path: &str) -> String {
140    path.rsplit('.')
141        .next()
142        .map(|e| format!(".{}", e.to_ascii_lowercase()))
143        .unwrap_or_default()
144}
145
146impl BounceTracker {
147    pub fn new() -> Self {
148        Self::default()
149    }
150
151    pub fn next_seq(&mut self) -> u64 {
152        self.seq_counter += 1;
153        self.commit_due();
154        self.seq_counter
155    }
156
157    pub fn set_seq(&mut self, seq: u64) {
158        self.seq_counter = seq;
159        self.commit_due();
160    }
161
162    pub fn record_read(
163        &mut self,
164        path: &str,
165        mode: &str,
166        tokens_sent: usize,
167        original_tokens: usize,
168    ) {
169        let norm = crate::core::pathutil::normalize_tool_path(path);
170        self.commit_due();
171        let seq = self.seq_counter;
172        let view = ReadView::of_mode(mode);
173        let compressed = view == ReadView::Compressed;
174
175        if view == ReadView::Full {
176            self.detect_bounce(&norm, path, seq);
177        }
178        if self.persist && compressed {
179            // K10: a compressed view is a truncated output of its read mode.
180            {
181                use crate::core::hive::metrics_v2::signals;
182                signals::truncated(&signals::read_mode_filter(mode));
183            }
184            // Keep the long-term majority rule honest: compressed reads that
185            // did not bounce dilute historical bounces (#496). Full and
186            // partial reads — the bounce re-read itself included — are not
187            // compression attempts and stay out of the denominator.
188            crate::core::path_mode_memory::record_compressed_read_if_tracked(&norm);
189        }
190
191        let current = if self.persist {
192            crate::core::context_store::task_signals::current_origin()
193        } else {
194            None
195        };
196        if let Some(current) = &current {
197            // Bounces are seen only by the process that served the read: a
198            // task served by several processes is not fully observed.
199            crate::core::context_store::task_signals::observe(current);
200        }
201        let origin = current.filter(|_| compressed);
202        self.push_event(
203            norm,
204            ReadEvent {
205                _mode: mode.to_string(),
206                tokens_sent,
207                _original_tokens: original_tokens,
208                seq,
209                view,
210                mtime: if compressed { file_mtime(path) } else { None },
211                origin,
212            },
213        );
214
215        let ext = extension_of(path);
216        if !ext.is_empty() {
217            let stats = self.per_extension.entry(ext).or_default();
218            stats.total_reads += 1;
219        }
220
221        self.prune_stale_paths();
222    }
223
224    fn push_event(&mut self, norm: String, event: ReadEvent) {
225        let events = self.recent_reads.entry(norm).or_default();
226        events.push(event);
227        if events.len() > 10 {
228            events.drain(..events.len() - 10);
229        }
230    }
231
232    /// Detect the correction a full read completes: only a full read whose
233    /// immediately preceding read of the path was a compressed view within
234    /// `BOUNCE_WINDOW`. A partial or full read in between ends the chain.
235    fn detect_bounce(&mut self, norm_path: &str, fs_path: &str, full_seq: u64) {
236        // A full re-read the system itself forced after an edit is not a
237        // compression failure (GL #622): `should_force_full` returns `full` for
238        // EDIT_FORCE_WINDOW ticks post-edit, so the agent had no choice. Counting
239        // it as a bounce would penalize the compression arm for the edit and
240        // inflate the per-extension bounce rate until `should_force_full` pins the
241        // whole extension to `full` — a self-reinforcing loss of compression.
242        if let Some(&edit_seq) = self.recently_edited.get(norm_path)
243            && full_seq.saturating_sub(edit_seq) <= EDIT_FORCE_WINDOW
244        {
245            return;
246        }
247
248        let Some(events) = self.recent_reads.get(norm_path) else {
249            return;
250        };
251
252        if let Some(ev) = events.iter().next_back()
253            && ev.view == ReadView::Compressed
254            && full_seq.saturating_sub(ev.seq) <= BOUNCE_WINDOW
255            // The file changed since the view was served: the full re-read
256            // fetches new content after an edit. A host's native Edit/Write
257            // in another process may reach neither `record_edit` nor the
258            // edit beacon in time; the moved mtime is direct evidence of it.
259            && (ev.mtime.is_none() || file_mtime(fs_path) == ev.mtime)
260        {
261            // Provisional until EDIT_FORCE_WINDOW passes without an edit of
262            // this path (see `PendingBounce`).
263            let pending = PendingBounce {
264                path: norm_path.to_string(),
265                seq: full_seq,
266                wasted: ev.tokens_sent,
267                origin: ev.origin.clone(),
268                detected_unix_ms: now_unix_ms(),
269                project_root: crate::core::scent_field::current_project(),
270                mode: ev._mode.clone(),
271            };
272            self.pending.push(pending);
273            if self.pending.len() > MAX_PENDING_BOUNCES {
274                let oldest = self.pending.remove(0);
275                self.commit(oldest);
276            }
277        }
278    }
279
280    /// Commit every provisional bounce whose edit window has passed. Called
281    /// whenever the seq clock moves or a read/edit is recorded.
282    fn commit_due(&mut self) {
283        if self.pending.is_empty() {
284            return;
285        }
286        let now = self.seq_counter;
287        let (due, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut self.pending)
288            .into_iter()
289            .partition(|p| now.saturating_sub(p.seq) > EDIT_FORCE_WINDOW);
290        self.pending = keep;
291        for pending in due {
292            self.commit(pending);
293        }
294    }
295
296    /// Commit every provisional bounce now, regardless of its window. Used at
297    /// process shutdown so a bounce detected shortly before exit is not lost.
298    pub fn flush_pending(&mut self) {
299        for pending in std::mem::take(&mut self.pending) {
300            self.commit(pending);
301        }
302    }
303
304    /// Provisional bounces still waiting for their edit window to pass.
305    pub fn pending_bounces(&self) -> usize {
306        self.pending.len()
307    }
308
309    /// Book one bounce: counters, per-extension stats and, for the
310    /// process-global tracker, the ledger entry, path memory, quality signal
311    /// and scent. A host edit another process reported for the path after the
312    /// detection (edit beacon) cancels it instead.
313    fn commit(&mut self, pending: PendingBounce) {
314        if self.persist && host_edited_since(&pending.path, pending.detected_unix_ms) {
315            return;
316        }
317        let PendingBounce {
318            path: norm_path,
319            wasted,
320            origin,
321            project_root,
322            mode,
323            ..
324        } = pending;
325        self.total_bounces += 1;
326        self.total_wasted_tokens += wasted;
327
328        let ext = extension_of(&norm_path);
329        if !ext.is_empty() {
330            let stats = self.per_extension.entry(ext).or_default();
331            stats.bounces += 1;
332            stats.wasted_tokens += wasted;
333        }
334
335        if self.persist {
336            if let Some(origin) = origin {
337                // Off this tracker's lock: recording waits on a file lock.
338                std::thread::spawn(move || {
339                    crate::core::context_store::task_signals::record(
340                        &origin,
341                        crate::core::context_store::task_signals::Signal::Bounce,
342                    );
343                });
344            }
345            crate::core::savings_ledger::record_bounce_event(wasted);
346            // K10: the compressed view was fetched back in full.
347            {
348                use crate::core::hive::metrics_v2::signals;
349                signals::refetched(&signals::read_mode_filter(&mode));
350            }
351            // Long-term per-path memory (#496): remember which exact
352            // files keep bouncing so auto-mode learns across restarts.
353            crate::core::path_mode_memory::record_bounce(&norm_path);
354            // A bounce penalizes the bandit arm that produced the read (#593).
355            crate::core::adaptive_thresholds::penalize_read_arm(&norm_path);
356            // Stigmergy (#540): a bounce marks this path as Stuck so
357            // other agents see friction here. Background: lock may block.
358            // The project was resolved at detection, inside the request.
359            if let Some(project_root) = project_root {
360                std::thread::spawn(move || {
361                    crate::core::scent_field::deposit_for(
362                        &project_root,
363                        crate::core::scent_field::scent_agent_id(),
364                        crate::core::scent_field::ScentKind::Stuck,
365                        &norm_path,
366                        0.5,
367                    );
368                });
369            }
370        }
371    }
372
373    /// A shell read of `path` (`cat`, `head`, `sed -n`, …). A full read can
374    /// complete a correction of a preceding compressed view; a partial one
375    /// never does. Either way it becomes the path's newest read, so a second
376    /// `cat` cannot book the same correction twice.
377    pub fn record_shell_read(&mut self, path: &str, view: ReadView) {
378        let norm = crate::core::pathutil::normalize_tool_path(path);
379        self.commit_due();
380        let seq = self.seq_counter;
381        if view == ReadView::Full {
382            self.detect_bounce(&norm, path, seq);
383        }
384        self.push_event(
385            norm,
386            ReadEvent {
387                _mode: "shell".to_string(),
388                tokens_sent: 0,
389                _original_tokens: 0,
390                seq,
391                // A shell read is never the compressed view of a correction.
392                view: if view == ReadView::Compressed {
393                    ReadView::Partial
394                } else {
395                    view
396                },
397                mtime: None,
398                origin: None,
399            },
400        );
401        self.prune_stale_paths();
402    }
403
404    /// Records an explicit archive/context expansion as a quality bounce.
405    ///
406    /// Unlike a full file re-read, `ctx_expand` may address a content handle
407    /// rather than a path, so it cannot always be inferred by `detect_bounce`.
408    /// Benchmark replay uses this method to keep the quality proxy on the same
409    /// tracker as ordinary compressed-then-full bounces.
410    pub fn record_expansion(&mut self, source: Option<&str>, wasted_tokens: usize) {
411        self.total_bounces = self.total_bounces.saturating_add(1);
412        self.total_wasted_tokens = self.total_wasted_tokens.saturating_add(wasted_tokens);
413
414        if let Some(path) = source {
415            let ext = extension_of(path);
416            if !ext.is_empty() {
417                let stats = self.per_extension.entry(ext).or_default();
418                stats.bounces = stats.bounces.saturating_add(1);
419                stats.wasted_tokens = stats.wasted_tokens.saturating_add(wasted_tokens);
420            }
421        }
422    }
423
424    /// The newest read of `path` this process still remembers: whether it
425    /// was compressed and the scope and task it ran under, so a later event
426    /// is charged to the read that caused it. `None`: no read is known here
427    /// (another process, or before a restart). A partial read (line window)
428    /// is precise, not lossy, so it reports `false` like a full read.
429    pub(crate) fn last_read(
430        &self,
431        path: &str,
432    ) -> Option<(
433        bool,
434        Option<crate::core::context_store::task_signals::Origin>,
435    )> {
436        let norm = crate::core::pathutil::normalize_tool_path(path);
437        let event = self.recent_reads.get(&norm)?.last()?;
438        Some((event.view == ReadView::Compressed, event.origin.clone()))
439    }
440
441    /// An edit of `path`. Besides exempting the full re-reads it forces, it
442    /// cancels any provisional bounce of the path still inside its edit
443    /// window: the compressed→full re-read was the read-before-edit, not a
444    /// compression failure.
445    pub fn record_edit(&mut self, path: &str) {
446        let norm = crate::core::pathutil::normalize_tool_path(path);
447        self.commit_due();
448        self.pending.retain(|p| p.path != norm);
449        self.recently_edited.insert(norm, self.seq_counter);
450        self.prune_stale_paths();
451    }
452
453    /// Evict outer-map entries whose newest seq is older than the detection windows —
454    /// they can no longer affect bounce detection or `should_force_full`. Bounds the
455    /// `recent_reads` / `recently_edited` maps on a long-lived process.
456    fn prune_stale_paths(&mut self) {
457        let seq = self.seq_counter;
458        self.recent_reads.retain(|_, events| {
459            events
460                .last()
461                .is_some_and(|e| seq.saturating_sub(e.seq) <= TRACKED_PATH_TTL_SEQ)
462        });
463        self.recently_edited
464            .retain(|_, &mut edit_seq| seq.saturating_sub(edit_seq) <= TRACKED_PATH_TTL_SEQ);
465    }
466
467    pub fn should_force_full(&self, path: &str) -> bool {
468        let norm = crate::core::pathutil::normalize_tool_path(path);
469
470        if let Some(&edit_seq) = self.recently_edited.get(&norm)
471            && self.seq_counter.saturating_sub(edit_seq) <= EDIT_FORCE_WINDOW
472        {
473            return true;
474        }
475
476        let ext = extension_of(path);
477        if !ext.is_empty()
478            && let Some(stats) = self.per_extension.get(&ext)
479            && stats.total_reads >= 3
480        {
481            let rate = stats.bounces as f64 / stats.total_reads as f64;
482            if rate >= BOUNCE_RATE_THRESHOLD {
483                return true;
484            }
485        }
486
487        false
488    }
489
490    pub fn bounce_rate_for_extension(&self, path: &str) -> Option<f64> {
491        let ext = extension_of(path);
492        self.per_extension.get(&ext).and_then(|s| {
493            if s.total_reads >= 3 {
494                Some(s.bounces as f64 / s.total_reads as f64)
495            } else {
496                None
497            }
498        })
499    }
500
501    pub fn total_bounces(&self) -> u64 {
502        self.total_bounces
503    }
504
505    pub fn total_wasted_tokens(&self) -> usize {
506        self.total_wasted_tokens
507    }
508
509    pub fn adjusted_savings(&self, raw_savings: usize) -> isize {
510        raw_savings as isize - self.total_wasted_tokens as isize
511    }
512
513    pub fn per_extension_json(&self) -> Vec<serde_json::Value> {
514        let mut exts: Vec<_> = self
515            .per_extension
516            .iter()
517            .filter(|(_, s)| s.total_reads > 0)
518            .collect();
519        exts.sort_by_key(|a| std::cmp::Reverse(a.1.bounces));
520        exts.iter()
521            .take(10)
522            .map(|(ext, stats)| {
523                let rate = if stats.total_reads > 0 {
524                    stats.bounces as f64 / stats.total_reads as f64
525                } else {
526                    0.0
527                };
528                serde_json::json!({
529                    "ext": ext,
530                    "reads": stats.total_reads,
531                    "bounces": stats.bounces,
532                    "wasted_tokens": stats.wasted_tokens,
533                    "rate": (rate * 1000.0).round() / 1000.0,
534                })
535            })
536            .collect()
537    }
538
539    pub fn format_summary(&self) -> String {
540        if self.total_bounces == 0 {
541            return "Bounces: 0".to_string();
542        }
543        let mut lines = vec![format!(
544            "Bounces: {} ({} wasted tokens)",
545            self.total_bounces, self.total_wasted_tokens
546        )];
547        let mut exts: Vec<_> = self
548            .per_extension
549            .iter()
550            .filter(|(_, s)| s.bounces > 0)
551            .collect();
552        exts.sort_by_key(|a| std::cmp::Reverse(a.1.bounces));
553        for (ext, stats) in exts.iter().take(5) {
554            let rate = if stats.total_reads > 0 {
555                stats.bounces as f64 / stats.total_reads as f64 * 100.0
556            } else {
557                0.0
558            };
559            lines.push(format!(
560                "  {ext}: {}/{} reads bounced ({rate:.0}%), {} tok wasted",
561                stats.bounces, stats.total_reads, stats.wasted_tokens,
562            ));
563        }
564        lines.join("\n")
565    }
566}
567
568static GLOBAL_TRACKER: OnceLock<Mutex<BounceTracker>> = OnceLock::new();
569
570pub fn global() -> &'static Mutex<BounceTracker> {
571    GLOBAL_TRACKER.get_or_init(|| {
572        // Seed from the persistent ledger so every process (including a fresh `gain`)
573        // accounts for historical bounce, then mark this tracker as the persisting one.
574        let summary = crate::core::savings_ledger::summary();
575        let mut bt = BounceTracker::new();
576        bt.total_wasted_tokens = summary.bounce_tokens as usize;
577        bt.total_bounces = summary.bounce_events as u64;
578        bt.persist = true;
579        Mutex::new(bt)
580    })
581}
582
583/// Process shutdown: commit the global tracker's provisional bounces. A no-op
584/// when this process never created the tracker (no read was served).
585pub(crate) fn flush_pending() {
586    if let Some(tracker) = GLOBAL_TRACKER.get()
587        && let Ok(mut bt) = tracker.lock()
588    {
589        bt.flush_pending();
590    }
591}
592
593fn now_unix_ms() -> u64 {
594    std::time::SystemTime::now()
595        .duration_since(std::time::UNIX_EPOCH)
596        .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
597}
598
599// ── Edit beacon ─────────────────────────────────────────────────────────────
600//
601// Native host edits (Claude Code `Edit`/`Write`, Cursor `StrReplace`, …) are
602// observed by short-lived hook processes, not by the MCP server that holds the
603// in-memory tracker. They append `<unix_ms>\t<normalized path>` to a small
604// append-only file; a provisional bounce consults it once, at commit time, and
605// is cancelled when its path was edited after the detection. Lines are written
606// with one `O_APPEND` write each, so concurrent hook processes do not
607// interleave; the file rotates to `.1` above `EDIT_BEACON_MAX_BYTES`, and the
608// reader scans both generations.
609
610const EDIT_BEACON_FILE: &str = "edit_beacon.log";
611const EDIT_BEACON_MAX_BYTES: u64 = 128 * 1024;
612
613fn edit_beacon_path() -> Option<std::path::PathBuf> {
614    crate::core::data_dir::lean_ctx_data_dir()
615        .ok()
616        .map(|dir| dir.join(EDIT_BEACON_FILE))
617}
618
619fn rotated_beacon_path(path: &std::path::Path) -> std::path::PathBuf {
620    path.with_extension("log.1")
621}
622
623/// Hook processes: report a native host edit of `path` (best-effort).
624pub(crate) fn note_host_edit(path: &str) {
625    let Some(beacon) = edit_beacon_path() else {
626        return;
627    };
628    append_edit_beacon(&beacon, path, now_unix_ms());
629}
630
631/// Hook processes: report the files a native shell command rewrites
632/// (`sed -i`, `>`, `tee`, `cp`/`mv`, `apply_patch` bodies), relative paths
633/// resolved against `cwd`. Best-effort, like [`note_host_edit`].
634pub(crate) fn note_host_shell_edits(command: &str, cwd: &str) {
635    for path in crate::core::shell_file_effects::analyze(command).edits {
636        note_host_edit(&resolve_against(cwd, &path));
637    }
638}
639
640/// Hook processes: report the files of a Codex `apply_patch` patch body.
641pub(crate) fn note_host_patch_edits(patch: &str, cwd: &str) {
642    for path in crate::core::shell_file_effects::apply_patch_targets(patch) {
643        note_host_edit(&resolve_against(cwd, &path));
644    }
645}
646
647/// `path` made absolute against `cwd` (the hook payload's), falling back to
648/// the hook process's own working directory.
649fn resolve_against(cwd: &str, path: &str) -> String {
650    if std::path::Path::new(path).is_absolute() {
651        return path.to_string();
652    }
653    let base = if cwd.trim().is_empty() {
654        std::env::current_dir().ok()
655    } else {
656        Some(std::path::PathBuf::from(cwd))
657    };
658    base.map_or_else(
659        || path.to_string(),
660        |dir| dir.join(path).to_string_lossy().into_owned(),
661    )
662}
663
664fn append_edit_beacon(beacon: &std::path::Path, path: &str, unix_ms: u64) {
665    use std::io::Write;
666    let norm = crate::core::pathutil::normalize_tool_path(path);
667    if norm.is_empty() || norm.contains('\n') {
668        return;
669    }
670    if std::fs::metadata(beacon).is_ok_and(|m| m.len() > EDIT_BEACON_MAX_BYTES) {
671        let _ = std::fs::rename(beacon, rotated_beacon_path(beacon));
672    }
673    if let Some(parent) = beacon.parent() {
674        let _ = std::fs::create_dir_all(parent);
675    }
676    if let Ok(mut file) = std::fs::OpenOptions::new()
677        .create(true)
678        .append(true)
679        .open(beacon)
680    {
681        let _ = file.write_all(format!("{unix_ms}\t{norm}\n").as_bytes());
682    }
683}
684
685fn host_edited_since(norm_path: &str, since_unix_ms: u64) -> bool {
686    edit_beacon_path().is_some_and(|beacon| beacon_has_edit(&beacon, norm_path, since_unix_ms))
687}
688
689fn beacon_has_edit(beacon: &std::path::Path, norm_path: &str, since_unix_ms: u64) -> bool {
690    use std::io::Read;
691    [rotated_beacon_path(beacon), beacon.to_path_buf()]
692        .iter()
693        .any(|file| {
694            let Ok(handle) = std::fs::File::open(file) else {
695                return false;
696            };
697            let mut raw = String::new();
698            // Bounded: rotation keeps each generation near EDIT_BEACON_MAX_BYTES.
699            if handle
700                .take(EDIT_BEACON_MAX_BYTES * 2)
701                .read_to_string(&mut raw)
702                .is_err()
703            {
704                return false;
705            }
706            raw.lines().any(|line| {
707                line.split_once('\t').is_some_and(|(ts, path)| {
708                    path == norm_path && ts.parse::<u64>().is_ok_and(|ts| ts >= since_unix_ms)
709                })
710            })
711        })
712}
713
714#[cfg(test)]
715pub mod tests {
716    use super::*;
717
718    #[test]
719    fn no_bounce_when_first_read_is_full() {
720        let mut bt = BounceTracker::new();
721        bt.seq_counter = 1;
722        bt.record_read("src/main.rs", "full", 500, 500);
723        assert_eq!(bt.total_bounces(), 0);
724        assert_eq!(bt.total_wasted_tokens(), 0);
725    }
726
727    #[test]
728    fn bounce_detected_on_compressed_then_full() {
729        let mut bt = BounceTracker::new();
730        bt.seq_counter = 1;
731        bt.record_read("src/main.rs", "map", 50, 500);
732        bt.seq_counter = 2;
733        bt.record_read("src/main.rs", "full", 500, 500);
734        assert_eq!(
735            bt.pending_bounces(),
736            1,
737            "provisional until the edit window passes"
738        );
739        bt.flush_pending();
740        assert_eq!(bt.total_bounces(), 1);
741        assert_eq!(bt.total_wasted_tokens(), 50);
742    }
743
744    #[test]
745    fn full_reread_of_externally_edited_file_is_not_a_bounce() {
746        // A host's native Edit/Write runs in another process and never calls
747        // `record_edit`; the moved mtime is what exempts the re-read.
748        let dir = tempfile::tempdir().unwrap();
749        let file = dir.path().join("edited.rs");
750        std::fs::write(&file, "fn a() {}\n").unwrap();
751        let path = file.to_str().unwrap();
752        let old = std::time::SystemTime::now() - std::time::Duration::from_mins(2);
753        std::fs::File::options()
754            .write(true)
755            .open(&file)
756            .unwrap()
757            .set_times(std::fs::FileTimes::new().set_modified(old))
758            .unwrap();
759
760        let mut bt = BounceTracker::new();
761        bt.seq_counter = 1;
762        bt.record_read(path, "map", 40, 500);
763        std::fs::write(&file, "fn a() { changed() }\n").unwrap();
764        bt.seq_counter = 2;
765        bt.record_read(path, "full", 500, 500);
766        bt.flush_pending();
767        assert_eq!(bt.total_bounces(), 0, "re-read after an edit is no bounce");
768
769        // Unchanged file: the same pattern is still a real bounce.
770        bt.seq_counter = 10;
771        bt.record_read(path, "map", 40, 500);
772        bt.seq_counter = 11;
773        bt.record_read(path, "full", 500, 500);
774        bt.flush_pending();
775        assert_eq!(bt.total_bounces(), 1);
776    }
777
778    #[test]
779    fn no_bounce_outside_window() {
780        let mut bt = BounceTracker::new();
781        bt.seq_counter = 1;
782        bt.record_read("src/main.rs", "map", 50, 500);
783        bt.seq_counter = 10;
784        bt.record_read("src/main.rs", "full", 500, 500);
785        assert_eq!(bt.total_bounces(), 0);
786    }
787
788    #[test]
789    fn shell_access_triggers_bounce() {
790        let mut bt = BounceTracker::new();
791        bt.seq_counter = 1;
792        bt.record_read("config.yml", "signatures", 30, 400);
793        bt.seq_counter = 3;
794        bt.record_shell_read("config.yml", ReadView::Full);
795        // A second `cat` does not book the same correction again.
796        bt.seq_counter = 4;
797        bt.record_shell_read("config.yml", ReadView::Full);
798        bt.flush_pending();
799        assert_eq!(bt.total_bounces(), 1);
800        assert_eq!(bt.total_wasted_tokens(), 30);
801    }
802
803    #[test]
804    fn read_view_classification() {
805        for mode in ["full", "full-compact", "raw", "anchored"] {
806            assert_eq!(ReadView::of_mode(mode), ReadView::Full, "{mode}");
807        }
808        for mode in [
809            "lines:10-40",
810            "lines:5,10-20",
811            "lines:-30",
812            "anchored:10-20",
813            "diff",
814            "bogus",
815        ] {
816            assert_eq!(ReadView::of_mode(mode), ReadView::Partial, "{mode}");
817        }
818        for mode in [
819            "map",
820            "signatures",
821            "aggressive",
822            "entropy",
823            "task",
824            "reference",
825            "cognitive",
826            "mdl",
827            "auto",
828            "density:0.40",
829        ] {
830            assert_eq!(ReadView::of_mode(mode), ReadView::Compressed, "{mode}");
831        }
832    }
833
834    /// Reading a file window by window, then in full, is no correction:
835    /// windows are precise reads, not lossy views.
836    #[test]
837    fn lines_then_full_is_not_a_bounce() {
838        let mut bt = BounceTracker::new();
839        bt.next_seq();
840        bt.record_read("docs/guide.md", "lines:1-80", 300, 2000);
841        bt.next_seq();
842        bt.record_read("docs/guide.md", "lines:81-160", 300, 2000);
843        bt.next_seq();
844        bt.record_read("docs/guide.md", "full", 2000, 2000);
845        bt.next_seq();
846        bt.record_shell_read("docs/guide.md", ReadView::Full);
847        bt.flush_pending();
848        assert_eq!(bt.total_bounces(), 0);
849    }
850
851    #[test]
852    fn map_then_head_is_not_a_bounce() {
853        let mut bt = BounceTracker::new();
854        bt.next_seq();
855        bt.record_read("src/a.rs", "map", 40, 500);
856        bt.next_seq();
857        bt.record_shell_read("src/a.rs", ReadView::Partial);
858        assert_eq!(bt.pending_bounces(), 0);
859        // The window ended the chain: a later full read is not the map's fault.
860        bt.next_seq();
861        bt.record_shell_read("src/a.rs", ReadView::Full);
862        bt.flush_pending();
863        assert_eq!(bt.total_bounces(), 0);
864    }
865
866    #[test]
867    fn map_then_lines_window_is_not_a_bounce() {
868        let mut bt = BounceTracker::new();
869        bt.next_seq();
870        bt.record_read("src/a.rs", "map", 40, 500);
871        bt.next_seq();
872        bt.record_read("src/a.rs", "lines:20-60", 120, 500);
873        bt.flush_pending();
874        assert_eq!(bt.total_bounces(), 0);
875    }
876
877    #[test]
878    fn map_then_cat_is_a_bounce_unless_edited() {
879        let mut bt = BounceTracker::new();
880        bt.next_seq();
881        bt.record_read("src/a.rs", "map", 40, 500);
882        bt.next_seq();
883        bt.record_shell_read("src/a.rs", ReadView::Full);
884        assert_eq!(bt.pending_bounces(), 1);
885        bt.flush_pending();
886        assert_eq!(bt.total_bounces(), 1);
887        assert_eq!(bt.total_wasted_tokens(), 40);
888
889        let mut edited = BounceTracker::new();
890        edited.next_seq();
891        edited.record_read("src/b.rs", "map", 40, 500);
892        edited.next_seq();
893        edited.record_shell_read("src/b.rs", ReadView::Full);
894        edited.next_seq();
895        // e.g. `sed -i` through ctx_shell
896        edited.record_edit("src/b.rs");
897        edited.flush_pending();
898        assert_eq!(edited.total_bounces(), 0);
899    }
900
901    /// `anchored` is verbatim: it never starts a correction, and as full
902    /// content it completes one (cancelled by the `ctx_patch` that follows).
903    #[test]
904    fn anchored_is_full_content() {
905        let mut bt = BounceTracker::new();
906        bt.next_seq();
907        bt.record_read("src/a.rs", "anchored", 500, 500);
908        bt.next_seq();
909        bt.record_read("src/a.rs", "full", 500, 500);
910        assert_eq!(bt.pending_bounces(), 0, "anchored→full is no correction");
911
912        bt.next_seq();
913        bt.record_read("src/a.rs", "map", 40, 500);
914        bt.next_seq();
915        bt.record_read("src/a.rs", "anchored", 500, 500);
916        assert_eq!(bt.pending_bounces(), 1);
917        bt.next_seq();
918        bt.record_edit("src/a.rs");
919        bt.flush_pending();
920        assert_eq!(bt.total_bounces(), 0);
921    }
922
923    #[test]
924    fn diff_never_completes_a_correction() {
925        let mut bt = BounceTracker::new();
926        bt.next_seq();
927        bt.record_read("src/a.rs", "map", 40, 500);
928        bt.next_seq();
929        bt.record_read("src/a.rs", "diff", 20, 500);
930        bt.flush_pending();
931        assert_eq!(bt.total_bounces(), 0);
932    }
933
934    #[test]
935    fn partial_read_is_not_charged_as_compressed() {
936        let mut bt = BounceTracker::new();
937        bt.next_seq();
938        bt.record_read("src/a.rs", "lines:1-20", 100, 500);
939        assert_eq!(bt.last_read("src/a.rs").map(|(c, _)| c), Some(false));
940        bt.next_seq();
941        bt.record_read("src/a.rs", "map", 40, 500);
942        assert_eq!(bt.last_read("src/a.rs").map(|(c, _)| c), Some(true));
943    }
944
945    #[test]
946    fn explicit_expansion_tracks_quality_and_waste() {
947        let mut bt = BounceTracker::new();
948        bt.record_expansion(Some("src/main.rs"), 125);
949        assert_eq!(bt.total_bounces(), 1);
950        assert_eq!(bt.total_wasted_tokens(), 125);
951    }
952
953    #[test]
954    fn edit_forced_full_read_is_not_a_bounce() {
955        // GL #622: a compressed overview read, then an edit, then the `full`
956        // re-read that `should_force_full` mandates must NOT register as a bounce
957        // — the edit forced it, the compression did not fail.
958        let mut bt = BounceTracker::new();
959        bt.seq_counter = 1;
960        bt.record_read("src/lib.rs", "map", 40, 500);
961        bt.seq_counter = 2;
962        bt.record_edit("src/lib.rs");
963        bt.seq_counter = 4;
964        bt.record_read("src/lib.rs", "full", 500, 500);
965        assert_eq!(
966            bt.total_bounces(),
967            0,
968            "edit-forced full read must not count as a compression bounce"
969        );
970    }
971
972    #[test]
973    fn full_read_without_edit_still_bounces() {
974        // The guard is scoped to edit-forced reads only: an unprompted full
975        // re-read after a compressed read is still a real bounce.
976        let mut bt = BounceTracker::new();
977        bt.seq_counter = 1;
978        bt.record_read("src/lib.rs", "map", 40, 500);
979        bt.seq_counter = 3;
980        bt.record_read("src/lib.rs", "full", 500, 500);
981        bt.flush_pending();
982        assert_eq!(bt.total_bounces(), 1);
983    }
984
985    #[test]
986    fn should_force_full_after_edit() {
987        let mut bt = BounceTracker::new();
988        bt.seq_counter = 5;
989        bt.record_edit("src/lib.rs");
990        bt.seq_counter = 8;
991        assert!(bt.should_force_full("src/lib.rs"));
992        bt.seq_counter = 20;
993        assert!(!bt.should_force_full("src/lib.rs"));
994    }
995
996    #[test]
997    fn should_force_full_by_extension_bounce_rate() {
998        let mut bt = BounceTracker::new();
999        for i in 1..=6 {
1000            bt.seq_counter = i * 2 - 1;
1001            bt.record_read(&format!("f{i}.yml"), "map", 30, 400);
1002            bt.seq_counter = i * 2;
1003            bt.record_read(&format!("f{i}.yml"), "full", 400, 400);
1004        }
1005        bt.flush_pending();
1006        assert!(bt.should_force_full("new.yml"));
1007    }
1008
1009    #[test]
1010    fn adjusted_savings_subtracts_waste() {
1011        let mut bt = BounceTracker::new();
1012        bt.seq_counter = 1;
1013        bt.record_read("a.rs", "map", 50, 500);
1014        bt.seq_counter = 2;
1015        bt.record_read("a.rs", "full", 500, 500);
1016        bt.flush_pending();
1017        assert_eq!(bt.adjusted_savings(1000), 950);
1018    }
1019
1020    #[test]
1021    fn bounce_rate_for_extension_below_minimum() {
1022        let bt = BounceTracker::new();
1023        assert!(bt.bounce_rate_for_extension("test.rs").is_none());
1024    }
1025
1026    #[test]
1027    fn format_summary_empty() {
1028        let bt = BounceTracker::new();
1029        assert_eq!(bt.format_summary(), "Bounces: 0");
1030    }
1031
1032    #[test]
1033    fn map_full_edit_is_not_a_bounce() {
1034        // Read-before-edit: orient compressed, read full, edit. The full read
1035        // was the edit's preparation, not a compression failure.
1036        let mut bt = BounceTracker::new();
1037        bt.next_seq();
1038        bt.record_read("src/edit_me.rs", "map", 40, 500);
1039        bt.next_seq();
1040        bt.record_read("src/edit_me.rs", "full", 500, 500);
1041        assert_eq!(bt.pending_bounces(), 1);
1042        for _ in 0..3 {
1043            bt.next_seq();
1044        }
1045        bt.record_edit("src/edit_me.rs");
1046        assert_eq!(
1047            bt.pending_bounces(),
1048            0,
1049            "the edit cancels the provisional bounce"
1050        );
1051        for _ in 0..(EDIT_FORCE_WINDOW + 5) {
1052            bt.next_seq();
1053        }
1054        bt.flush_pending();
1055        assert_eq!(bt.total_bounces(), 0);
1056        assert_eq!(bt.total_wasted_tokens(), 0);
1057    }
1058
1059    #[test]
1060    fn map_full_without_edit_commits_when_window_passes() {
1061        let mut bt = BounceTracker::new();
1062        bt.next_seq();
1063        bt.record_read("src/only_read.rs", "map", 40, 500);
1064        bt.next_seq();
1065        bt.record_read("src/only_read.rs", "full", 500, 500);
1066        for _ in 0..EDIT_FORCE_WINDOW {
1067            bt.next_seq();
1068        }
1069        assert_eq!(bt.total_bounces(), 0, "still inside the edit window");
1070        bt.next_seq();
1071        assert_eq!(bt.pending_bounces(), 0);
1072        assert_eq!(bt.total_bounces(), 1, "committed once the window passed");
1073        assert_eq!(bt.total_wasted_tokens(), 40);
1074        // An edit after the window no longer changes the booked bounce.
1075        bt.record_edit("src/only_read.rs");
1076        assert_eq!(bt.total_bounces(), 1);
1077    }
1078
1079    #[test]
1080    fn edit_of_another_path_keeps_the_bounce() {
1081        let mut bt = BounceTracker::new();
1082        bt.next_seq();
1083        bt.record_read("src/a.rs", "map", 40, 500);
1084        bt.next_seq();
1085        bt.record_read("src/a.rs", "full", 500, 500);
1086        bt.record_edit("src/b.rs");
1087        bt.flush_pending();
1088        assert_eq!(bt.total_bounces(), 1);
1089    }
1090
1091    #[test]
1092    fn flush_pending_commits_at_shutdown() {
1093        let mut bt = BounceTracker::new();
1094        bt.next_seq();
1095        bt.record_read("src/late.rs", "signatures", 25, 300);
1096        bt.next_seq();
1097        bt.record_read("src/late.rs", "full", 300, 300);
1098        assert_eq!(bt.total_bounces(), 0);
1099        bt.flush_pending();
1100        assert_eq!(bt.pending_bounces(), 0);
1101        assert_eq!(bt.total_bounces(), 1);
1102        assert_eq!(bt.total_wasted_tokens(), 25);
1103    }
1104
1105    #[test]
1106    fn pending_queue_is_bounded() {
1107        let mut bt = BounceTracker::new();
1108        for i in 0..(MAX_PENDING_BOUNCES + 4) {
1109            let path = format!("src/burst{i}.rs");
1110            bt.record_read(&path, "map", 10, 100);
1111            bt.record_read(&path, "full", 100, 100);
1112        }
1113        assert_eq!(bt.pending_bounces(), MAX_PENDING_BOUNCES);
1114        assert_eq!(bt.total_bounces(), 4, "overflow commits the oldest early");
1115    }
1116
1117    #[test]
1118    fn edit_beacon_reports_host_edits_after_detection() {
1119        let dir = tempfile::tempdir().unwrap();
1120        let beacon = dir.path().join(EDIT_BEACON_FILE);
1121        let file = dir.path().join("edited.rs");
1122        std::fs::write(&file, "fn main() {}\n").unwrap();
1123        let path = file.to_string_lossy().to_string();
1124        let norm = crate::core::pathutil::normalize_tool_path(&path);
1125
1126        assert!(!beacon_has_edit(&beacon, &norm, 0), "no beacon yet");
1127        append_edit_beacon(&beacon, &path, 2_000);
1128        assert!(
1129            beacon_has_edit(&beacon, &norm, 1_500),
1130            "edit after detection"
1131        );
1132        assert!(
1133            !beacon_has_edit(&beacon, &norm, 2_500),
1134            "edit before detection"
1135        );
1136        assert!(!beacon_has_edit(&beacon, "/other/path.rs", 0));
1137    }
1138
1139    #[test]
1140    fn edit_beacon_rotation_keeps_the_previous_generation_readable() {
1141        let dir = tempfile::tempdir().unwrap();
1142        let beacon = dir.path().join(EDIT_BEACON_FILE);
1143        append_edit_beacon(&beacon, "/rotated/first.rs", 10);
1144        let filler = "x".repeat(usize::try_from(EDIT_BEACON_MAX_BYTES).unwrap() + 1);
1145        std::fs::OpenOptions::new()
1146            .append(true)
1147            .open(&beacon)
1148            .and_then(|mut f| std::io::Write::write_all(&mut f, filler.as_bytes()))
1149            .unwrap();
1150        append_edit_beacon(&beacon, "/rotated/second.rs", 20);
1151        assert!(rotated_beacon_path(&beacon).exists());
1152        assert!(beacon_has_edit(&beacon, "/rotated/first.rs", 0));
1153        assert!(beacon_has_edit(&beacon, "/rotated/second.rs", 0));
1154    }
1155}