1use std::path::{Path, PathBuf};
11use std::time::Duration;
12
13use super::{GitOutput, run_git};
14
15const FIELD: char = '\u{1f}'; #[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Checkpoint {
20 pub sha: String,
21 pub time: String,
23 pub message: String,
24 pub files_changed: Option<usize>,
26}
27
28pub(crate) fn init(project: &Path) -> Result<(), String> {
30 let git_dir = shadow_git_dir(project)?;
31 if git_dir.join("HEAD").exists() {
32 return Ok(());
33 }
34 std::fs::create_dir_all(&git_dir).map_err(|e| format!("cannot create shadow dir: {e}"))?;
35
36 let env = base_env(&git_dir, project);
37 git(&["init", "-q"], project, Duration::from_secs(15), &env)?.ok_stdout()?;
38
39 let excludes = write_excludes(&git_dir)?;
42 let exc = excludes.to_string_lossy();
43 for (k, v) in [
44 ("core.excludesFile", exc.as_ref()),
45 ("commit.gpgsign", "false"),
46 ("gc.auto", "0"),
47 ("core.autocrlf", "false"),
51 ("core.safecrlf", "false"),
52 ] {
53 git(&["config", k, v], project, Duration::from_secs(10), &env)?.ok_stdout()?;
54 }
55 Ok(())
56}
57
58pub fn snapshot(project: &Path, message: &str) -> Result<Checkpoint, String> {
61 init(project)?;
62 let git_dir = shadow_git_dir(project)?;
63 let env = base_env(&git_dir, project);
64
65 git(&["add", "-A"], project, Duration::from_mins(2), &env)?.ok_stdout()?;
66
67 let msg = if message.trim().is_empty() {
68 "lean-ctx checkpoint"
69 } else {
70 message
71 };
72 let commit = git(
73 &["commit", "--no-verify", "-q", "-m", msg],
74 project,
75 Duration::from_mins(1),
76 &env,
77 )?;
78
79 if commit.success {
80 let sha = head_sha(project, &env)?;
81 let files = count_changed(project, &env, &sha);
82 return Ok(Checkpoint {
83 sha,
84 time: now_iso(project, &env),
85 message: msg.to_string(),
86 files_changed: Some(files),
87 });
88 }
89
90 if let Ok(sha) = head_sha(project, &env) {
92 return Ok(Checkpoint {
93 sha,
94 time: now_iso(project, &env),
95 message: "(no changes since last checkpoint)".to_string(),
96 files_changed: Some(0),
97 });
98 }
99 commit.ok_stdout()?;
100 Err("git commit failed".to_string())
101}
102
103pub fn log(project: &Path, limit: usize) -> Result<Vec<Checkpoint>, String> {
105 let git_dir = shadow_git_dir(project)?;
106 if !git_dir.join("HEAD").exists() {
107 return Ok(Vec::new());
108 }
109 let env = base_env(&git_dir, project);
110 let fmt = format!("--pretty=format:%H{FIELD}%cI{FIELD}%s");
111 let out = git(
112 &["log", &fmt, &format!("--max-count={}", limit.max(1))],
113 project,
114 Duration::from_secs(15),
115 &env,
116 )?;
117 if !out.success {
118 return Ok(Vec::new()); }
120 Ok(out
121 .stdout
122 .lines()
123 .filter_map(|line| {
124 let mut parts = line.splitn(3, FIELD);
125 Some(Checkpoint {
126 sha: parts.next()?.to_string(),
127 time: parts.next().unwrap_or("").to_string(),
128 message: parts.next().unwrap_or("").to_string(),
129 files_changed: None,
130 })
131 })
132 .collect())
133}
134
135pub fn files_of(project: &Path, sha: &str) -> Result<Vec<String>, String> {
138 if sha.is_empty() || !sha.chars().all(|c| c.is_ascii_hexdigit()) {
139 return Err("not a checkpoint id".to_string());
140 }
141 let git_dir = shadow_git_dir(project)?;
142 if !git_dir.join("HEAD").exists() {
143 return Ok(Vec::new());
144 }
145 let env = base_env(&git_dir, project);
146 let out = git(
147 &[
148 "show",
149 "--name-only",
150 "--no-renames",
151 "--pretty=format:",
152 sha,
153 ],
154 project,
155 Duration::from_secs(15),
156 &env,
157 )?
158 .ok_stdout()?;
159 let mut files: Vec<String> = out
160 .lines()
161 .map(str::trim)
162 .filter(|l| !l.is_empty())
163 .map(str::to_owned)
164 .collect();
165 files.sort();
166 files.dedup();
167 Ok(files)
168}
169
170pub fn diff(project: &Path, from: Option<&str>, to: Option<&str>) -> Result<String, String> {
173 let git_dir = shadow_git_dir(project)?;
174 if !git_dir.join("HEAD").exists() {
175 return Err("no checkpoints yet — run snapshot first".to_string());
176 }
177 let env = base_env(&git_dir, project);
178 let mut args: Vec<String> = vec!["diff".to_string()];
179 match (from, to) {
180 (Some(f), Some(t)) => {
181 args.push(f.to_string());
182 args.push(t.to_string());
183 }
184 (Some(f), None) => args.push(f.to_string()),
185 (None, _) => args.push("HEAD".to_string()),
186 }
187 let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
188 git(&arg_refs, project, Duration::from_secs(30), &env)?.ok_stdout()
189}
190
191pub fn restore(project: &Path, git_ref: &str, path: Option<&str>) -> Result<String, String> {
194 let git_dir = shadow_git_dir(project)?;
195 if !git_dir.join("HEAD").exists() {
196 return Err("no checkpoints yet — nothing to restore".to_string());
197 }
198 let env = base_env(&git_dir, project);
199 let target = path.unwrap_or(".");
200 git(
201 &["checkout", git_ref, "--", target],
202 project,
203 Duration::from_mins(1),
204 &env,
205 )?
206 .ok_stdout()?;
207 Ok(format!("restored {target} from {git_ref}"))
208}
209
210pub fn git(
213 args: &[&str],
214 cwd: &Path,
215 timeout: Duration,
216 env: &[(String, String)],
217) -> Result<GitOutput, String> {
218 let refs: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
219 run_git(args, cwd, timeout, &refs)
220}
221
222fn base_env(git_dir: &Path, work_tree: &Path) -> Vec<(String, String)> {
223 vec![
224 ("GIT_DIR".into(), git_dir.to_string_lossy().into_owned()),
225 (
226 "GIT_WORK_TREE".into(),
227 work_tree.to_string_lossy().into_owned(),
228 ),
229 ("GIT_AUTHOR_NAME".into(), "lean-ctx".into()),
230 ("GIT_AUTHOR_EMAIL".into(), "agent@lean-ctx.local".into()),
231 ("GIT_COMMITTER_NAME".into(), "lean-ctx".into()),
232 ("GIT_COMMITTER_EMAIL".into(), "agent@lean-ctx.local".into()),
233 ]
234}
235
236fn head_sha(project: &Path, env: &[(String, String)]) -> Result<String, String> {
237 let out = git(
238 &["rev-parse", "--short", "HEAD"],
239 project,
240 Duration::from_secs(10),
241 env,
242 )?
243 .ok_stdout()?;
244 Ok(out.trim().to_string())
245}
246
247fn now_iso(project: &Path, env: &[(String, String)]) -> String {
248 git(
249 &["show", "-s", "--format=%cI", "HEAD"],
250 project,
251 Duration::from_secs(10),
252 env,
253 )
254 .ok()
255 .and_then(|o| o.ok_stdout().ok())
256 .map(|s| s.trim().to_string())
257 .unwrap_or_default()
258}
259
260fn count_changed(project: &Path, env: &[(String, String)], sha: &str) -> usize {
261 let range = format!("{sha}^..{sha}");
263 let out = git(
264 &["diff", "--name-only", &range],
265 project,
266 Duration::from_secs(15),
267 env,
268 );
269 match out {
270 Ok(o) if o.success => o.stdout.lines().filter(|l| !l.trim().is_empty()).count(),
271 _ => {
272 git(
274 &["show", "--name-only", "--pretty=format:", sha],
275 project,
276 Duration::from_secs(15),
277 env,
278 )
279 .ok()
280 .and_then(|o| o.ok_stdout().ok())
281 .map_or(0, |s| s.lines().filter(|l| !l.trim().is_empty()).count())
282 }
283 }
284}
285
286fn shadow_git_dir(project: &Path) -> Result<PathBuf, String> {
287 let hash = project_hash(project);
288 Ok(crate::core::data_dir::lean_ctx_data_dir()?
289 .join("shadow")
290 .join(hash)
291 .join("git"))
292}
293
294fn project_hash(project: &Path) -> String {
296 let canonical = std::fs::canonicalize(project).unwrap_or_else(|_| project.to_path_buf());
297 let bytes = canonical.to_string_lossy();
298 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
299 for b in bytes.as_bytes() {
300 hash ^= u64::from(*b);
301 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
302 }
303 format!("{hash:016x}")
304}
305
306fn write_excludes(git_dir: &Path) -> Result<PathBuf, String> {
307 let path = git_dir
308 .parent()
309 .unwrap_or(git_dir)
310 .join("lean-ctx-excludes");
311 let defaults = "\
312# lean-ctx shadow-history excludes (keeps snapshots lean even without a project .gitignore)
313.git/
314target/
315node_modules/
316dist/
317build/
318.venv/
319__pycache__/
320*.lock
321";
322 std::fs::write(&path, defaults).map_err(|e| format!("cannot write excludes: {e}"))?;
323 Ok(path)
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 fn git_ready() -> bool {
331 super::super::git_available()
332 }
333
334 fn temp_project(tag: &str) -> PathBuf {
335 let dir = std::env::temp_dir().join(format!("lc_shadow_{tag}_{}", std::process::id()));
336 let _ = std::fs::remove_dir_all(&dir);
337 std::fs::create_dir_all(&dir).unwrap();
338 dir
339 }
340
341 #[test]
342 fn project_hash_is_stable_and_hex() {
343 let h1 = project_hash(Path::new("/some/project"));
344 let h2 = project_hash(Path::new("/some/project"));
345 assert_eq!(h1, h2);
346 assert_eq!(h1.len(), 16);
347 assert!(h1.chars().all(|c| c.is_ascii_hexdigit()));
348 }
349
350 #[test]
351 fn snapshot_log_diff_restore_roundtrip() {
352 if !git_ready() {
353 return;
354 }
355 let _lock = crate::core::data_dir::test_env_lock();
356 let data = temp_project("data");
357 crate::test_env::set_var("LEAN_CTX_DATA_DIR", &data);
358 let project = temp_project("proj");
359
360 std::fs::write(project.join("a.txt"), "v1\n").unwrap();
361 let c1 = snapshot(&project, "first").expect("snapshot 1");
362 assert_eq!(c1.files_changed, Some(1));
363
364 let c1b = snapshot(&project, "again").expect("snapshot noop");
366 assert_eq!(c1b.files_changed, Some(0));
367
368 std::fs::write(project.join("a.txt"), "v2\n").unwrap();
369 let d = diff(&project, None, None).expect("diff vs HEAD");
370 assert!(d.contains("-v1") && d.contains("+v2"), "diff was: {d}");
371
372 let c2 = snapshot(&project, "second").expect("snapshot 2");
373 assert_ne!(c1.sha, c2.sha);
374
375 let entries = log(&project, 10).expect("log");
376 assert!(entries.len() >= 2, "expected >=2 checkpoints");
377
378 restore(&project, &c1.sha, Some("a.txt")).expect("restore");
380 let restored = std::fs::read_to_string(project.join("a.txt")).unwrap();
381 assert_eq!(restored, "v1\n");
382
383 assert!(
385 !project.join(".git").exists(),
386 "shadow history must not touch the user's project .git"
387 );
388
389 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
390 let _ = std::fs::remove_dir_all(&data);
391 let _ = std::fs::remove_dir_all(&project);
392 }
393
394 #[test]
395 fn files_of_lists_what_each_checkpoint_changed() {
396 if !git_ready() {
397 return;
398 }
399 let _lock = crate::core::data_dir::test_env_lock();
400 let data = temp_project("files_data");
401 crate::test_env::set_var("LEAN_CTX_DATA_DIR", &data);
402 let project = temp_project("files_proj");
403 assert_eq!(files_of(&project, "abc123").unwrap(), Vec::<String>::new());
404
405 std::fs::write(project.join("b.txt"), "1\n").unwrap();
406 std::fs::write(project.join("a.txt"), "1\n").unwrap();
407 let c1 = snapshot(&project, "first").expect("snapshot 1");
408 std::fs::write(project.join("b.txt"), "2\n").unwrap();
409 let c2 = snapshot(&project, "second").expect("snapshot 2");
410
411 assert_eq!(files_of(&project, &c1.sha).unwrap(), vec!["a.txt", "b.txt"]);
412 assert_eq!(files_of(&project, &c2.sha).unwrap(), vec!["b.txt"]);
413 assert!(
414 files_of(&project, "HEAD; rm").is_err(),
415 "only checkpoint ids"
416 );
417 assert!(files_of(&project, "").is_err());
418
419 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
420 let _ = std::fs::remove_dir_all(&data);
421 let _ = std::fs::remove_dir_all(&project);
422 }
423}