Skip to main content

lean_ctx/cli/
ledger_cmd.rs

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