Skip to main content

vtcode_core/core/agent/snapshots/
mod.rs

1mod native;
2mod retention;
3mod types;
4pub use native::{PromptCheckpointLease, declare_prompt_edit};
5use std::collections::BTreeSet;
6use std::fs;
7use std::path::{Component, Path, PathBuf};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
10pub use types::{
11    ActionSnapshot, DEFAULT_CHECKPOINTS_ENABLED, DEFAULT_MAX_AGE_DAYS, DEFAULT_MAX_SNAPSHOTS, FileEncoding,
12    FileSnapshot, REWIND_ACTIVE_KEEP, RevertScope, RollbackResult, SnapshotConfig, SnapshotMetadata,
13    SnapshotSkippedPath, SnapshotSkippedPaths, SnapshotTurnContext, SnapshotTurnDiagnostics, StoredSnapshot,
14};
15use types::{
16    MAX_DESCRIPTION_LEN, NEXT_ACTION_NUMBER, SNAPSHOT_SCHEMA_VERSION, collect_turn_numbers, normalized_prompt_text,
17    sanitize_relative_path,
18};
19
20use anyhow::{Context, Result};
21use base64::Engine as _;
22use base64::engine::general_purpose::STANDARD as BASE64;
23use serde::{Deserialize, Serialize};
24use vtcode_commons::canonicalize;
25use vtcode_exec_events::{MAX_IN_PROGRESS_EXEC_SESSIONS, Usage, deserialize_null_as_default};
26
27use crate::core::SECONDS_PER_DAY;
28use crate::core::pending_actions::ExpectedOutcome;
29use crate::core::state_schema::{SchemaVersion, VersionedState};
30use crate::types::CompactStr;
31use crate::utils::error_messages::ERR_CREATE_CHECKPOINT_DIR;
32use crate::utils::file_utils::{ensure_dir_exists, ensure_dir_exists_sync, write_json_file};
33use crate::utils::path::canonicalize_workspace;
34use crate::utils::session_archive::SessionMessage;
35
36#[derive(Clone)]
37pub struct SnapshotManager {
38    enabled: bool,
39    workspace: PathBuf,
40    canonical_workspace: PathBuf,
41    storage_dir: PathBuf,
42    max_snapshots: usize,
43    max_age_days: Option<u64>,
44}
45
46/// Filesystem-safe session key shared by branch files, snapshot records, and
47/// session locks.
48///
49/// Hex-encoding keeps every byte (including `/`, `.`, and unicode) out of the
50/// filename so session ids can never escape the storage directory. Fails
51/// closed on empty or over-long ids instead of writing an ambiguous file.
52fn session_filename_key(session: &str) -> Result<String> {
53    anyhow::ensure!(!session.is_empty() && session.len() <= 80, "Invalid session ID");
54    Ok(session.as_bytes().iter().map(|b| format!("{b:02x}")).collect())
55}
56
57/// Shared lock file serializing checkpoint-content reclamation
58/// (`delete_sessions` + `collect_garbage`) across processes.
59///
60/// Retention is best-effort and retryable: a process that finds this lock
61/// held skips its cleanup round instead of interleaving filesnap deletes
62/// with another process's scan. Unlike the per-session turn locks, this
63/// file persists; it is never unlinked.
64const WORKSPACE_CLEANUP_LOCK_FILE: &str = "rewind.lock";
65
66/// Whether a locked fd still refers to the file currently at `lock_path`.
67///
68/// The completion path unlinks a session lock while holding its lock. A process
69/// that opened the old inode just before that unlink can `try_lock` the ghost
70/// after the holder drops — while another process creates a fresh file — and
71/// both would believe they hold the lock. Comparing inos closes that window.
72#[cfg(unix)]
73fn locked_file_matches_path(file: &fs::File, lock_path: &Path) -> bool {
74    use std::os::unix::fs::MetadataExt;
75    let Ok(locked) = file.metadata() else {
76        return false;
77    };
78    let Ok(current) = fs::metadata(lock_path) else {
79        return false;
80    };
81    locked.ino() == current.ino()
82}
83
84#[cfg(not(unix))]
85fn locked_file_matches_path(_: &fs::File, _: &Path) -> bool {
86    true
87}
88
89/// Acquire the lock at `lock_path`, verifying the locked inode is still the
90/// file at that path. A ghost acquisition (locked inode replaced under us)
91/// is dropped and retried against the current file, so mutual exclusion holds
92/// across the completion path's unlink-while-held cleanup.
93fn acquire_verified_rewind_lock(lock_path: &Path) -> std::io::Result<fs::File> {
94    for _ in 0..3 {
95        let file = fs::OpenOptions::new()
96            .read(true)
97            .write(true)
98            .create(true)
99            .truncate(false)
100            .open(lock_path)?;
101        file.try_lock()?;
102        if locked_file_matches_path(&file, lock_path) {
103            return Ok(file);
104        }
105        drop(file);
106    }
107    Err(std::io::Error::other(format!(
108        "{} kept changing identity; retry the turn",
109        lock_path.file_name().and_then(|name| name.to_str()).unwrap_or("lock file")
110    )))
111}
112
113/// Context marker attached when this session's checkpoint lock is already
114/// held. Shared by the lock site and [`classify_begin_prompt_error`] so a
115/// reworded message cannot silently break contention detection.
116pub(crate) const SESSION_BUSY_CONTEXT: &str = "Another turn is using this session";
117
118/// Marker prefix for errors reporting an interrupted rewind with pending
119/// recovery state. Shared by the guard sites and [`classify_begin_prompt_error`].
120pub(crate) const INTERRUPTED_REWIND_MARKER: &str = "Interrupted rewind";
121
122/// Why a turn-start checkpoint could not be taken.
123///
124/// Classified from the full error chain (see [`classify_begin_prompt_error`]);
125/// drives both the user-facing notice and whether the turn may proceed
126/// without a checkpoint.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum BeginPromptFailure {
129    /// This same session already has a running turn holding its checkpoint
130    /// lock. Fail closed: a second writer would corrupt the session's
131    /// navigation state.
132    SessionBusy,
133    /// A previous rewind was interrupted and still holds pending recovery
134    /// state. Fail closed: the user must run `/rewind` to auto-recover first.
135    InterruptedRewind,
136    /// Anything else: storage, capture, or worker failures with no concurrent
137    /// writer. The turn may proceed without a checkpoint (no rewind for it).
138    Other,
139}
140
141/// Classify a `begin_prompt` failure from its full error chain.
142///
143/// The busy branch recognizes both VT Code's session-lock marker and
144/// filesnap's typed [`filesnap::SnapshotError::SessionBusy`], so a contended
145/// filesnap session is never misreported as a generic outage.
146pub fn classify_begin_prompt_error(err: &anyhow::Error) -> BeginPromptFailure {
147    let mut interrupted = false;
148    for layer in err.chain() {
149        if layer
150            .downcast_ref::<filesnap::SnapshotError>()
151            .is_some_and(|snapshot| matches!(snapshot, filesnap::SnapshotError::SessionBusy { .. }))
152            || layer.to_string().contains(SESSION_BUSY_CONTEXT)
153        {
154            return BeginPromptFailure::SessionBusy;
155        }
156        if layer.to_string().contains(INTERRUPTED_REWIND_MARKER) {
157            interrupted = true;
158        }
159    }
160    if interrupted {
161        BeginPromptFailure::InterruptedRewind
162    } else {
163        BeginPromptFailure::Other
164    }
165}
166
167/// Whether a turn may proceed without its start-of-turn checkpoint.
168///
169/// Only [`BeginPromptFailure::Other`] proceeds: contention and pending-rewind
170/// states imply another writer (or a half-restored workspace) and stay
171/// fail-closed with the prompt kept for retry.
172pub fn checkpoint_failure_is_recoverable(failure: BeginPromptFailure) -> bool {
173    matches!(failure, BeginPromptFailure::Other)
174}
175
176/// Remove a lock file only while holding its lock on the current inode.
177///
178/// Deleting a lock another process holds (or is about to hold) would let a
179/// later open create a fresh inode and break mutual exclusion, so an
180/// unacquirable or replaced file is left alone. Best-effort: failures only
181/// leave a stale 0-byte file for the next cleanup round.
182fn remove_lock_file_if_unheld(lock_path: &Path) {
183    let file = match fs::OpenOptions::new().read(true).write(true).open(lock_path) {
184        Ok(file) => file,
185        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
186        Err(error) => {
187            tracing::debug!(%error, path = %lock_path.display(), "failed to open lock file for cleanup");
188            return;
189        }
190    };
191    // Only unlink while holding a lock on the file that is currently at the
192    // path; a ghost lock (path replaced under us) must not delete the
193    // replacement's lock file.
194    if file.try_lock().is_ok() && locked_file_matches_path(&file, lock_path) {
195        if let Err(error) = fs::remove_file(lock_path)
196            && error.kind() != std::io::ErrorKind::NotFound
197        {
198            tracing::debug!(%error, path = %lock_path.display(), "failed to remove stale lock file");
199        }
200    }
201    // `file` (and its lock) drops here, after the unlink.
202}
203
204/// Identity of one checkpoint record file: the owning session (if any) plus
205/// the session-local turn number.
206///
207/// `session_key` is `None` for legacy `turn_{n}.json` records written before
208/// session scoping; scoped records carry `Some(key)`.
209///
210/// Ordering is turn-major so retention prunes the oldest turns first across
211/// all sessions, with the session key as a deterministic tiebreak.
212#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
213struct SnapshotRecordId {
214    turn: usize,
215    session_key: Option<String>,
216}
217
218/// One enumerated checkpoint record: its identity plus its live `.json` path.
219///
220/// Retired (`*.retired-*`), recovery (`turn_recovery_*.json`), and branch
221/// (`branch_*.json`) files never produce entries.
222#[derive(Debug, Clone, PartialEq, Eq)]
223struct SnapshotFileEntry {
224    id: SnapshotRecordId,
225    path: PathBuf,
226}
227
228/// Parse a checkpoint-directory filename into a record identity.
229///
230/// Returns `None` for anything that is not a live checkpoint record: wrong
231/// extension, `turn_recovery_*` rescue files, branch files, and malformed
232/// stems. This predicate is shared by enumeration, retention, and tests so the
233/// on-disk contract cannot drift between readers.
234fn parse_snapshot_filename(file_name: &str) -> Option<SnapshotRecordId> {
235    let stem = file_name.strip_suffix(".json")?;
236    let rest = stem.strip_prefix("turn_")?;
237    if rest.is_empty() || stem.starts_with("turn_recovery_") {
238        return None;
239    }
240    // Legacy `turn_{n}.json`: the whole remainder is the turn number.
241    if let Ok(turn) = rest.parse::<usize>() {
242        return Some(SnapshotRecordId { turn, session_key: None });
243    }
244    // Scoped `turn_{hex}_{n}.json`: hex carries no underscores, so the turn
245    // is everything after the last one.
246    let (key, turn_str) = rest.rsplit_once('_')?;
247    if key.is_empty() || key.len() % 2 != 0 || !key.bytes().all(|b| b.is_ascii_hexdigit()) {
248        return None;
249    }
250    let turn = turn_str.parse::<usize>().ok()?;
251    Some(SnapshotRecordId { turn, session_key: Some(key.to_owned()) })
252}
253
254impl SnapshotManager {
255    pub fn new(config: SnapshotConfig) -> Result<Self> {
256        let storage_dir = config.storage_dir();
257        let canonical_workspace = canonicalize_workspace(&config.workspace);
258
259        if config.enabled {
260            ensure_dir_exists_sync(&storage_dir)
261                .with_context(|| format!("{}: {}", ERR_CREATE_CHECKPOINT_DIR, storage_dir.display()))?;
262        }
263        Ok(Self {
264            enabled: config.enabled,
265            workspace: config.workspace,
266            canonical_workspace,
267            storage_dir,
268            max_snapshots: config.max_snapshots,
269            max_age_days: config.max_age_days,
270        })
271    }
272
273    pub fn enabled(&self) -> bool {
274        self.enabled
275    }
276
277    fn snapshot_path(&self, turn_number: usize) -> PathBuf {
278        self.storage_dir.join(format!("turn_{turn_number}.json"))
279    }
280
281    /// Session-scoped checkpoint record: `turn_{session_key}_{turn}.json`.
282    ///
283    /// Each session owns a disjoint set of record files so two sessions in one
284    /// workspace never overwrite each other's checkpoints. The unscoped
285    /// [`Self::snapshot_path`] form stays as the legacy layout: pre-upgrade
286    /// records keep loading (see [`Self::load_snapshot_for_session`]) and
287    /// session-less writers keep writing it.
288    fn snapshot_path_for_session(&self, session: &str, turn_number: usize) -> Result<PathBuf> {
289        let key = session_filename_key(session)?;
290        Ok(self.storage_dir.join(format!("turn_{key}_{turn_number}.json")))
291    }
292
293    fn normalize_path(&self, path: &Path) -> Option<PathBuf> {
294        if path.is_absolute() {
295            if let Ok(canonical_path) = canonicalize(path)
296                && let Ok(stripped) = canonical_path.strip_prefix(&self.canonical_workspace)
297            {
298                return sanitize_relative_path(stripped);
299            }
300
301            if let Ok(stripped) = path.strip_prefix(&self.workspace) {
302                return sanitize_relative_path(stripped);
303            }
304
305            None
306        } else {
307            sanitize_relative_path(path)
308        }
309    }
310
311    fn checked_file_path(workspace: &Path, storage: &Path, relative: &Path) -> Result<PathBuf> {
312        let relative = sanitize_relative_path(relative).context("Checkpoint path escapes the workspace")?;
313        anyhow::ensure!(!relative.as_os_str().is_empty(), "Checkpoint path must name a file");
314        let absolute = workspace.join(&relative);
315        let storage = canonicalize(storage).unwrap_or_else(|_| storage.to_path_buf());
316        anyhow::ensure!(!absolute.starts_with(&storage), "Checkpoint cannot restore its own storage");
317        let mut current = workspace.to_path_buf();
318        for part in relative.components() {
319            current.push(part);
320            match fs::symlink_metadata(&current) {
321                Ok(metadata) => {
322                    anyhow::ensure!(!metadata.file_type().is_symlink(), "Checkpoint path crosses a symlink")
323                }
324                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
325                Err(error) => return Err(error.into()),
326            }
327        }
328        Ok(absolute)
329    }
330
331    fn read_snapshot_files(&self) -> Result<Vec<SnapshotFileEntry>> {
332        let mut entries = Vec::with_capacity(64); // Typical directory has ~20-50 snapshot files
333        if !self.storage_dir.exists() {
334            return Ok(entries);
335        }
336        for entry in fs::read_dir(&self.storage_dir)
337            .with_context(|| format!("failed to read checkpoint directory: {}", self.storage_dir.display()))?
338        {
339            let path = entry?.path();
340            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
341                continue;
342            };
343            if let Some(id) = parse_snapshot_filename(name) {
344                entries.push(SnapshotFileEntry { id, path });
345            }
346        }
347        entries.sort_by(|a, b| a.id.cmp(&b.id));
348        Ok(entries)
349    }
350
351    /// Enumerate live checkpoint records that carry `turn_number`, across the
352    /// legacy layout and every session scope.
353    ///
354    /// Used to resolve bare-turn lookups (`revert --turn N`): legacy records
355    /// sort before scoped ones so pre-upgrade workspaces resolve exactly as
356    /// they did before session scoping existed.
357    fn read_snapshot_files_for_turn(&self, turn_number: usize) -> Result<Vec<SnapshotFileEntry>> {
358        let mut matches: Vec<SnapshotFileEntry> = self
359            .read_snapshot_files()?
360            .into_iter()
361            .filter(|entry| entry.id.turn == turn_number)
362            .collect();
363        matches.sort_by(|a, b| a.id.session_key.cmp(&b.id.session_key));
364        Ok(matches)
365    }
366
367    fn decode_file(encoding: FileEncoding, data: &str) -> Result<Vec<u8>> {
368        match encoding {
369            FileEncoding::Utf8 => Ok(data.as_bytes().to_vec()),
370            FileEncoding::Base64 => BASE64.decode(data).context("failed to decode base64 file contents"),
371            FileEncoding::Filesnap => anyhow::bail!("filesnap references require the snapshot store"),
372        }
373    }
374
375    fn truncate_description(description: &str) -> String {
376        let first_line = description.lines().next().unwrap_or("").trim();
377        vtcode_commons::formatting::truncate_within(first_line, MAX_DESCRIPTION_LEN, "…")
378    }
379
380    fn derive_prompt_metadata(conversation: &[SessionMessage]) -> (Option<String>, Option<usize>) {
381        conversation
382            .iter()
383            .enumerate()
384            .rev()
385            .find_map(|(index, message)| {
386                if message.role != crate::llm::provider::MessageRole::User {
387                    return None;
388                }
389
390                let prompt = message.content.as_text();
391                normalized_prompt_text(prompt.as_ref()).map(|prompt| (Some(prompt.to_string()), Some(index)))
392            })
393            .unwrap_or((None, None))
394    }
395
396    fn resolve_prompt_metadata(
397        prompt_text: Option<&str>,
398        prompt_message_index: Option<usize>,
399        conversation: &[SessionMessage],
400    ) -> (Option<String>, Option<usize>) {
401        let (derived_prompt_text, derived_prompt_index) = Self::derive_prompt_metadata(conversation);
402        let prompt_text = prompt_text
403            .and_then(normalized_prompt_text)
404            .map(str::to_string)
405            .or(derived_prompt_text);
406        let prompt_message_index = prompt_message_index
407            .filter(|index| *index < conversation.len())
408            .or(derived_prompt_index);
409        (prompt_text, prompt_message_index)
410    }
411
412    fn hydrate_prompt_metadata(stored: &mut StoredSnapshot) {
413        let (prompt_text, prompt_message_index) = Self::resolve_prompt_metadata(
414            stored.metadata.prompt_text.as_deref(),
415            stored.metadata.prompt_message_index,
416            &stored.conversation,
417        );
418        stored.metadata.prompt_text = prompt_text;
419        stored.metadata.prompt_message_index = prompt_message_index;
420    }
421
422    fn current_timestamp() -> Result<u64> {
423        Ok(SystemTime::now()
424            .duration_since(UNIX_EPOCH)
425            .context("system clock before UNIX_EPOCH")?
426            .as_secs())
427    }
428
429    /// Next checkpoint turn number for `session`: one past the highest turn
430    /// the session already owns.
431    ///
432    /// Legacy (unscoped) records count toward every session's maximum so a
433    /// resumed pre-upgrade session never reuses a turn number its own branch
434    /// file already references under the legacy layout. Fresh sessions in a
435    /// fresh workspace still start at 1.
436    pub fn next_turn_number(&self, session: &str) -> Result<usize> {
437        let key = session_filename_key(session)?;
438        Ok(self
439            .read_snapshot_files()?
440            .into_iter()
441            .filter(|entry| entry.id.session_key.is_none() || entry.id.session_key.as_deref() == Some(&key))
442            .map(|entry| entry.id.turn)
443            .max()
444            .unwrap_or(0)
445            .saturating_add(1))
446    }
447
448    pub async fn create_snapshot(
449        &self,
450        turn_number: usize,
451        description: &str,
452        conversation: &[SessionMessage],
453        modified_files: &BTreeSet<PathBuf>,
454        prompt_text: Option<&str>,
455        prompt_message_index: Option<usize>,
456        turn_context: Option<SnapshotTurnContext>,
457    ) -> Result<Option<SnapshotMetadata>> {
458        if !self.enabled {
459            return Ok(None);
460        }
461
462        let timestamp = Self::current_timestamp()?;
463        let mut paths = Vec::with_capacity(modified_files.len());
464        for path in modified_files {
465            if let Some(relative) = self.normalize_path(path) {
466                paths.push(relative);
467            }
468        }
469        let workspace = self.canonical_workspace.clone();
470        let storage = self.storage_dir.clone();
471        let files = tokio::task::spawn_blocking(move || -> Result<Vec<FileSnapshot>> {
472            // Conversation-only checkpoints need no unreferenced engine session.
473            if paths.is_empty() {
474                return Ok(Vec::new());
475            }
476            let mut absolute_paths = Vec::with_capacity(paths.len());
477            for relative in &paths {
478                absolute_paths.push(Self::checked_file_path(&workspace, &storage, relative)?);
479            }
480            let store = filesnap::WorkspaceStore::open(&storage, &workspace)?;
481            let turn = format!("vt-{}", uuid::Uuid::new_v4());
482            let checkpoint = store.checkpoint(&turn, &turn, absolute_paths.iter().cloned())?;
483            if checkpoint.stats.dropped != 0 {
484                let skipped = native::skipped_paths_record(&workspace, &checkpoint);
485                anyhow::bail!("Checkpoint could not capture every selected file: {}", skipped.summary());
486            }
487            Ok(paths
488                .into_iter()
489                .zip(absolute_paths)
490                .map(|(relative, absolute)| {
491                    let key = filesnap::canonical_key(&absolute).to_string_lossy().into_owned();
492                    FileSnapshot {
493                        path: relative.to_string_lossy().replace('\\', "/"),
494                        deleted: checkpoint.manifest.absent.contains(&key),
495                        encoding: Some(FileEncoding::Filesnap),
496                        data: Some(turn.clone()),
497                    }
498                })
499                .collect())
500        })
501        .await??;
502
503        let (prompt_text, prompt_message_index) =
504            Self::resolve_prompt_metadata(prompt_text, prompt_message_index, conversation);
505        let description_source = prompt_text.as_deref().unwrap_or(description);
506        let turn_context = turn_context.unwrap_or_default();
507        // Session-carrying snapshots land in that session's disjoint record
508        // set; session-less callers keep the legacy shared layout.
509        let record_session = turn_context.session_id.clone();
510        let metadata = SnapshotMetadata {
511            id: format!("turn_{turn_number}"),
512            turn_number,
513            created_at: timestamp,
514            description: Self::truncate_description(description_source),
515            message_count: conversation.len(),
516            file_count: files.len(),
517            touched_files: turn_context.touched_files.clone(),
518            prompt_text,
519            prompt_message_index,
520            session_id: turn_context.session_id,
521            runtime_turn_id: turn_context.runtime_turn_id,
522            session_turn_number: turn_context.session_turn_number,
523            turn_diagnostics: turn_context.turn_diagnostics,
524            skipped_paths: None,
525        };
526
527        let stored = StoredSnapshot {
528            metadata: metadata.clone(),
529            conversation: conversation.to_vec(),
530            files,
531            schema_version: Some(SNAPSHOT_SCHEMA_VERSION),
532        };
533
534        let path = match record_session.as_deref() {
535            Some(session) => self.snapshot_path_for_session(session, turn_number)?,
536            None => self.snapshot_path(turn_number),
537        };
538        if let Some(parent) = path.parent() {
539            ensure_dir_exists(parent)
540                .await
541                .with_context(|| format!("failed to ensure checkpoint directory: {}", parent.display()))?;
542        }
543
544        // Preserve an overwritten turn as a cleanup journal until the new JSON
545        // is published. It is invisible to checkpoint enumeration.
546        let retired = path.with_extension(format!("retired-{}", uuid::Uuid::new_v4()));
547        match tokio::fs::copy(&path, &retired).await {
548            Ok(_) => {}
549            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
550            Err(error) => return Err(error).context("failed to journal replaced checkpoint"),
551        }
552        write_json_file(&path, &stored)
553            .await
554            .with_context(|| format!("failed to write checkpoint: {}", path.display()))?;
555
556        self.cleanup_old_snapshots().await?;
557
558        Ok(Some(metadata))
559    }
560
561    pub async fn list_snapshots(&self) -> Result<Vec<SnapshotMetadata>> {
562        if !self.enabled {
563            return Ok(Vec::new());
564        }
565        self.cleanup_old_snapshots().await?;
566        let snapshot_files = self.read_snapshot_files()?;
567        let mut snapshots = Vec::with_capacity(snapshot_files.len());
568        for entry in snapshot_files {
569            let data = tokio::fs::read(&entry.path)
570                .await
571                .with_context(|| format!("failed to read checkpoint: {}", entry.path.display()))?;
572            let mut stored: StoredSnapshot = serde_json::from_slice(&data)
573                .with_context(|| format!("failed to parse checkpoint: {}", entry.path.display()))?;
574            Self::hydrate_prompt_metadata(&mut stored);
575            snapshots.push(stored.metadata);
576        }
577        snapshots.sort_by(|a, b| b.turn_number.cmp(&a.turn_number).then_with(|| a.session_id.cmp(&b.session_id)));
578        Ok(snapshots)
579    }
580
581    pub async fn load_snapshot(&self, turn_number: usize) -> Result<Option<StoredSnapshot>> {
582        if !self.enabled {
583            return Ok(None);
584        }
585        self.load_snapshot_from_path(&self.snapshot_path(turn_number)).await
586    }
587
588    /// Load `session`'s checkpoint for `turn_number`.
589    ///
590    /// Reads the session-scoped record first, then falls back to the legacy
591    /// shared layout so resumed pre-upgrade sessions keep rewinding turns
592    /// they recorded before session scoping existed.
593    pub async fn load_snapshot_for_session(&self, session: &str, turn_number: usize) -> Result<Option<StoredSnapshot>> {
594        if !self.enabled {
595            return Ok(None);
596        }
597        let scoped = self.snapshot_path_for_session(session, turn_number)?;
598        if let Some(stored) = self.load_snapshot_from_path(&scoped).await? {
599            return Ok(Some(stored));
600        }
601        self.load_snapshot_from_path(&self.snapshot_path(turn_number)).await
602    }
603
604    async fn load_snapshot_from_path(&self, path: &Path) -> Result<Option<StoredSnapshot>> {
605        if !tokio::fs::try_exists(path).await.unwrap_or(false) {
606            return Ok(None);
607        }
608        let data = tokio::fs::read(path)
609            .await
610            .with_context(|| format!("failed to read checkpoint: {}", path.display()))?;
611        let mut stored: StoredSnapshot =
612            serde_json::from_slice(&data).with_context(|| format!("failed to parse checkpoint: {}", path.display()))?;
613        // Migrate legacy snapshots to the current schema version
614        stored = stored
615            .migrate(SNAPSHOT_SCHEMA_VERSION)
616            .with_context(|| format!("failed to migrate checkpoint: {}", path.display()))?;
617        Self::hydrate_prompt_metadata(&mut stored);
618        Ok(Some(stored))
619    }
620
621    pub async fn restore_snapshot(&self, turn_number: usize, scope: RevertScope) -> Result<Option<CheckpointRestore>> {
622        // Legacy records resolve exactly as before session scoping existed.
623        if let Some(stored) = self.load_snapshot(turn_number).await? {
624            return self.restore_stored_snapshot(stored, scope).await.map(Some);
625        }
626        let matches = self.read_snapshot_files_for_turn(turn_number)?;
627        let [entry] = matches.as_slice() else {
628            if matches.is_empty() {
629                return Ok(None);
630            }
631            let sessions = matches
632                .iter()
633                .filter_map(|entry| entry.id.session_key.as_deref())
634                .collect::<Vec<_>>()
635                .join(", ");
636            anyhow::bail!("turn {turn_number} exists in multiple sessions ({sessions}); re-run with --session <id>");
637        };
638        let Some(stored) = self.load_snapshot_from_path(&entry.path).await? else {
639            return Ok(None);
640        };
641        self.restore_stored_snapshot(stored, scope).await.map(Some)
642    }
643
644    /// Restore `session`'s checkpoint for `turn_number`, with the same
645    /// session-then-legacy lookup as [`Self::load_snapshot_for_session`].
646    pub async fn restore_snapshot_for_session(
647        &self,
648        session: &str,
649        turn_number: usize,
650        scope: RevertScope,
651    ) -> Result<Option<CheckpointRestore>> {
652        let Some(stored) = self.load_snapshot_for_session(session, turn_number).await? else {
653            return Ok(None);
654        };
655
656        self.restore_stored_snapshot(stored, scope).await.map(Some)
657    }
658
659    async fn restore_stored_snapshot(&self, stored: StoredSnapshot, scope: RevertScope) -> Result<CheckpointRestore> {
660        self.restore_stored_snapshot_with_ignore(stored, scope, &filesnap::Gitignore::empty())
661            .await
662    }
663
664    async fn restore_stored_snapshot_with_ignore(
665        &self,
666        stored: StoredSnapshot,
667        scope: RevertScope,
668        ignore: &filesnap::Gitignore,
669    ) -> Result<CheckpointRestore> {
670        if scope.includes_code() {
671            let workspace = self.canonical_workspace.clone();
672            let storage = self.storage_dir.clone();
673            let files = stored.files.clone();
674            // Validate the complete path set before any write, including legacy records.
675            tokio::task::spawn_blocking(move || -> Result<()> {
676                for file in &files {
677                    Self::checked_file_path(&workspace, &storage, Path::new(&file.path))?;
678                }
679                Ok(())
680            })
681            .await??;
682        }
683        let engine_backed = stored.files.iter().any(|file| file.encoding == Some(FileEncoding::Filesnap));
684        if scope.includes_code() && engine_backed {
685            let ignore = ignore.clone();
686            let workspace = self.canonical_workspace.clone();
687            let storage = self.storage_dir.clone();
688            let files = stored.files.clone();
689            tokio::task::spawn_blocking(move || -> Result<()> {
690                let turn = files
691                    .first()
692                    .and_then(|file| file.data.as_deref())
693                    .context("Missing filesnap reference")?;
694                anyhow::ensure!(files.iter().all(|file| file.encoding == Some(FileEncoding::Filesnap)
695                    && file.data.as_deref() == Some(turn)), "Mixed or inconsistent checkpoint references");
696                let store = filesnap::WorkspaceStore::open(&storage, &workspace)?;
697                let target = store.target_for_turn(turn)?.context("Missing filesnap checkpoint")?;
698                let manifest = store.manifest(target.manifest_id())?;
699                let expected: BTreeSet<String> = files
700                    .iter()
701                    .map(|file| {
702                        filesnap::canonical_key(&workspace.join(&file.path))
703                            .to_string_lossy()
704                            .into_owned()
705                    })
706                    .collect();
707                let recorded: BTreeSet<String> =
708                    manifest.entries.keys().chain(manifest.absent.iter()).cloned().collect();
709                anyhow::ensure!(expected == recorded, "Checkpoint contains unexpected file paths");
710                let outcome = store.restore_to(
711                    turn,
712                    &target,
713                    filesnap::RestoreKind::Rewind { undo_for: Some(turn) },
714                    expected.iter().map(PathBuf::from),
715                    &ignore,
716                )?;
717                anyhow::ensure!(
718                    outcome.stats.failed.is_empty(),
719                    "Checkpoint restore failed: {:?}",
720                    outcome.stats.failed
721                );
722                Ok(())
723            })
724            .await??;
725        } else if scope.includes_code() {
726            for snapshot in &stored.files {
727                let relative = Path::new(&snapshot.path);
728                let Some(sanitized) = sanitize_relative_path(relative) else {
729                    continue;
730                };
731                let absolute = self.workspace.join(&sanitized);
732                if snapshot.deleted {
733                    if tokio::fs::try_exists(&absolute).await.unwrap_or(false) {
734                        tokio::fs::remove_file(&absolute).await.with_context(|| {
735                            format!("failed to remove file during checkpoint restore: {}", absolute.display())
736                        })?;
737                    }
738                    continue;
739                }
740
741                if let Some(parent) = absolute.parent() {
742                    ensure_dir_exists(parent)
743                        .await
744                        .with_context(|| format!("failed to create directories for restore: {}", parent.display()))?;
745                }
746
747                let encoding = snapshot.encoding.unwrap_or(FileEncoding::Utf8);
748                let data = snapshot.data.as_deref().unwrap_or_default();
749                let bytes = Self::decode_file(encoding, data)?;
750                tokio::fs::write(&absolute, &bytes)
751                    .await
752                    .with_context(|| format!("failed to write restored file: {}", absolute.display()))?;
753            }
754        }
755
756        let conversation = if scope.includes_conversation() {
757            stored.conversation.clone()
758        } else {
759            Vec::new()
760        };
761
762        Ok(CheckpointRestore { metadata: stored.metadata, conversation })
763    }
764
765    pub fn parse_revert_scope(value: &str) -> Option<RevertScope> {
766        match value.to_ascii_lowercase().as_str() {
767            "conversation" | "chat" => Some(RevertScope::Conversation),
768            "code" | "files" => Some(RevertScope::Code),
769            "both" | "full" => Some(RevertScope::Both),
770            _ => None,
771        }
772    }
773
774    // ─── Action-level Snapshots (Incremental Rollback) ────────────────────
775
776    /// File path for an action-level snapshot.
777    fn action_snapshot_path(&self, action_number: usize) -> PathBuf {
778        self.storage_dir.join(format!("action_{action_number}.json"))
779    }
780
781    /// Save an action-level snapshot to disk. Returns the action number.
782    pub async fn save_action_snapshot(&self, action: &ActionSnapshot) -> Result<usize> {
783        if !self.enabled {
784            return Ok(action.action_number);
785        }
786        let path = self.action_snapshot_path(action.action_number);
787        if let Some(parent) = path.parent() {
788            ensure_dir_exists(parent)
789                .await
790                .with_context(|| format!("failed to ensure checkpoint directory: {}", parent.display()))?;
791        }
792        write_json_file(&path, action)
793            .await
794            .with_context(|| format!("failed to write action snapshot: {}", path.display()))?;
795        Ok(action.action_number)
796    }
797
798    /// Load an action-level snapshot from disk.
799    pub async fn load_action_snapshot(&self, action_number: usize) -> Result<Option<ActionSnapshot>> {
800        if !self.enabled {
801            return Ok(None);
802        }
803        let path = self.action_snapshot_path(action_number);
804        if !tokio::fs::try_exists(&path).await.unwrap_or(false) {
805            return Ok(None);
806        }
807        let data = tokio::fs::read(&path)
808            .await
809            .with_context(|| format!("failed to read action snapshot: {}", path.display()))?;
810        let action: ActionSnapshot = serde_json::from_slice(&data)
811            .with_context(|| format!("failed to parse action snapshot: {}", path.display()))?;
812        Ok(Some(action))
813    }
814
815    /// Rollback a single action by restoring conversation state and files.
816    ///
817    /// This truncates the messages vector to `pre_action_message_count` and
818    /// restores file contents from their pre-action state (requires the workspace
819    /// manager to have tracked file versions).
820    pub async fn rollback_one_action(
821        &self,
822        action: &ActionSnapshot,
823        messages: &mut Vec<SessionMessage>,
824        scope: RevertScope,
825    ) -> Result<RollbackResult> {
826        let mut files_restored = 0;
827
828        // Restore conversation: truncate to pre-action length
829        let messages_removed = if scope.includes_conversation() && action.pre_action_message_count <= messages.len() {
830            let removed = messages.len() - action.pre_action_message_count;
831            messages.truncate(action.pre_action_message_count);
832            removed
833        } else {
834            0
835        };
836
837        // Restore files that were touched by this action
838        if scope.includes_code() {
839            for file_path in &action.touched_files {
840                // Read the current file content as a snapshot if possible
841                let absolute = self.workspace.join(file_path);
842                if tokio::fs::try_exists(&absolute).await.unwrap_or(false) {
843                    // In a full implementation, we'd restore from a file version store.
844                    // For now, we track that the file was touched and would need restoration.
845                    files_restored += 1;
846                }
847            }
848        }
849
850        Ok(RollbackResult {
851            rollback_action_id: action.action_id.clone(),
852            messages_removed,
853            files_restored,
854            next_action_number: action.action_number,
855        })
856    }
857
858    /// Generate the next monotonic action number.
859    ///
860    /// Uses an atomic counter to avoid conflicts between concurrent sessions.
861    pub fn next_action_number(&self) -> usize {
862        NEXT_ACTION_NUMBER.fetch_add(1, Ordering::Relaxed) as usize
863    }
864}
865
866#[derive(Debug, Clone)]
867pub struct CheckpointRestore {
868    pub metadata: SnapshotMetadata,
869    pub conversation: Vec<SessionMessage>,
870}
871
872#[cfg(test)]
873mod tests;