Skip to main content

lean_ctx/tools/registered/
ctx_checkpoint.rs

1use std::path::Path;
2
3use rmcp::ErrorData;
4use rmcp::model::Tool;
5use serde_json::{Map, Value, json};
6
7use crate::core::git::shadow::{self, Checkpoint};
8use crate::core::tokens::count_tokens;
9use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_int, get_str};
10use crate::tool_defs::tool_def;
11
12const DEFAULT_LOG_LIMIT: usize = 20;
13const DIFF_MAX_TOKENS: usize = 8000;
14
15/// `ctx_checkpoint` — snapshot, review, diff, and revert the agent's code
16/// changes in a shadow git history kept outside the user's own `.git`.
17pub struct CtxCheckpointTool;
18
19impl McpTool for CtxCheckpointTool {
20    fn name(&self) -> &'static str {
21        "ctx_checkpoint"
22    }
23
24    fn tool_def(&self) -> Tool {
25        tool_def(
26            "ctx_checkpoint",
27            "Local shadow git history of the agent's changes — separate from the user's .git.\n\
28WORKFLOW: snapshot before+after changes to capture exactly what was modified.\n\
29Actions: snapshot (record current state), log (list checkpoints with SHAs),\n\
30diff from=... to=... (compare checkpoints), restore ref=... (revert files).\n\
31ANTIPATTERN: Never touches the user's repository — completely isolated shadow history.",
32            json!({
33                "type": "object",
34                "properties": {
35                    "action": {
36                        "type": "string",
37                        "enum": ["snapshot", "log", "diff", "restore"],
38                        "description": "snapshot|log|diff|restore (default: log)"
39                    },
40                    "message": { "type": "string", "description": "Label for the snapshot (action=snapshot only)" },
41                    "from": { "type": "string", "description": "Base checkpoint SHA for diff (default: HEAD~1, action=diff only)" },
42                    "to": { "type": "string", "description": "Target checkpoint SHA for diff (default: HEAD, action=diff only)" },
43                    "ref": { "type": "string", "description": "Checkpoint SHA to restore (required for action=restore)" },
44                    "path": { "type": "string", "description": "File/dir to restore (omit for full restore, action=restore only)" },
45                    "limit": { "type": "integer", "description": "Max checkpoints in log (default: 20, max: 200)" }
46                },
47                "allOf": [
48                    {
49                        "if": { "properties": { "action": { "const": "restore" } }, "required": ["action"] },
50                        "then": { "required": ["action", "ref"] }
51                    }
52                ]
53            }),
54        )
55    }
56
57    fn handle(
58        &self,
59        args: &Map<String, Value>,
60        ctx: &ToolContext,
61    ) -> Result<ToolOutput, ErrorData> {
62        let action = get_str(args, "action").unwrap_or_else(|| "log".to_string());
63        let project = Path::new(&ctx.project_root).to_path_buf();
64        if ctx.project_root.is_empty() {
65            return Err(ErrorData::invalid_params(
66                "no project root resolved for ctx_checkpoint",
67                None,
68            ));
69        }
70
71        let result = tokio::task::block_in_place(|| match action.as_str() {
72            "snapshot" => {
73                let msg = get_str(args, "message").unwrap_or_default();
74                shadow::snapshot(&project, &msg).map(|c| render_checkpoint_line("Checkpoint", &c))
75            }
76            "log" => {
77                let limit =
78                    get_int(args, "limit").map_or(DEFAULT_LOG_LIMIT, |n| n.clamp(1, 200) as usize);
79                shadow::log(&project, limit).map(|cs| render_log(&cs))
80            }
81            "diff" => {
82                let from = get_str(args, "from");
83                let to = get_str(args, "to");
84                shadow::diff(&project, from.as_deref(), to.as_deref())
85                    .and_then(|d| admitted_diff(&d))
86                    .inspect(|_| {
87                        crate::core::context_admission::capture::note_source_id(&format!(
88                            "checkpoint-diff:{}..{}",
89                            from.as_deref().unwrap_or(""),
90                            to.as_deref().unwrap_or("")
91                        ));
92                    })
93                    .map(|d| budget(&d, DIFF_MAX_TOKENS))
94            }
95            "restore" => {
96                let git_ref = get_str(args, "ref").ok_or_else(|| {
97                    "restore requires 'ref' (a checkpoint sha from log)".to_string()
98                })?;
99                let path = get_str(args, "path")
100                    .map(|raw| {
101                        crate::core::workspace_authority::confine(&raw, &ctx.project_root, true)
102                    })
103                    .transpose()?;
104                shadow::restore(&project, &git_ref, path.as_deref())
105            }
106            other => Err(format!(
107                "invalid action '{other}' (use: snapshot, log, diff, restore)"
108            )),
109        });
110
111        match result {
112            Ok(text) => Ok(ToolOutput {
113                text,
114                original_tokens: 0,
115                saved_tokens: 0,
116                mode: Some(action),
117                path: None,
118                changed: matches!(
119                    args.get("action").and_then(Value::as_str),
120                    Some("snapshot" | "restore")
121                ),
122                shell_outcome: None,
123                content_blocks: None,
124            }),
125            Err(e) => Err(ErrorData::invalid_params(
126                format!("ctx_checkpoint failed: {e}"),
127                None,
128            )),
129        }
130    }
131}
132
133/// A checkpoint diff is content of project files taken from git objects, not
134/// from a rooted file read: it is admitted as a context source — project
135/// policy on the text, then the gateway — BEFORE it is cut to the token
136/// budget (G01). A diff that is withheld yields the content-free reason as
137/// the tool's error. Limit: a diff is an excerpt; a marking that sits in an
138/// unchanged part of a file does not travel with its hunks.
139fn admitted_diff(diff: &str) -> Result<String, String> {
140    if diff.trim().is_empty() {
141        return Ok(diff.to_string());
142    }
143    crate::tools::admitted_sources::admit_remote_text(diff, "ctx_checkpoint")
144        .map(|admission| admission.text)
145}
146
147fn render_checkpoint_line(prefix: &str, c: &Checkpoint) -> String {
148    let files = c
149        .files_changed
150        .map(|n| format!(" · {n} file(s)"))
151        .unwrap_or_default();
152    format!("{prefix} {}{files} — {}", c.sha, c.message)
153}
154
155fn render_log(checkpoints: &[Checkpoint]) -> String {
156    if checkpoints.is_empty() {
157        return "No checkpoints yet. Run `ctx_checkpoint` with action=snapshot to record one."
158            .to_string();
159    }
160    let mut out = format!("{} checkpoint(s):\n", checkpoints.len());
161    for c in checkpoints {
162        out.push_str(&format!("- {} · {} — {}\n", c.sha, c.time, c.message));
163    }
164    out.trim_end().to_string()
165}
166
167fn budget(content: &str, max_tokens: usize) -> String {
168    if content.trim().is_empty() {
169        return "No differences.".to_string();
170    }
171    let tokens = count_tokens(content);
172    if tokens <= max_tokens {
173        return content.to_string();
174    }
175    let ratio = max_tokens as f64 / tokens as f64;
176    let keep = ((content.chars().count() as f64 * ratio) as usize).max(1);
177    let truncated: String = content.chars().take(keep).collect();
178    crate::core::recovery::with_original_pointer(
179        "ctx_checkpoint",
180        "diff",
181        content,
182        format!("{truncated}\n\n…[diff truncated to ~{max_tokens} tokens]"),
183    )
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    fn cp(sha: &str, msg: &str, files: Option<usize>) -> Checkpoint {
191        Checkpoint {
192            sha: sha.to_string(),
193            time: "2026-06-07T10:00:00Z".to_string(),
194            message: msg.to_string(),
195            files_changed: files,
196        }
197    }
198
199    #[test]
200    fn renders_empty_log_with_hint() {
201        assert!(render_log(&[]).contains("snapshot"));
202    }
203
204    #[test]
205    fn renders_checkpoint_line_with_file_count() {
206        let line = render_checkpoint_line("Checkpoint", &cp("abc1234", "fix bug", Some(3)));
207        assert_eq!(line, "Checkpoint abc1234 · 3 file(s) — fix bug");
208    }
209
210    #[test]
211    fn renders_log_entries() {
212        let out = render_log(&[cp("a1", "one", None), cp("b2", "two", None)]);
213        assert!(out.contains("2 checkpoint(s)"));
214        assert!(out.contains("- a1 ·"));
215        assert!(out.contains("- b2 ·"));
216    }
217
218    #[test]
219    fn budget_handles_empty_diff() {
220        assert_eq!(budget("", 100), "No differences.");
221    }
222
223    /// G01: a checkpoint diff was returned as git printed it — a key in a
224    /// changed line reached the model, and a diff the project policy blocks
225    /// was delivered. A clean diff keeps its bytes.
226    #[test]
227    fn a_diff_is_admitted_before_it_is_budgeted() {
228        const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
229        let _data = crate::core::data_dir::isolated_data_dir();
230        let clean = "--- a/src/a.rs\n+++ b/src/a.rs\n@@ -1 +1 @@\n-fn a() {}\n+fn b() {}\n";
231        {
232            let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
233            assert_eq!(admitted_diff(clean).as_deref(), Ok(clean));
234            assert_eq!(admitted_diff("").as_deref(), Ok(""));
235            let keyed = format!("@@ -1 +1 @@\n+let aws_key = \"{AWS_KEY}\";\n");
236            assert!(admitted_diff(&keyed).is_ok_and(|diff| !diff.contains(AWS_KEY)));
237        }
238        let policy = crate::core::policy::load(
239            "name = \"ctx-checkpoint-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
240             [redaction]\ncustomer = \"CUS-[0-9]{4}\"\n",
241        )
242        .unwrap();
243        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(policy));
244        let masked = admitted_diff("@@ -1 +1 @@\n+let owner = \"CUS-1234\";\n").unwrap();
245        assert!(!masked.contains("CUS-1234"), "{masked}");
246    }
247}