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
46fn 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
57const WORKSPACE_CLEANUP_LOCK_FILE: &str = "rewind.lock";
65
66#[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
89fn 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
113pub(crate) const SESSION_BUSY_CONTEXT: &str = "Another turn is using this session";
117
118pub(crate) const INTERRUPTED_REWIND_MARKER: &str = "Interrupted rewind";
121
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum BeginPromptFailure {
129 SessionBusy,
133 InterruptedRewind,
136 Other,
139}
140
141pub 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
167pub fn checkpoint_failure_is_recoverable(failure: BeginPromptFailure) -> bool {
173 matches!(failure, BeginPromptFailure::Other)
174}
175
176fn 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 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 }
203
204#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
213struct SnapshotRecordId {
214 turn: usize,
215 session_key: Option<String>,
216}
217
218#[derive(Debug, Clone, PartialEq, Eq)]
223struct SnapshotFileEntry {
224 id: SnapshotRecordId,
225 path: PathBuf,
226}
227
228fn 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 if let Ok(turn) = rest.parse::<usize>() {
242 return Some(SnapshotRecordId { turn, session_key: None });
243 }
244 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 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(¤t) {
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); 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 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 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 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 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 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 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 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 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 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 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 fn action_snapshot_path(&self, action_number: usize) -> PathBuf {
778 self.storage_dir.join(format!("action_{action_number}.json"))
779 }
780
781 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 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 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 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 if scope.includes_code() {
839 for file_path in &action.touched_files {
840 let absolute = self.workspace.join(file_path);
842 if tokio::fs::try_exists(&absolute).await.unwrap_or(false) {
843 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 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;