Skip to main content

lean_ctx_cli/cli/
ledger_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::path::{Path, PathBuf};
3use std::time::Instant;
4
5use lean_ctx::core::cache::SessionCache;
6use lean_ctx::core::context_ledger::ContextLedger;
7use lean_ctx::core::tokens::count_tokens;
8use lean_ctx_server::tools::{CrpMode, ctx_read};
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11struct PushOptions {
12    target: String,
13    depth: Option<usize>,
14    ignore: Vec<String>,
15}
16
17#[derive(Debug, Default, PartialEq, Eq)]
18struct PushSummary {
19    pushed: usize,
20    skipped: usize,
21    original_tokens: usize,
22    sent_tokens: usize,
23}
24
25impl PushSummary {
26    fn saved_tokens(&self) -> usize {
27        self.original_tokens.saturating_sub(self.sent_tokens)
28    }
29}
30
31fn parse_push_args(args: &[String]) -> Result<PushOptions, String> {
32    let mut target = None;
33    let mut depth = None;
34    let mut ignore = Vec::new();
35    let mut i = 0;
36
37    while i < args.len() {
38        let arg = &args[i];
39        if arg == "--depth" {
40            i += 1;
41            let value = args
42                .get(i)
43                .ok_or_else(|| "--depth requires a non-negative integer".to_string())?;
44            depth = Some(
45                value
46                    .parse::<usize>()
47                    .map_err(|_| format!("invalid depth '{value}'"))?,
48            );
49        } else if let Some(value) = arg.strip_prefix("--depth=") {
50            depth = Some(
51                value
52                    .parse::<usize>()
53                    .map_err(|_| format!("invalid depth '{value}'"))?,
54            );
55        } else if arg == "--ignore" {
56            i += 1;
57            let value = args
58                .get(i)
59                .ok_or_else(|| "--ignore requires a glob pattern".to_string())?;
60            if value.is_empty() {
61                return Err("--ignore requires a non-empty glob pattern".to_string());
62            }
63            ignore.push(value.clone());
64        } else if let Some(value) = arg.strip_prefix("--ignore=") {
65            if value.is_empty() {
66                return Err("--ignore requires a non-empty glob pattern".to_string());
67            }
68            ignore.push(value.to_string());
69        } else if arg.starts_with('-') {
70            return Err(format!("unknown ledger push flag '{arg}'"));
71        } else if target.replace(arg.clone()).is_some() {
72            return Err("ledger push accepts one file or directory path".to_string());
73        }
74        i += 1;
75    }
76
77    Ok(PushOptions {
78        target: target
79            .ok_or_else(|| "ledger push requires a file or directory path".to_string())?,
80        depth,
81        ignore,
82    })
83}
84
85fn resolve_push_path(raw: &str) -> PathBuf {
86    let path = Path::new(raw);
87    let path = if path.is_absolute() {
88        path.to_path_buf()
89    } else {
90        std::env::current_dir().map_or_else(|_| path.to_path_buf(), |cwd| cwd.join(path))
91    };
92    std::fs::canonicalize(&path).unwrap_or(path)
93}
94
95fn ignore_matches(pattern: &glob::Pattern, relative: &str) -> bool {
96    let relative = relative.trim_matches('/');
97    if pattern.matches(relative) {
98        return true;
99    }
100
101    let pattern_text = pattern.as_str().trim_matches('/');
102    if let Some(prefix) = pattern_text.strip_suffix("/**")
103        && (relative == prefix || relative.starts_with(&format!("{prefix}/")))
104    {
105        return true;
106    }
107
108    !pattern_text.contains('/')
109        && relative
110            .split('/')
111            .any(|component| pattern.matches(component))
112}
113
114fn collect_push_files(
115    root: &Path,
116    depth: Option<usize>,
117    ignore_patterns: &[String],
118) -> Result<Vec<PathBuf>, String> {
119    if !root.exists() {
120        return Err(format!("{} does not exist", root.display()));
121    }
122    if root.is_file() {
123        return Ok(vec![root.to_path_buf()]);
124    }
125    if !root.is_dir() {
126        return Err(format!(
127            "{} is not a regular file or directory",
128            root.display()
129        ));
130    }
131
132    let root_string = root.to_string_lossy().into_owned();
133    if let Some(error) = lean_ctx_server::tools::walk_guard::deny_unsafe_walk_root(&root_string) {
134        return Err(error);
135    }
136
137    let patterns: Vec<glob::Pattern> = ignore_patterns
138        .iter()
139        .filter_map(|pattern| glob::Pattern::new(pattern).ok())
140        .collect();
141    let walk_root = lean_ctx::core::walk_filter::explicit_walk_root(root);
142    let filter_root = walk_root.clone();
143    let walker = ignore::WalkBuilder::new(&walk_root)
144        .hidden(true)
145        .git_ignore(true)
146        .git_global(true)
147        .git_exclude(true)
148        .require_git(false)
149        .max_depth(depth)
150        .filter_entry(move |entry| {
151            if !lean_ctx::core::walk_filter::keep_entry(entry) || entry.depth() == 0 {
152                return entry.depth() == 0;
153            }
154            let relative = entry
155                .path()
156                .strip_prefix(&filter_root)
157                .unwrap_or(entry.path())
158                .to_string_lossy()
159                .replace('\\', "/");
160            !patterns
161                .iter()
162                .any(|pattern| ignore_matches(pattern, &relative))
163        })
164        .sort_by_file_path(Path::cmp)
165        .build();
166
167    let mut files = walker
168        .filter_map(Result::ok)
169        .filter(|entry| entry.file_type().is_some_and(|kind| kind.is_file()))
170        .filter(|entry| !entry.path_is_symlink())
171        .map(ignore::DirEntry::into_path)
172        .collect::<Vec<_>>();
173    files.sort();
174    Ok(files)
175}
176
177/// The source a local push hands to the read pipeline. A push seeds the
178/// one-shot cache and persists a read record with an excerpt, so it takes the
179/// ADMITTED text (G01) and only of a source whose original may be kept in a
180/// derived store. The unscoped reader used here before is a raw local read
181/// outside a request scope. `Err` is a content-free reason.
182fn admitted_push_source(path: &str) -> Result<String, String> {
183    let source = ctx_read::read_file_lossy_admitted_for_cli(path).map_err(|e| e.to_string())?;
184    if !source.storable {
185        return Err(lean_ctx::core::context_admission::carrier::Withheld::new(&[
186            "store.restricted_content",
187        ])
188        .message("source content"));
189    }
190    Ok(source.text)
191}
192
193fn push_files_locally(files: &[PathBuf]) -> PushSummary {
194    let mut cache = SessionCache::new();
195    let mut summary = PushSummary::default();
196
197    for path in files {
198        let path_string = path.to_string_lossy().into_owned();
199        let raw = match admitted_push_source(&path_string) {
200            Ok(content) => content,
201            Err(error) => {
202                eprintln!("Skipping {path_string}: {error}");
203                summary.skipped += 1;
204                continue;
205            }
206        };
207        let original_tokens = count_tokens(&raw);
208        let started = Instant::now();
209        let output = ctx_read::handle_with_preread(
210            &mut cache,
211            &path_string,
212            "auto",
213            true,
214            CrpMode::effective(),
215            None,
216            None,
217            &[],
218            raw,
219        );
220        let sent_tokens = count_tokens(&output.content);
221        lean_ctx::core::tool_lifecycle::record_file_read(
222            &path_string,
223            &output.resolved_mode,
224            original_tokens,
225            sent_tokens,
226            output.is_cache_hit,
227            started.elapsed(),
228            &output.content,
229        );
230        summary.pushed += 1;
231        summary.original_tokens = summary.original_tokens.saturating_add(original_tokens);
232        summary.sent_tokens = summary.sent_tokens.saturating_add(sent_tokens);
233    }
234
235    lean_ctx::core::tool_lifecycle::flush_all();
236    summary
237}
238
239#[cfg(unix)]
240fn push_files_via_daemon(files: &[PathBuf]) -> Option<PushSummary> {
241    let first = files.first()?;
242    let read = |path: &Path| {
243        lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
244            "ctx_read",
245            Some(serde_json::json!({
246                "path": path.to_string_lossy(),
247                "mode": "auto",
248                "fresh": true,
249            })),
250        )
251    };
252    let first_output = read(first)?;
253    let mut summary = PushSummary::default();
254    for output in std::iter::once(first_output).chain(files[1..].iter().filter_map(|p| read(p))) {
255        if output.trim_start().starts_with("ERROR:") {
256            summary.skipped += 1;
257        } else {
258            summary.pushed += 1;
259        }
260    }
261    Some(summary)
262}
263
264#[cfg(not(unix))]
265fn push_files_via_daemon(_files: &[PathBuf]) -> Option<PushSummary> {
266    None
267}
268
269fn cmd_push(args: &[String]) {
270    let options = match parse_push_args(args) {
271        Ok(options) => options,
272        Err(error) => {
273            eprintln!("Error: {error}");
274            eprintln!("Usage: lean-ctx ledger push <path> [--depth N] [--ignore PATTERN]");
275            std::process::exit(1);
276        }
277    };
278    let root = resolve_push_path(&options.target);
279    let mut ignore_patterns = lean_ctx::core::config::Config::load().extra_ignore_patterns;
280    ignore_patterns.extend(options.ignore);
281    let files = match collect_push_files(&root, options.depth, &ignore_patterns) {
282        Ok(files) => files,
283        Err(error) => {
284            eprintln!("Error: {error}");
285            std::process::exit(1);
286        }
287    };
288    if files.is_empty() {
289        eprintln!("No files found under {}", root.display());
290        return;
291    }
292
293    let summary = push_files_via_daemon(&files).unwrap_or_else(|| push_files_locally(&files));
294    println!(
295        "Pushed {} file(s), skipped {}. Tokens: {} → {} ({} saved).",
296        summary.pushed,
297        summary.skipped,
298        summary.original_tokens,
299        summary.sent_tokens,
300        summary.saved_tokens(),
301    );
302}
303
304pub fn cmd_ledger(args: &[String]) {
305    let action = args.first().map_or("status", String::as_str);
306
307    // The MCP tool `ctx_ledger` was retired in 3.12.0, so the daemon cannot
308    // serve these actions; they work on the persisted ledger directly.
309    match action {
310        // Local Read v1: the savings ledger's chain verdict (`ledger.verify`).
311        "verify" if super::local_read::wants_json(args) => {
312            super::local_read::kinds::run("ledger.verify", args);
313        }
314        "push" => cmd_push(&args[1..]),
315        "status" => {
316            let ledger = ContextLedger::load();
317            let pressure = ledger.pressure();
318            println!(
319                "Context pressure: {:.0}% ({}/{} tokens)",
320                pressure.utilization * 100.0,
321                ledger.total_tokens_sent,
322                ledger.window_size,
323            );
324            println!("Entries: {}", ledger.entries.len());
325            println!("Recommendation: {:?}", pressure.recommendation);
326            let top = ledger.files_by_token_cost();
327            if !top.is_empty() {
328                println!("Top files by cost:");
329                for (path, tokens) in top.iter().take(5) {
330                    println!("  {path} ({tokens} tok)");
331                }
332            }
333        }
334
335        "reset" => {
336            let mut ledger = ContextLedger::load();
337            let prev_entries = ledger.entries.len();
338            let prev_tokens = ledger.total_tokens_sent;
339            ledger.reset();
340            ledger.save();
341            println!(
342                "Ledger reset. Removed {prev_entries} entries, freed {prev_tokens} tracked tokens. Pressure: 0%."
343            );
344        }
345
346        "evict" => {
347            let targets: Vec<&str> = args[1..].iter().map(String::as_str).collect();
348            if targets.is_empty() {
349                eprintln!("Usage: lean-ctx ledger evict <file1> [file2...]");
350                std::process::exit(1);
351            }
352
353            let mut ledger = ContextLedger::load();
354            // #715: resolve partial paths/basenames and report each outcome.
355            let root = std::env::current_dir()
356                .ok()
357                .map(|d| d.to_string_lossy().into_owned());
358            let outcomes = ledger.evict_paths_resolved(&targets, root.as_deref());
359            let removed = outcomes.iter().filter(|o| o.resolved.is_some()).count();
360            ledger.save();
361            let pressure = ledger.pressure();
362            println!(
363                "Evicted {removed}/{} target(s). Pressure now: {:.0}%.",
364                targets.len(),
365                pressure.utilization * 100.0,
366            );
367            for outcome in &outcomes {
368                match (&outcome.resolved, outcome.ambiguous.is_empty()) {
369                    (Some(resolved), _) if resolved != &outcome.target => {
370                        println!("  {} → {resolved}", outcome.target);
371                    }
372                    (Some(_), _) => {}
373                    (None, false) => println!(
374                        "  {} is ambiguous ({}) — use a longer suffix",
375                        outcome.target,
376                        outcome.ambiguous.join(", ")
377                    ),
378                    (None, true) => println!("  {} not in ledger", outcome.target),
379                }
380            }
381        }
382
383        "prune" => {
384            let mut ledger = ContextLedger::load();
385            let pruned = ledger.prune();
386            ledger.save();
387            let pressure = ledger.pressure();
388            println!(
389                "Pruned {pruned} entries. Remaining: {}. Pressure: {:.0}%.",
390                ledger.entries.len(),
391                pressure.utilization * 100.0,
392            );
393        }
394
395        _ => {
396            eprintln!("Usage: lean-ctx ledger <status|reset|evict|prune|push> [args...]");
397            std::process::exit(1);
398        }
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::{
405        PushOptions, admitted_push_source, collect_push_files, ignore_matches, parse_push_args,
406    };
407
408    fn args(values: &[&str]) -> Vec<String> {
409        values.iter().map(ToString::to_string).collect()
410    }
411
412    #[test]
413    fn parses_push_path_depth_and_repeatable_ignores() {
414        assert_eq!(
415            parse_push_args(&args(&[
416                "src",
417                "--depth",
418                "2",
419                "--ignore",
420                "*.generated",
421                "--ignore=vendor/**"
422            ])),
423            Ok(PushOptions {
424                target: "src".to_string(),
425                depth: Some(2),
426                ignore: vec!["*.generated".to_string(), "vendor/**".to_string()],
427            })
428        );
429    }
430
431    /// G01: a local push read each file with the unscoped reader — raw
432    /// outside a request scope — and persisted a read record with an excerpt
433    /// of it. It now takes the admitted text, and a restricted source is
434    /// skipped with a content-free reason.
435    #[test]
436    fn a_local_push_takes_admitted_storable_sources_only() {
437        const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
438        let _data = lean_ctx::core::data_dir::isolated_data_dir();
439        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
440        let dir = tempfile::tempdir().unwrap();
441        let file = |name: &str, content: &str| {
442            let path = dir.path().join(name);
443            std::fs::write(&path, content).unwrap();
444            path.to_string_lossy().into_owned()
445        };
446        let clean = file("clean.rs", "pub fn clean() {}\n");
447        let keyed = file("keyed.rs", &format!("let aws_key = \"{AWS_KEY}\";\n"));
448        let marked = file("marked.rs", "// TOP SECRET\npub fn plan_marker() {}\n");
449
450        assert_eq!(admitted_push_source(&clean).unwrap(), "pub fn clean() {}\n");
451        assert!(!admitted_push_source(&keyed).unwrap().contains(AWS_KEY));
452        let reason = admitted_push_source(&marked).expect_err("restricted source is skipped");
453        assert!(reason.contains("store.restricted_content"), "{reason}");
454        assert!(!reason.contains("plan_marker"), "{reason}");
455    }
456
457    #[test]
458    fn rejects_missing_path_and_invalid_flags() {
459        assert!(parse_push_args(&[]).is_err());
460        assert!(parse_push_args(&args(&["src", "--depth", "nope"])).is_err());
461        assert!(parse_push_args(&args(&["src", "--unknown"])).is_err());
462    }
463
464    #[test]
465    fn collects_gitignored_and_depth_limited_files() {
466        let root = tempfile::tempdir().expect("tempdir");
467        std::fs::create_dir_all(root.path().join("nested/deeper")).expect("mkdir");
468        std::fs::write(root.path().join(".gitignore"), "ignored.rs\n").expect("gitignore");
469        std::fs::write(root.path().join("kept.rs"), "fn kept() {}\n").expect("write");
470        std::fs::write(root.path().join("ignored.rs"), "fn ignored() {}\n").expect("write");
471        std::fs::write(root.path().join("nested/visible.rs"), "fn visible() {}\n").expect("write");
472        std::fs::write(
473            root.path().join("nested/deeper/hidden.rs"),
474            "fn hidden() {}\n",
475        )
476        .expect("write");
477
478        let files = collect_push_files(root.path(), Some(2), &[]).expect("collect");
479        let names: Vec<_> = files
480            .iter()
481            .filter_map(|path| path.file_name().and_then(|name| name.to_str()))
482            .collect();
483        assert_eq!(names, vec!["kept.rs", "visible.rs"]);
484    }
485
486    #[test]
487    fn ignore_patterns_match_components_and_recursive_directories() {
488        let component = glob::Pattern::new("*.generated").expect("pattern");
489        let recursive = glob::Pattern::new("vendor/**").expect("pattern");
490        assert!(ignore_matches(&component, "src/model.generated"));
491        assert!(ignore_matches(&recursive, "vendor/pkg/lib.rs"));
492        assert!(!ignore_matches(&recursive, "src/vendor.rs"));
493    }
494}