Skip to main content

lean_ctx/core/context_ledger/
ledger.rs

1use std::collections::HashMap;
2
3use crate::core::context_field::{
4    ContextItemId, ContextKind, ContextState, Provenance, ViewCosts, ViewKind,
5};
6
7use super::helpers::{
8    DEFAULT_CONTEXT_WINDOW, GWT_MIN_ENTRIES, PHI_REREAD_ALPHA, acquire_ledger_lock,
9    atomic_write_json, ledger_path,
10};
11use super::reinjection::ignition_z_threshold;
12use super::types::{
13    ContextLedger, ContextPressure, EvictOutcome, LedgerEntry, LedgerResolution, PressureAction,
14};
15
16impl ContextLedger {
17    pub fn new() -> Self {
18        Self {
19            window_size: DEFAULT_CONTEXT_WINDOW,
20            entries: Vec::new(),
21            total_tokens_sent: 0,
22            total_tokens_saved: 0,
23            last_flush: None,
24        }
25    }
26
27    pub fn with_window_size(size: usize) -> Self {
28        Self {
29            window_size: size,
30            entries: Vec::new(),
31            total_tokens_sent: 0,
32            total_tokens_saved: 0,
33            last_flush: None,
34        }
35    }
36
37    pub fn record(&mut self, path: &str, mode: &str, original_tokens: usize, sent_tokens: usize) {
38        self.record_with_task(path, mode, original_tokens, sent_tokens, None);
39    }
40
41    pub fn record_shell(&mut self, command: &str, original_tokens: usize, sent_tokens: usize) {
42        self.record_with_task(command, "shell", original_tokens, sent_tokens, None);
43        if let Some(entry) = self.entries.iter_mut().find(|e| e.path == command) {
44            entry.kind = Some(ContextKind::Shell);
45        }
46    }
47
48    pub fn record_with_task(
49        &mut self,
50        path: &str,
51        mode: &str,
52        original_tokens: usize,
53        sent_tokens: usize,
54        task: Option<&str>,
55    ) {
56        let path = crate::core::pathutil::normalize_tool_path(path);
57        let item_id = ContextItemId::from_file(&path);
58
59        let phi =
60            Self::compute_real_phi(&path, sent_tokens, original_tokens, self.window_size, task);
61
62        if let Some(existing) = self.entries.iter_mut().find(|e| e.path == path) {
63            self.total_tokens_sent -= existing.sent_tokens;
64            self.total_tokens_saved -= existing
65                .original_tokens
66                .saturating_sub(existing.sent_tokens);
67            existing.mode = mode.to_string();
68            existing.original_tokens = original_tokens;
69            existing.sent_tokens = sent_tokens;
70            existing.timestamp = chrono::Utc::now().timestamp();
71            existing.access_count = existing.access_count.saturating_add(1);
72            existing.active_view = Some(ViewKind::parse(mode));
73            if existing.id.is_none() {
74                existing.id = Some(item_id);
75            }
76            if existing.state.is_none() || existing.state == Some(ContextState::Candidate) {
77                existing.state = Some(ContextState::Included);
78            }
79            // #2 Sticky-Phi fix: salience is time-variant (recency, task match,
80            // access frequency all changed since the first read), so recompute
81            // Phi on every re-read instead of freezing the first value. Blend
82            // with the prior score via a fixed-alpha EMA — deterministic, and
83            // damped so a single noisy read can't whipsaw eviction order.
84            existing.phi = Some(match existing.phi {
85                Some(old) => PHI_REREAD_ALPHA * phi + (1.0 - PHI_REREAD_ALPHA) * old,
86                None => phi,
87            });
88            crate::core::introspect::tick("phi_recompute");
89        } else {
90            self.entries.push(LedgerEntry {
91                path: path.clone(),
92                mode: mode.to_string(),
93                original_tokens,
94                sent_tokens,
95                timestamp: chrono::Utc::now().timestamp(),
96                id: Some(item_id),
97                kind: Some(ContextKind::File),
98                source_hash: None,
99                state: Some(ContextState::Included),
100                phi: Some(phi),
101                view_costs: Some(ViewCosts::from_full_tokens(original_tokens)),
102                active_view: Some(ViewKind::parse(mode)),
103                provenance: None,
104                access_count: 1,
105            });
106        }
107        self.total_tokens_sent += sent_tokens;
108        self.total_tokens_saved += original_tokens.saturating_sub(sent_tokens);
109    }
110
111    fn compute_real_phi(
112        path: &str,
113        sent_tokens: usize,
114        original_tokens: usize,
115        window_size: usize,
116        task: Option<&str>,
117    ) -> f64 {
118        use crate::core::context_field::{ContextField, compute_signals_for_path};
119
120        let (signals, _costs) =
121            compute_signals_for_path(path, task, None, window_size, original_tokens);
122        // #4: use the learned (bandit-selected) field weights when available.
123        let phi = ContextField::active().compute_phi(&signals);
124        if phi > 0.0 {
125            return phi;
126        }
127
128        Self::compute_lightweight_phi(sent_tokens, window_size)
129    }
130
131    fn compute_lightweight_phi(sent_tokens: usize, window_size: usize) -> f64 {
132        use crate::core::context_field::{ContextField, FieldSignals};
133        let token_cost_norm = if window_size > 0 {
134            (sent_tokens as f64 / window_size as f64).min(1.0)
135        } else {
136            0.0
137        };
138        let signals = FieldSignals {
139            relevance: 1.0,
140            surprise: 0.5,
141            graph_proximity: 0.0,
142            history_signal: 0.0,
143            token_cost_norm,
144            redundancy: 0.0,
145        };
146        ContextField::active().compute_phi(&signals)
147    }
148
149    /// Record with full CFT metadata including source hash and provenance.
150    pub fn upsert(
151        &mut self,
152        path: &str,
153        mode: &str,
154        original_tokens: usize,
155        sent_tokens: usize,
156        source_hash: Option<&str>,
157        kind: ContextKind,
158        provenance: Option<Provenance>,
159    ) {
160        self.record(path, mode, original_tokens, sent_tokens);
161        if let Some(entry) = self.entries.iter_mut().find(|e| e.path == path) {
162            entry.kind = Some(kind);
163            if let Some(h) = source_hash
164                && entry.source_hash.as_deref() != Some(h)
165            {
166                if entry.source_hash.is_some() {
167                    entry.state = Some(ContextState::Stale);
168                }
169                entry.source_hash = Some(h.to_string());
170            }
171            if let Some(prov) = provenance {
172                entry.provenance = Some(prov);
173            }
174        }
175    }
176
177    /// Update the Phi score for an entry.
178    pub fn update_phi(&mut self, path: &str, phi: f64) {
179        if let Some(entry) = self.entries.iter_mut().find(|e| e.path == path) {
180            entry.phi = Some(phi);
181        }
182    }
183
184    /// Set the state for an entry. Accepts partial paths and basenames via
185    /// [`Self::resolve_entry`] (#715).
186    pub fn set_state(&mut self, path: &str, state: ContextState) {
187        if let LedgerResolution::Unique(idx) = self.resolve_entry(path, None) {
188            self.entries[idx].state = Some(state);
189        }
190    }
191
192    /// Resolve a user-supplied target against the ledger (#715):
193    /// exact match → project-root-relative → unambiguous suffix at a path
194    /// component boundary. Entries are stored as normalized absolute paths
195    /// (forward slashes); targets arrive as basenames, relative paths, or
196    /// OS-native separators.
197    pub fn resolve_entry(&self, target: &str, project_root: Option<&str>) -> LedgerResolution {
198        let lex = crate::core::pathutil::normalize_tool_path_lexical(target);
199        if lex.is_empty() {
200            return LedgerResolution::NotFound;
201        }
202
203        // Stage 1 — exact: lexical form first (no FS access), then the fully
204        // canonical form (resolves symlinks, matching what `record` stored).
205        if let Some(idx) = self.entries.iter().position(|e| e.path == lex) {
206            return LedgerResolution::Unique(idx);
207        }
208        let full = crate::core::pathutil::normalize_tool_path(target);
209        if full != lex
210            && let Some(idx) = self.entries.iter().position(|e| e.path == full)
211        {
212            return LedgerResolution::Unique(idx);
213        }
214
215        // Stage 2 — relative to the project root.
216        if let Some(root) = project_root.filter(|r| !r.is_empty()) {
217            let joined = format!(
218                "{}/{}",
219                root.trim_end_matches(['/', '\\']),
220                lex.trim_start_matches('/')
221            );
222            let joined_lex = crate::core::pathutil::normalize_tool_path_lexical(&joined);
223            if let Some(idx) = self.entries.iter().position(|e| e.path == joined_lex) {
224                return LedgerResolution::Unique(idx);
225            }
226            let joined_full = crate::core::pathutil::normalize_tool_path(&joined_lex);
227            if joined_full != joined_lex
228                && let Some(idx) = self.entries.iter().position(|e| e.path == joined_full)
229            {
230                return LedgerResolution::Unique(idx);
231            }
232        }
233
234        // Stage 3 — unambiguous suffix at a component boundary ("/…"), so
235        // `main.rs` matches `src/main.rs` but never `domain.rs`.
236        let suffix = format!("/{}", lex.trim_start_matches('/'));
237        let matches: Vec<usize> = self
238            .entries
239            .iter()
240            .enumerate()
241            .filter(|(_, e)| e.path.ends_with(&suffix))
242            .map(|(idx, _)| idx)
243            .collect();
244        match matches.len() {
245            1 => LedgerResolution::Unique(matches[0]),
246            0 => LedgerResolution::NotFound,
247            _ => LedgerResolution::Ambiguous(
248                matches
249                    .iter()
250                    .map(|&idx| self.entries[idx].path.clone())
251                    .collect(),
252            ),
253        }
254    }
255
256    /// Find an entry by its ContextItemId.
257    pub fn find_by_id(&self, id: &ContextItemId) -> Option<&LedgerEntry> {
258        self.entries.iter().find(|e| e.id.as_ref() == Some(id))
259    }
260
261    /// Get all entries with a specific state.
262    pub fn items_by_state(&self, state: ContextState) -> Vec<&LedgerEntry> {
263        self.entries
264            .iter()
265            .filter(|e| e.state == Some(state))
266            .collect()
267    }
268
269    /// Eviction candidates ordered by Phi (lowest first), falling back to
270    /// timestamp for entries without Phi scores.
271    pub fn eviction_candidates_by_phi(&self, keep_count: usize) -> Vec<String> {
272        if self.entries.len() <= keep_count {
273            return Vec::new();
274        }
275        let mut sorted = self.entries.clone();
276        sorted.sort_by(|a, b| {
277            let a_phi = a.phi.unwrap_or(0.0);
278            let b_phi = b.phi.unwrap_or(0.0);
279            a_phi
280                .partial_cmp(&b_phi)
281                .unwrap_or(std::cmp::Ordering::Equal)
282                .then_with(|| a.timestamp.cmp(&b.timestamp))
283        });
284        sorted
285            .iter()
286            .filter(|e| e.state != Some(ContextState::Pinned))
287            .take(self.entries.len() - keep_count)
288            .map(|e| e.path.clone())
289            .collect()
290    }
291
292    /// Global-Workspace ignition (#6): context items compete on salience (Phi);
293    /// any whose z-score exceeds the ignition threshold is "broadcast" — promoted
294    /// to Pinned so it survives eviction (`eviction_candidates_by_phi` already
295    /// skips Pinned) and pressure reinjection, and reaches the compiler's working
296    /// set as a pinned candidate. Deterministic: a pure threshold over the current
297    /// Phi distribution, no sampling. Returns the paths newly ignited this call.
298    pub fn ignite_high_salience(&mut self) -> Vec<String> {
299        let z_threshold = ignition_z_threshold();
300        let phis: Vec<f64> = self.entries.iter().filter_map(|e| e.phi).collect();
301        if phis.len() < GWT_MIN_ENTRIES {
302            return Vec::new();
303        }
304        let n = phis.len() as f64;
305        let mean = phis.iter().sum::<f64>() / n;
306        let var = phis.iter().map(|p| (p - mean).powi(2)).sum::<f64>() / n;
307        let std = var.sqrt();
308        if std <= f64::EPSILON {
309            return Vec::new();
310        }
311
312        let mut ignited = Vec::new();
313        for e in &mut self.entries {
314            let Some(phi) = e.phi else { continue };
315            let state = e.state.unwrap_or(ContextState::Included);
316            if matches!(state, ContextState::Excluded | ContextState::Pinned) {
317                continue;
318            }
319            if (phi - mean) / std > z_threshold {
320                e.state = Some(ContextState::Pinned);
321                ignited.push(e.path.clone());
322            }
323        }
324        if !ignited.is_empty() {
325            crate::core::introspect::tick("gwt_ignition");
326        }
327        ignited
328    }
329
330    /// Mark entries as stale if their source hash has changed.
331    pub fn mark_stale_by_hash(&mut self, path: &str, new_hash: &str) {
332        if let Some(entry) = self.entries.iter_mut().find(|e| e.path == path)
333            && let Some(ref old_hash) = entry.source_hash
334            && old_hash != new_hash
335        {
336            entry.state = Some(ContextState::Stale);
337            entry.source_hash = Some(new_hash.to_string());
338        }
339    }
340
341    pub fn pressure(&self) -> ContextPressure {
342        let utilization = self.total_tokens_sent as f64 / self.window_size as f64;
343
344        let pinned_count = self
345            .entries
346            .iter()
347            .filter(|e| e.state == Some(ContextState::Pinned))
348            .count();
349        let stale_count = self
350            .entries
351            .iter()
352            .filter(|e| e.state == Some(ContextState::Stale))
353            .count();
354        let pinned_pressure = pinned_count as f64 * 0.02;
355        let stale_penalty = stale_count as f64 * 0.01;
356        // Pinned/stale entries reduce eviction flexibility, so they nudge
357        // pressure upward — but the nudge must stay bounded. Without a cap, a
358        // long session where many entries end up Pinned (e.g. via GWT
359        // ignition, #6) can alone drive utilization to 100% regardless of
360        // actual token usage.
361        const MAX_STATE_PRESSURE: f64 = 0.2;
362        let effective_utilization =
363            (utilization + (pinned_pressure + stale_penalty).min(MAX_STATE_PRESSURE)).min(1.0);
364
365        // `remaining_tokens` is a literal token-budget figure consumed by
366        // dashboards and the deficit-suggestion auto-loader
367        // (`context_deficit.rs`) as "how much room is actually left" — it
368        // must track real usage, not the heuristic-boosted
369        // `effective_utilization`, or a heavily-pinned/stale session reports
370        // 0 remaining (and silently starves auto-loading) while tokens of
371        // real headroom are still free.
372        let remaining = self.window_size.saturating_sub(self.total_tokens_sent);
373
374        let recommendation = if effective_utilization > 0.9 {
375            PressureAction::EvictLeastRelevant
376        } else if effective_utilization > 0.75 {
377            PressureAction::ForceCompression
378        } else if effective_utilization > 0.5 {
379            PressureAction::SuggestCompression
380        } else {
381            PressureAction::NoAction
382        };
383
384        ContextPressure {
385            utilization: effective_utilization,
386            remaining_tokens: remaining,
387            entries_count: self.entries.len(),
388            recommendation,
389        }
390    }
391
392    pub fn compression_ratio(&self) -> f64 {
393        let total_original: usize = self.entries.iter().map(|e| e.original_tokens).sum();
394        if total_original == 0 {
395            return 1.0;
396        }
397        self.total_tokens_sent as f64 / total_original as f64
398    }
399
400    pub fn files_by_token_cost(&self) -> Vec<(String, usize)> {
401        let mut costs: Vec<(String, usize)> = self
402            .entries
403            .iter()
404            .map(|e| (e.path.clone(), e.sent_tokens))
405            .collect();
406        costs.sort_by_key(|b| std::cmp::Reverse(b.1));
407        costs
408    }
409
410    pub fn mode_distribution(&self) -> HashMap<String, usize> {
411        let mut dist: HashMap<String, usize> = HashMap::new();
412        for entry in &self.entries {
413            *dist.entry(entry.mode.clone()).or_insert(0) += 1;
414        }
415        dist
416    }
417
418    pub fn eviction_candidates(&self, keep_count: usize) -> Vec<String> {
419        if self.entries.len() <= keep_count {
420            return Vec::new();
421        }
422        let mut sorted = self.entries.clone();
423        sorted.sort_by_key(|e| e.timestamp);
424        sorted
425            .iter()
426            .take(self.entries.len() - keep_count)
427            .map(|e| e.path.clone())
428            .collect()
429    }
430
431    /// Remove one entry by target. Resolves partial paths and basenames
432    /// (#715); an ambiguous target removes nothing.
433    pub fn remove(&mut self, path: &str) -> bool {
434        match self.resolve_entry(path, None) {
435            LedgerResolution::Unique(idx) => {
436                self.remove_at(idx);
437                true
438            }
439            _ => false,
440        }
441    }
442
443    fn remove_at(&mut self, idx: usize) {
444        let entry = &self.entries[idx];
445        self.total_tokens_sent = self.total_tokens_sent.saturating_sub(entry.sent_tokens);
446        self.total_tokens_saved = self
447            .total_tokens_saved
448            .saturating_sub(entry.original_tokens.saturating_sub(entry.sent_tokens));
449        self.entries.remove(idx);
450    }
451
452    /// Clear all entries and reset totals to zero.
453    pub fn reset(&mut self) {
454        let pinned_count = self
455            .entries
456            .iter()
457            .filter(|e| e.state == Some(ContextState::Pinned))
458            .count();
459        self.entries.clear();
460        self.total_tokens_sent = 0;
461        self.total_tokens_saved = 0;
462        if pinned_count > 0 {
463            tracing::info!("{pinned_count} pinned entries were also cleared");
464        }
465    }
466
467    /// Remove specific paths from the ledger. Returns count of entries removed.
468    /// Targets resolve like [`Self::resolve_entry`] (#715).
469    pub fn evict_paths(&mut self, paths: &[&str]) -> usize {
470        self.evict_paths_resolved(paths, None)
471            .iter()
472            .filter(|o| o.resolved.is_some())
473            .count()
474    }
475
476    /// Eviction with full per-target diagnostics (#715): resolves each target
477    /// (exact → root-relative → unique suffix) and reports the canonical path
478    /// it removed, or the ambiguous candidates, so callers can surface WHY
479    /// nothing was evicted instead of a bare "Evicted 0/1".
480    pub fn evict_paths_resolved(
481        &mut self,
482        paths: &[&str],
483        project_root: Option<&str>,
484    ) -> Vec<EvictOutcome> {
485        paths
486            .iter()
487            .map(|target| match self.resolve_entry(target, project_root) {
488                LedgerResolution::Unique(idx) => {
489                    let resolved = self.entries[idx].path.clone();
490                    self.remove_at(idx);
491                    EvictOutcome {
492                        target: (*target).to_string(),
493                        resolved: Some(resolved),
494                        ambiguous: Vec::new(),
495                    }
496                }
497                LedgerResolution::Ambiguous(candidates) => EvictOutcome {
498                    target: (*target).to_string(),
499                    resolved: None,
500                    ambiguous: candidates,
501                },
502                LedgerResolution::NotFound => EvictOutcome {
503                    target: (*target).to_string(),
504                    resolved: None,
505                    ambiguous: Vec::new(),
506                },
507            })
508            .collect()
509    }
510
511    pub fn save(&self) {
512        self.save_for_agent("default");
513    }
514
515    /// Debounced save: only flushes to disk if >=3s since last save.
516    /// Reduces I/O overhead during burst sequences of tool calls.
517    pub fn save_debounced(&mut self) {
518        let now = std::time::Instant::now();
519        if let Some(last) = self.last_flush
520            && now.duration_since(last) < std::time::Duration::from_secs(3)
521        {
522            return;
523        }
524        self.save();
525        self.last_flush = Some(now);
526    }
527
528    pub fn save_for_agent(&self, agent_id: &str) {
529        if let Ok(path) = ledger_path(agent_id) {
530            if let Some(parent) = path.parent() {
531                let _ = std::fs::create_dir_all(parent);
532            }
533            let _lock = acquire_ledger_lock(&path);
534            if let Ok(json) = serde_json::to_string(self) {
535                atomic_write_json(&path, &json);
536            }
537        }
538    }
539
540    const MAX_LEDGER_ENTRIES: usize = 200;
541    const STALE_AGE_SECS: i64 = 7 * 24 * 3600;
542
543    pub fn prune(&mut self) -> usize {
544        let before = self.entries.len();
545        let now = chrono::Utc::now().timestamp();
546
547        for entry in &mut self.entries {
548            if let Some(phi) = entry.phi {
549                let hours_since = ((now - entry.timestamp) as f64 / 3600.0).max(0.0);
550                let decayed = phi * 0.95_f64.powf(hours_since);
551                entry.phi = Some(decayed.max(0.0));
552            }
553        }
554
555        self.entries
556            .retain(|e| !(e.mode == "error" && e.original_tokens == 0));
557
558        self.entries.retain(|e| {
559            let age = now - e.timestamp;
560            let phi = e.phi.unwrap_or(0.0);
561            !(age > Self::STALE_AGE_SECS && phi < 0.1)
562        });
563
564        let mut seen = std::collections::HashSet::new();
565        self.entries.sort_by_key(|e| std::cmp::Reverse(e.timestamp));
566        self.entries.retain(|e| {
567            // Lexical key only: entries were normalized when written, and the
568            // full variant would `realpath` every persisted path — the daemon
569            // runs this at boot (ContextLedger::load → prune) and stat-ing
570            // stored paths under ~/Documents from a launchd process pops the
571            // macOS TCC prompt (#356).
572            let key = crate::core::pathutil::normalize_tool_path_lexical(&e.path);
573            seen.insert(key)
574        });
575
576        if self.entries.len() > Self::MAX_LEDGER_ENTRIES {
577            self.entries.sort_by(|a, b| {
578                let pa = a.phi.unwrap_or(0.0);
579                let pb = b.phi.unwrap_or(0.0);
580                pb.partial_cmp(&pa).unwrap_or(std::cmp::Ordering::Equal)
581            });
582            self.entries.truncate(Self::MAX_LEDGER_ENTRIES);
583        }
584
585        self.rebuild_totals();
586        before - self.entries.len()
587    }
588
589    fn rebuild_totals(&mut self) {
590        self.total_tokens_sent = self.entries.iter().map(|e| e.sent_tokens).sum();
591        self.total_tokens_saved = self
592            .entries
593            .iter()
594            .map(|e| e.original_tokens.saturating_sub(e.sent_tokens))
595            .sum();
596    }
597
598    pub fn load() -> Self {
599        Self::load_for_agent("default")
600    }
601
602    pub fn load_for_agent(agent_id: &str) -> Self {
603        let mut ledger: Self = ledger_path(agent_id)
604            .ok()
605            .and_then(|p| {
606                let _lock = acquire_ledger_lock(&p);
607                std::fs::read_to_string(p).ok()
608            })
609            .and_then(|s| serde_json::from_str(&s).ok())
610            .unwrap_or_default();
611        if let Some((_model, window)) = crate::hook_handlers::load_detected_model() {
612            ledger.window_size = window;
613        }
614        // #715 migration: older Windows builds persisted `\`-separated paths;
615        // resolution and dedup assume the forward-slash canonical form.
616        // Lexical only — no FS access on persisted paths (TCC, #356).
617        let mut migrated = false;
618        for entry in &mut ledger.entries {
619            let normalized = crate::core::pathutil::normalize_tool_path_lexical(&entry.path);
620            if normalized != entry.path {
621                entry.path = normalized;
622                migrated = true;
623            }
624        }
625        let pruned = ledger.prune();
626        if pruned > 0 || migrated {
627            ledger.save_for_agent(agent_id);
628        }
629        ledger
630    }
631
632    pub fn format_summary(&self) -> String {
633        let pressure = self.pressure();
634        format!(
635            "CTX: {}/{} tokens ({:.0}%), {} files, ratio {:.2}, action: {:?}",
636            self.total_tokens_sent,
637            self.window_size,
638            pressure.utilization * 100.0,
639            self.entries.len(),
640            self.compression_ratio(),
641            pressure.recommendation,
642        )
643    }
644
645    pub fn adjusted_total_saved(&self) -> isize {
646        match crate::core::bounce_tracker::global().lock() {
647            Ok(bt) => bt.adjusted_savings(self.total_tokens_saved),
648            _ => self.total_tokens_saved as isize,
649        }
650    }
651}