Skip to main content

lean_ctx_ext/core/context_snapshot/
restore.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Restore / resume from a Context Snapshot (#1026).
3//!
4//! Phase 3 of the Context Time Machine: take a stored snapshot and bring the
5//! live working state back to it. Two halves, mirroring the vision verbs:
6//!
7//! - **continue** — merge the snapshot's distilled session slice (task,
8//!   progress, decisions, touched files) into the project's live session so the
9//!   next agent picks up exactly where that snapshot left off.
10//! - **reproduce** — optionally check out the snapshot's git anchor so the code
11//!   matches what the model saw (guarded: never discards a dirty tree).
12//!
13//! `merge_session` is a pure function over an in-memory [`SessionState`]
14//! (unit-tested); loading/saving and git are the impure shell around it.
15
16use std::path::Path;
17use std::time::Duration;
18
19use crate::core::session::SessionState;
20
21use super::types::{ContextSnapshotV1, SnapshotSessionV1};
22
23/// What [`restore`] should do beyond the always-on session resume.
24pub struct RestoreOptions {
25    /// Project the snapshot belongs to (selects the live session + git repo).
26    pub project_root: String,
27    /// Check out the snapshot's git commit (refused if the tree is dirty).
28    pub checkout_git: bool,
29}
30
31/// Git side-effect outcome of a restore.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum GitRestore {
34    /// Caller didn't ask to touch git.
35    Skipped,
36    /// Snapshot has no commit anchor (or git is unavailable) to check out.
37    NoAnchor,
38    /// Refused: the working tree had uncommitted changes.
39    DirtyTree,
40    /// Checked out the given commit.
41    CheckedOut(String),
42    /// `git checkout` ran but failed (carries the trimmed git error).
43    Failed(String),
44}
45
46/// What a session merge changed — pure, drives tests and CLI output.
47#[derive(Debug, Default, PartialEq, Eq)]
48pub struct SessionMerge {
49    pub task: Option<String>,
50    pub progress_pct: Option<u8>,
51    pub decisions_added: usize,
52    pub files_added: usize,
53}
54
55/// Full outcome of a [`restore`].
56pub struct RestoreOutcome {
57    pub session: SessionMerge,
58    pub git: GitRestore,
59    /// Whether the snapshot actually carried a session slice to resume from.
60    pub had_session_slice: bool,
61}
62
63/// Restore a snapshot into the live project state: resume its session, and —
64/// when `opts.checkout_git` — check out its git anchor (guarded).
65pub fn restore(
66    snapshot: &ContextSnapshotV1,
67    opts: &RestoreOptions,
68) -> Result<RestoreOutcome, String> {
69    let mut session =
70        SessionState::load_latest_for_project_root(&opts.project_root).unwrap_or_default();
71    if session.project_root.is_none() {
72        session.project_root = Some(opts.project_root.clone());
73    }
74
75    let had_session_slice = snapshot.session.is_some();
76    let merge = match snapshot.session.as_ref() {
77        Some(slice) => {
78            let m = merge_session(&mut session, slice);
79            session.save()?;
80            m
81        }
82        None => SessionMerge::default(),
83    };
84
85    let git = if opts.checkout_git {
86        checkout_anchor(snapshot, &opts.project_root)
87    } else {
88        GitRestore::Skipped
89    };
90
91    Ok(RestoreOutcome {
92        session: merge,
93        git,
94        had_session_slice,
95    })
96}
97
98/// Pure merge of a snapshot session slice into a live session. Task + progress
99/// are overwritten (the snapshot is the source of truth being restored);
100/// decisions and touched files are appended, de-duplicated against what the
101/// live session already holds.
102fn merge_session(session: &mut SessionState, slice: &SnapshotSessionV1) -> SessionMerge {
103    let mut report = SessionMerge::default();
104
105    if let Some(task) = slice
106        .task
107        .as_deref()
108        .map(str::trim)
109        .filter(|t| !t.is_empty())
110    {
111        session.set_task(task, None);
112        if let Some(t) = session.task.as_mut() {
113            t.progress_pct = slice.progress_pct;
114        }
115        report.task = Some(task.to_string());
116        report.progress_pct = slice.progress_pct;
117    }
118
119    for decision in &slice.decisions {
120        let summary = decision.trim();
121        if summary.is_empty() || session.decisions.iter().any(|e| e.summary == summary) {
122            continue;
123        }
124        session.add_decision(summary, None);
125        report.decisions_added += 1;
126    }
127
128    for path in &slice.files_touched {
129        let p = path.trim();
130        if p.is_empty() || session.files_touched.iter().any(|f| f.path == p) {
131            continue;
132        }
133        session.touch_file(p, None, "full", 0);
134        report.files_added += 1;
135    }
136
137    report
138}
139
140/// Check out the snapshot's git anchor, refusing to clobber a dirty tree.
141fn checkout_anchor(snapshot: &ContextSnapshotV1, project_root: &str) -> GitRestore {
142    let Some(commit) = snapshot.git.commit.as_deref().filter(|c| !c.is_empty()) else {
143        return GitRestore::NoAnchor;
144    };
145    // An imported snapshot is untrusted input: only a full object id may
146    // reach git, never an option (`--orphan=…`), a ref or a refspec.
147    if !is_full_object_id(commit) {
148        return GitRestore::Failed(
149            "snapshot git anchor is not a full hex commit id — refusing to check it out".into(),
150        );
151    }
152    if !crate::core::git::git_available() {
153        return GitRestore::NoAnchor;
154    }
155    let root = Path::new(project_root);
156    let dirty = crate::core::git::run_git(
157        &["status", "--porcelain"],
158        root,
159        Duration::from_secs(5),
160        &[],
161    )
162    .is_ok_and(|o| o.success && !o.stdout.trim().is_empty());
163    if dirty {
164        return GitRestore::DirtyTree;
165    }
166    // `--` ends the revision: git never reads the id as a pathspec.
167    match crate::core::git::run_git(
168        &["checkout", "--detach", commit, "--"],
169        root,
170        Duration::from_secs(20),
171        &[],
172    ) {
173        Ok(o) if o.success => GitRestore::CheckedOut(commit.to_string()),
174        Ok(o) => GitRestore::Failed(o.stderr.trim().to_string()),
175        Err(e) => GitRestore::Failed(e),
176    }
177}
178
179/// A full SHA-1 (40) or SHA-256 (64) object id in lowercase hex, as
180/// `git rev-parse HEAD` writes it into the anchor.
181fn is_full_object_id(commit: &str) -> bool {
182    matches!(commit.len(), 40 | 64)
183        && commit
184            .bytes()
185            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    fn slice(
193        task: Option<&str>,
194        progress: Option<u8>,
195        decisions: &[&str],
196        files: &[&str],
197    ) -> SnapshotSessionV1 {
198        SnapshotSessionV1 {
199            session_id: None,
200            task: task.map(str::to_string),
201            decisions: decisions.iter().map(|d| (*d).to_string()).collect(),
202            files_touched: files.iter().map(|f| (*f).to_string()).collect(),
203            progress_pct: progress,
204        }
205    }
206
207    #[test]
208    fn merge_sets_task_and_progress() {
209        let mut session = SessionState::new();
210        let s = slice(Some("Resume the timeline"), Some(60), &[], &[]);
211        let report = merge_session(&mut session, &s);
212        assert_eq!(report.task.as_deref(), Some("Resume the timeline"));
213        assert_eq!(report.progress_pct, Some(60));
214        assert_eq!(session.task.as_ref().and_then(|t| t.progress_pct), Some(60));
215    }
216
217    #[test]
218    fn merge_appends_and_dedups_decisions() {
219        let mut session = SessionState::new();
220        session.add_decision("Use JSONL index", None);
221        let s = slice(
222            None,
223            None,
224            &["Use JSONL index", "Sign with ed25519", "  "],
225            &[],
226        );
227        let report = merge_session(&mut session, &s);
228        // Only the genuinely new, non-empty decision is added.
229        assert_eq!(report.decisions_added, 1);
230        assert!(
231            session
232                .decisions
233                .iter()
234                .any(|d| d.summary == "Sign with ed25519")
235        );
236        assert_eq!(
237            session
238                .decisions
239                .iter()
240                .filter(|d| d.summary == "Use JSONL index")
241                .count(),
242            1
243        );
244    }
245
246    #[test]
247    fn merge_appends_and_dedups_files() {
248        let mut session = SessionState::new();
249        session.touch_file("src/a.rs", None, "full", 100);
250        let s = slice(None, None, &[], &["src/a.rs", "src/b.rs", ""]);
251        let report = merge_session(&mut session, &s);
252        assert_eq!(report.files_added, 1);
253        assert!(session.files_touched.iter().any(|f| f.path == "src/b.rs"));
254    }
255
256    #[test]
257    fn only_full_hex_object_ids_reach_git_checkout() {
258        assert!(is_full_object_id(&"a1".repeat(20)));
259        assert!(is_full_object_id(&"0f".repeat(32)));
260        for hostile in [
261            "--orphan=x",
262            "-b",
263            "abc1234",
264            "main",
265            "HEAD~1",
266            "refs/heads/main:refs/heads/x",
267            &"A1".repeat(20),
268            &format!("-{}", "a".repeat(39)),
269        ] {
270            assert!(!is_full_object_id(hostile), "{hostile}");
271        }
272
273        let mut snapshot = ContextSnapshotV1::new("2026-06-28T00:00:00Z".into(), "9.9.9".into());
274        snapshot.git.commit = Some("--orphan=pwned".into());
275        let outcome = checkout_anchor(&snapshot, "/nonexistent-project-root");
276        assert!(
277            matches!(&outcome, GitRestore::Failed(e) if e.contains("full hex commit id")),
278            "{outcome:?}"
279        );
280    }
281
282    #[test]
283    fn merge_of_empty_slice_changes_nothing() {
284        let mut session = SessionState::new();
285        let report = merge_session(&mut session, &slice(None, None, &[], &[]));
286        assert_eq!(report, SessionMerge::default());
287        assert!(session.task.is_none());
288    }
289}