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        "push" => cmd_push(&args[1..]),
311        "status" => {
312            let ledger = ContextLedger::load();
313            let pressure = ledger.pressure();
314            println!(
315                "Context pressure: {:.0}% ({}/{} tokens)",
316                pressure.utilization * 100.0,
317                ledger.total_tokens_sent,
318                ledger.window_size,
319            );
320            println!("Entries: {}", ledger.entries.len());
321            println!("Recommendation: {:?}", pressure.recommendation);
322            let top = ledger.files_by_token_cost();
323            if !top.is_empty() {
324                println!("Top files by cost:");
325                for (path, tokens) in top.iter().take(5) {
326                    println!("  {path} ({tokens} tok)");
327                }
328            }
329        }
330
331        "reset" => {
332            let mut ledger = ContextLedger::load();
333            let prev_entries = ledger.entries.len();
334            let prev_tokens = ledger.total_tokens_sent;
335            ledger.reset();
336            ledger.save();
337            println!(
338                "Ledger reset. Removed {prev_entries} entries, freed {prev_tokens} tracked tokens. Pressure: 0%."
339            );
340        }
341
342        "evict" => {
343            let targets: Vec<&str> = args[1..].iter().map(String::as_str).collect();
344            if targets.is_empty() {
345                eprintln!("Usage: lean-ctx ledger evict <file1> [file2...]");
346                std::process::exit(1);
347            }
348
349            let mut ledger = ContextLedger::load();
350            // #715: resolve partial paths/basenames and report each outcome.
351            let root = std::env::current_dir()
352                .ok()
353                .map(|d| d.to_string_lossy().into_owned());
354            let outcomes = ledger.evict_paths_resolved(&targets, root.as_deref());
355            let removed = outcomes.iter().filter(|o| o.resolved.is_some()).count();
356            ledger.save();
357            let pressure = ledger.pressure();
358            println!(
359                "Evicted {removed}/{} target(s). Pressure now: {:.0}%.",
360                targets.len(),
361                pressure.utilization * 100.0,
362            );
363            for outcome in &outcomes {
364                match (&outcome.resolved, outcome.ambiguous.is_empty()) {
365                    (Some(resolved), _) if resolved != &outcome.target => {
366                        println!("  {} → {resolved}", outcome.target);
367                    }
368                    (Some(_), _) => {}
369                    (None, false) => println!(
370                        "  {} is ambiguous ({}) — use a longer suffix",
371                        outcome.target,
372                        outcome.ambiguous.join(", ")
373                    ),
374                    (None, true) => println!("  {} not in ledger", outcome.target),
375                }
376            }
377        }
378
379        "prune" => {
380            let mut ledger = ContextLedger::load();
381            let pruned = ledger.prune();
382            ledger.save();
383            let pressure = ledger.pressure();
384            println!(
385                "Pruned {pruned} entries. Remaining: {}. Pressure: {:.0}%.",
386                ledger.entries.len(),
387                pressure.utilization * 100.0,
388            );
389        }
390
391        _ => {
392            eprintln!("Usage: lean-ctx ledger <status|reset|evict|prune|push> [args...]");
393            std::process::exit(1);
394        }
395    }
396}
397
398#[cfg(test)]
399mod tests {
400    use super::{
401        PushOptions, admitted_push_source, collect_push_files, ignore_matches, parse_push_args,
402    };
403
404    fn args(values: &[&str]) -> Vec<String> {
405        values.iter().map(ToString::to_string).collect()
406    }
407
408    #[test]
409    fn parses_push_path_depth_and_repeatable_ignores() {
410        assert_eq!(
411            parse_push_args(&args(&[
412                "src",
413                "--depth",
414                "2",
415                "--ignore",
416                "*.generated",
417                "--ignore=vendor/**"
418            ])),
419            Ok(PushOptions {
420                target: "src".to_string(),
421                depth: Some(2),
422                ignore: vec!["*.generated".to_string(), "vendor/**".to_string()],
423            })
424        );
425    }
426
427    /// G01: a local push read each file with the unscoped reader — raw
428    /// outside a request scope — and persisted a read record with an excerpt
429    /// of it. It now takes the admitted text, and a restricted source is
430    /// skipped with a content-free reason.
431    #[test]
432    fn a_local_push_takes_admitted_storable_sources_only() {
433        const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
434        let _data = lean_ctx::core::data_dir::isolated_data_dir();
435        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
436        let dir = tempfile::tempdir().unwrap();
437        let file = |name: &str, content: &str| {
438            let path = dir.path().join(name);
439            std::fs::write(&path, content).unwrap();
440            path.to_string_lossy().into_owned()
441        };
442        let clean = file("clean.rs", "pub fn clean() {}\n");
443        let keyed = file("keyed.rs", &format!("let aws_key = \"{AWS_KEY}\";\n"));
444        let marked = file("marked.rs", "// TOP SECRET\npub fn plan_marker() {}\n");
445
446        assert_eq!(admitted_push_source(&clean).unwrap(), "pub fn clean() {}\n");
447        assert!(!admitted_push_source(&keyed).unwrap().contains(AWS_KEY));
448        let reason = admitted_push_source(&marked).expect_err("restricted source is skipped");
449        assert!(reason.contains("store.restricted_content"), "{reason}");
450        assert!(!reason.contains("plan_marker"), "{reason}");
451    }
452
453    #[test]
454    fn rejects_missing_path_and_invalid_flags() {
455        assert!(parse_push_args(&[]).is_err());
456        assert!(parse_push_args(&args(&["src", "--depth", "nope"])).is_err());
457        assert!(parse_push_args(&args(&["src", "--unknown"])).is_err());
458    }
459
460    #[test]
461    fn collects_gitignored_and_depth_limited_files() {
462        let root = tempfile::tempdir().expect("tempdir");
463        std::fs::create_dir_all(root.path().join("nested/deeper")).expect("mkdir");
464        std::fs::write(root.path().join(".gitignore"), "ignored.rs\n").expect("gitignore");
465        std::fs::write(root.path().join("kept.rs"), "fn kept() {}\n").expect("write");
466        std::fs::write(root.path().join("ignored.rs"), "fn ignored() {}\n").expect("write");
467        std::fs::write(root.path().join("nested/visible.rs"), "fn visible() {}\n").expect("write");
468        std::fs::write(
469            root.path().join("nested/deeper/hidden.rs"),
470            "fn hidden() {}\n",
471        )
472        .expect("write");
473
474        let files = collect_push_files(root.path(), Some(2), &[]).expect("collect");
475        let names: Vec<_> = files
476            .iter()
477            .filter_map(|path| path.file_name().and_then(|name| name.to_str()))
478            .collect();
479        assert_eq!(names, vec!["kept.rs", "visible.rs"]);
480    }
481
482    #[test]
483    fn ignore_patterns_match_components_and_recursive_directories() {
484        let component = glob::Pattern::new("*.generated").expect("pattern");
485        let recursive = glob::Pattern::new("vendor/**").expect("pattern");
486        assert!(ignore_matches(&component, "src/model.generated"));
487        assert!(ignore_matches(&recursive, "vendor/pkg/lib.rs"));
488        assert!(!ignore_matches(&recursive, "src/vendor.rs"));
489    }
490}