Skip to main content

harn_hostlib/
fs_snapshot.rs

1//! Per-tool-call filesystem snapshots — Gemini-style `/restore` primitives.
2//!
3//! Captures the pre-image of paths touched by a mutating tool call so a
4//! client can roll the change back surgically without losing untracked
5//! work. Snapshot identity is the ACP `toolCallId`, so consumers index
6//! into the same id space the rest of the transcript already records.
7//!
8//! Two capture modes:
9//!
10//! 1. **Explicit** — the caller passes a `paths` list to
11//!    `hostlib_fs_snapshot`; bytes are copied immediately.
12//! 2. **Auto-on-write** — calling `hostlib_fs_snapshot` without `paths`
13//!    registers an open snapshot. The
14//!    [`auto_capture_for_write`] hook fires from inside
15//!    `tools/write_file` and `tools/delete_file` and lazy-copies each
16//!    pre-image into the active snapshot keyed by the current
17//!    [`harn_vm::agent_sessions::current_tool_call_id`].
18//!
19//! Storage layout (per session):
20//!
21//! ```text
22//! .harn/state/snapshots/<session_id>/
23//!   <snapshot_id>/
24//!     manifest.json    # path -> { kind, body_hash?, mode? }
25//!     bodies/<sha256>  # content-addressed; deduped across snapshots
26//! ```
27//!
28//! Snapshots are session-scoped and ephemeral. They are not persisted
29//! across machine reboots; consumers that need durable rollback bundle
30//! them into a session via `session/load`.
31
32use std::collections::{BTreeMap, BTreeSet};
33use std::fs as stdfs;
34use std::path::{Component, Path, PathBuf};
35use std::sync::Arc;
36use std::sync::{Mutex, OnceLock};
37
38use harn_vm::VmValue;
39use serde::{Deserialize, Serialize};
40use sha2::{Digest, Sha256};
41
42use crate::error::HostlibError;
43use crate::registry::{BuiltinRegistry, HostlibCapability, RegisteredBuiltin, SyncHandler};
44use crate::tools::args::{
45    build_dict, dict_arg, optional_string, optional_string_list, require_string, str_value,
46};
47
48const SNAPSHOT_BUILTIN: &str = "hostlib_fs_snapshot";
49const RESTORE_BUILTIN: &str = "hostlib_fs_restore";
50const LIST_BUILTIN: &str = "hostlib_fs_list_snapshots";
51const DROP_BUILTIN: &str = "hostlib_fs_drop_snapshot";
52
53const MANIFEST_VERSION: u32 = 1;
54const STATE_REL: &[&str] = &[".harn", "state", "snapshots"];
55
56/// Default cap on the on-disk footprint of one session's snapshot bundle
57/// before the oldest snapshots are evicted. Matches the proposal in
58/// [#1720](https://github.com/burin-labs/harn/issues/1720): 1 GiB.
59pub const DEFAULT_SESSION_BYTE_CAP: u64 = 1024 * 1024 * 1024;
60
61/// Hostlib filesystem snapshot capability handle.
62#[derive(Default)]
63pub struct FsSnapshotCapability;
64
65impl HostlibCapability for FsSnapshotCapability {
66    fn module_name(&self) -> &'static str {
67        // Snapshots live under the existing `fs/` schema directory so the
68        // contract surface stays consolidated alongside the staging
69        // primitives.
70        "fs"
71    }
72
73    fn register_builtins(&self, registry: &mut BuiltinRegistry) {
74        register(registry, SNAPSHOT_BUILTIN, "snapshot", snapshot_builtin);
75        register(registry, RESTORE_BUILTIN, "restore", restore_builtin);
76        register(
77            registry,
78            LIST_BUILTIN,
79            "list_snapshots",
80            list_snapshots_builtin,
81        );
82        register(
83            registry,
84            DROP_BUILTIN,
85            "drop_snapshot",
86            drop_snapshot_builtin,
87        );
88    }
89}
90
91fn register(
92    registry: &mut BuiltinRegistry,
93    name: &'static str,
94    method: &'static str,
95    runner: fn(&[VmValue]) -> Result<VmValue, HostlibError>,
96) {
97    let handler: SyncHandler = std::sync::Arc::new(runner);
98    registry.register(RegisteredBuiltin {
99        name,
100        module: "fs",
101        method,
102        handler,
103    });
104}
105
106#[derive(Clone, Debug, Serialize, Deserialize)]
107#[serde(tag = "kind", rename_all = "snake_case")]
108enum SnapshotEntry {
109    File {
110        body_hash: String,
111        len: u64,
112        #[serde(default, skip_serializing_if = "Option::is_none")]
113        mode: Option<u32>,
114    },
115    Absent,
116}
117
118#[derive(Clone, Debug, Serialize, Deserialize)]
119struct Manifest {
120    version: u32,
121    snapshot_id: String,
122    scope_id: String,
123    session_id: String,
124    root: String,
125    taken_at_ms: i64,
126    entries: BTreeMap<String, SnapshotEntry>,
127}
128
129#[derive(Clone, Debug)]
130struct SnapshotState {
131    snapshot_id: String,
132    scope_id: String,
133    session_id: String,
134    root: PathBuf,
135    taken_at_ms: i64,
136    /// Logical absolute paths (workspace-relative when storage permits).
137    entries: BTreeMap<PathBuf, SnapshotEntry>,
138}
139
140/// Per-snapshot summary returned by `list_snapshots`.
141#[derive(Clone, Debug)]
142pub struct SnapshotSummary {
143    /// Stable identifier (canonically the ACP toolCallId).
144    pub snapshot_id: String,
145    /// Caller-chosen scope id passed when the snapshot was created.
146    pub scope_id: String,
147    /// Wall-clock capture time, milliseconds since the UNIX epoch.
148    pub taken_at_ms: i64,
149    /// Logical paths captured at snapshot time.
150    pub captured_paths: Vec<String>,
151    /// Total bytes captured for `captured_paths`.
152    pub byte_count: u64,
153}
154
155/// Result returned after capturing a new snapshot.
156#[derive(Clone, Debug)]
157pub struct SnapshotResult {
158    /// Stable identifier (equal to the requested `scope_id`).
159    pub snapshot_id: String,
160    /// Paths captured into this snapshot.
161    pub captured_paths: Vec<String>,
162    /// Total bytes captured for `captured_paths`.
163    pub byte_count: u64,
164}
165
166/// Result returned after restoring a snapshot.
167#[derive(Clone, Debug)]
168pub struct RestoreResult {
169    /// Echoed snapshot id.
170    pub snapshot_id: String,
171    /// Paths successfully restored.
172    pub restored_paths: Vec<String>,
173    /// Paths skipped, with human-readable reasons.
174    pub skipped_paths_with_reasons: Vec<(String, String)>,
175}
176
177/// Result returned after dropping a snapshot.
178#[derive(Clone, Debug)]
179pub struct DropResult {
180    /// Echoed snapshot id.
181    pub snapshot_id: String,
182    /// True when an existing snapshot was removed.
183    pub dropped: bool,
184}
185
186#[derive(Debug)]
187struct SessionSnapshots {
188    /// Snapshots, in insertion order.
189    snapshots: Vec<SnapshotState>,
190    /// Bytes currently held in this session's snapshot bundle. We track
191    /// this rather than recomputing from `bodies/` so eviction stays
192    /// O(snapshots) instead of walking the filesystem on every write.
193    byte_count: u64,
194    /// Per-session byte cap. Defaults to [`DEFAULT_SESSION_BYTE_CAP`] and
195    /// can be overridden with [`configure_session_byte_cap`].
196    byte_cap: u64,
197}
198
199impl Default for SessionSnapshots {
200    fn default() -> Self {
201        Self {
202            snapshots: Vec::new(),
203            byte_count: 0,
204            byte_cap: DEFAULT_SESSION_BYTE_CAP,
205        }
206    }
207}
208
209static SESSIONS: OnceLock<Mutex<BTreeMap<String, SessionSnapshots>>> = OnceLock::new();
210
211fn sessions() -> &'static Mutex<BTreeMap<String, SessionSnapshots>> {
212    SESSIONS.get_or_init(|| Mutex::new(BTreeMap::new()))
213}
214
215/// Override the byte cap for a specific session and immediately enforce
216/// it. Returns the previous cap.
217///
218/// Primarily intended for tests that want to force eviction without
219/// writing a gigabyte. Production embedders generally leave the default
220/// in place; touching one session never affects another.
221pub fn configure_session_byte_cap(session_id: &str, bytes: u64) -> u64 {
222    let mut guard = sessions()
223        .lock()
224        .expect("fs_snapshot session mutex poisoned");
225    let bundle = guard.entry(session_id.to_string()).or_default();
226    let previous = bundle.byte_cap;
227    bundle.byte_cap = bytes.max(1);
228    enforce_byte_cap(bundle, session_id, None);
229    previous
230}
231
232/// Drop every snapshot registered for `session_id`, both in memory and
233/// on disk. Returns the number of snapshots removed.
234///
235/// ACP hosts should call this on session close so the snapshot bundle
236/// doesn't outlive the conversation. Tests can also call it on
237/// teardown when reusing a session id across cases.
238pub fn drop_session_snapshots(session_id: &str) -> usize {
239    let mut guard = sessions()
240        .lock()
241        .expect("fs_snapshot session mutex poisoned");
242    let Some(bundle) = guard.remove(session_id) else {
243        return 0;
244    };
245    let count = bundle.snapshots.len();
246    for snapshot in &bundle.snapshots {
247        remove_snapshot_dir(snapshot);
248    }
249    count
250}
251
252/// Drop every registered session's snapshots, in memory and on disk.
253/// Returns the number of sessions removed.
254///
255/// [`drop_session_snapshots`] handles a single conversation on ACP
256/// session close. This drains the entire process-global map and is
257/// intended for host reset paths (e.g. the test runner between cases)
258/// where the worker is reused and snapshot bundles would otherwise
259/// accumulate one session at a time.
260pub fn reset_all_sessions() -> usize {
261    let mut guard = sessions()
262        .lock()
263        .expect("fs_snapshot session mutex poisoned");
264    let session_count = guard.len();
265    for bundle in guard.values() {
266        for snapshot in &bundle.snapshots {
267            remove_snapshot_dir(snapshot);
268        }
269    }
270    guard.clear();
271    session_count
272}
273
274/// Number of sessions with registered snapshots. Test-only.
275#[cfg(test)]
276pub fn session_count() -> usize {
277    sessions()
278        .lock()
279        .expect("fs_snapshot session mutex poisoned")
280        .len()
281}
282
283/// Take a snapshot. When `paths` is empty the snapshot is "open" — bytes
284/// are captured lazily as `auto_capture_for_write` fires from inside
285/// the mutating tool builtins.
286pub fn snapshot(
287    session_id: &str,
288    scope_id: &str,
289    paths: &[String],
290    root: Option<&Path>,
291) -> Result<SnapshotResult, HostlibError> {
292    validate_session_id(SNAPSHOT_BUILTIN, session_id)?;
293    validate_scope_id(SNAPSHOT_BUILTIN, scope_id)?;
294    let root = resolve_root(root);
295    let mut guard = sessions()
296        .lock()
297        .expect("fs_snapshot session mutex poisoned");
298    let bundle = guard.entry(session_id.to_string()).or_default();
299    upsert_snapshot(bundle, session_id, scope_id, &root)?;
300    let mut captured_paths = Vec::new();
301    let mut byte_count = 0u64;
302    for raw in paths {
303        let path = normalize_logical(Path::new(raw));
304        let added =
305            capture_path(bundle, session_id, scope_id, &path, &root).map_err(|message| {
306                HostlibError::Backend {
307                    builtin: SNAPSHOT_BUILTIN,
308                    message,
309                }
310            })?;
311        if let Some(bytes) = added {
312            byte_count = byte_count.saturating_add(bytes);
313            captured_paths.push(path.to_string_lossy().into_owned());
314        }
315    }
316    enforce_byte_cap(bundle, session_id, Some(scope_id));
317    let state = bundle
318        .snapshots
319        .iter()
320        .find(|snap| snap.snapshot_id == scope_id)
321        .expect("snapshot just upserted is protected from byte-cap eviction");
322    persist_manifest(state).map_err(|err| HostlibError::Backend {
323        builtin: SNAPSHOT_BUILTIN,
324        message: err,
325    })?;
326    Ok(SnapshotResult {
327        snapshot_id: state.snapshot_id.clone(),
328        captured_paths,
329        byte_count,
330    })
331}
332
333/// Restore a previously-captured snapshot.
334pub fn restore(
335    session_id: &str,
336    snapshot_id: &str,
337    paths: &[String],
338) -> Result<RestoreResult, HostlibError> {
339    validate_session_id(RESTORE_BUILTIN, session_id)?;
340    validate_scope_id(RESTORE_BUILTIN, snapshot_id)?;
341    let mut guard = sessions()
342        .lock()
343        .expect("fs_snapshot session mutex poisoned");
344    let bundle = guard
345        .get_mut(session_id)
346        .ok_or_else(|| HostlibError::Backend {
347            builtin: RESTORE_BUILTIN,
348            message: format!("no snapshots registered for session `{session_id}`"),
349        })?;
350    let state = bundle
351        .snapshots
352        .iter()
353        .find(|snap| snap.snapshot_id == snapshot_id)
354        .cloned()
355        .ok_or_else(|| HostlibError::Backend {
356            builtin: RESTORE_BUILTIN,
357            message: format!("unknown snapshot `{snapshot_id}` for session `{session_id}`"),
358        })?;
359    let selected = select_paths(&state, paths);
360    let mut restored_paths = Vec::new();
361    let mut skipped_paths_with_reasons = Vec::new();
362    for path in selected {
363        let Some(entry) = state.entries.get(&path) else {
364            continue;
365        };
366        let label = path.to_string_lossy().into_owned();
367        match restore_entry(&state, &path, entry) {
368            Ok(()) => restored_paths.push(label),
369            Err(reason) => skipped_paths_with_reasons.push((label, reason)),
370        }
371    }
372    Ok(RestoreResult {
373        snapshot_id: snapshot_id.to_string(),
374        restored_paths,
375        skipped_paths_with_reasons,
376    })
377}
378
379/// List snapshots registered for a session, sorted by capture time.
380pub fn list_snapshots(session_id: &str) -> Result<Vec<SnapshotSummary>, HostlibError> {
381    validate_session_id(LIST_BUILTIN, session_id)?;
382    let guard = sessions()
383        .lock()
384        .expect("fs_snapshot session mutex poisoned");
385    let Some(bundle) = guard.get(session_id) else {
386        return Ok(Vec::new());
387    };
388    let mut summaries: Vec<SnapshotSummary> = bundle
389        .snapshots
390        .iter()
391        .map(|state| SnapshotSummary {
392            snapshot_id: state.snapshot_id.clone(),
393            scope_id: state.scope_id.clone(),
394            taken_at_ms: state.taken_at_ms,
395            captured_paths: state
396                .entries
397                .keys()
398                .map(|path| path.to_string_lossy().into_owned())
399                .collect(),
400            byte_count: entry_byte_count(state),
401        })
402        .collect();
403    summaries.sort_by_key(|summary| summary.taken_at_ms);
404    Ok(summaries)
405}
406
407/// Drop a snapshot's in-memory and on-disk state.
408pub fn drop_snapshot(session_id: &str, snapshot_id: &str) -> Result<DropResult, HostlibError> {
409    validate_session_id(DROP_BUILTIN, session_id)?;
410    validate_scope_id(DROP_BUILTIN, snapshot_id)?;
411    let mut guard = sessions()
412        .lock()
413        .expect("fs_snapshot session mutex poisoned");
414    let Some(bundle) = guard.get_mut(session_id) else {
415        return Ok(DropResult {
416            snapshot_id: snapshot_id.to_string(),
417            dropped: false,
418        });
419    };
420    let position = bundle
421        .snapshots
422        .iter()
423        .position(|snap| snap.snapshot_id == snapshot_id);
424    let dropped = match position {
425        Some(idx) => {
426            let removed = bundle.snapshots.remove(idx);
427            bundle.byte_count = bundle.byte_count.saturating_sub(entry_byte_count(&removed));
428            remove_snapshot_dir(&removed);
429            true
430        }
431        None => false,
432    };
433    Ok(DropResult {
434        snapshot_id: snapshot_id.to_string(),
435        dropped,
436    })
437}
438
439/// Auto-on-write hook called from the mutating tool builtins.
440///
441/// Captures `path`'s pre-image into the snapshot whose id matches the
442/// current [`harn_vm::agent_sessions::current_tool_call_id`]. The first
443/// write in a tool call auto-opens that snapshot. The hook silently no-ops
444/// when no session is active or no tool-call id is set, which keeps read-only
445/// tools and writes outside active tool scopes cheap.
446pub(crate) fn auto_capture_for_write(builtin: &'static str, path: &Path) {
447    let Some(session_id) = active_session_id() else {
448        return;
449    };
450    let Some(snapshot_id) = harn_vm::agent_sessions::current_tool_call_id() else {
451        return;
452    };
453    let mut guard = sessions()
454        .lock()
455        .expect("fs_snapshot session mutex poisoned");
456    let bundle = guard.entry(session_id.clone()).or_default();
457    if !bundle
458        .snapshots
459        .iter()
460        .any(|snap| snap.snapshot_id == snapshot_id)
461    {
462        let root =
463            crate::fs::configured_session_root(&session_id).unwrap_or_else(|| resolve_root(None));
464        if let Err(error) = upsert_snapshot(bundle, &session_id, &snapshot_id, &root) {
465            tracing::warn!(
466                "fs_snapshot: failed to auto-open snapshot {snapshot_id} in session {session_id} (builtin={builtin}): {error}"
467            );
468            return;
469        }
470    }
471    let Some(snapshot) = bundle
472        .snapshots
473        .iter()
474        .find(|snap| snap.snapshot_id == snapshot_id)
475    else {
476        return;
477    };
478    let scope_id = snapshot.scope_id.clone();
479    let root = snapshot.root.clone();
480    let key = normalize_logical(path);
481    match capture_path(bundle, &session_id, &snapshot_id, &key, &root) {
482        Ok(_added) => {
483            if let Some(state) = bundle
484                .snapshots
485                .iter()
486                .find(|snap| snap.snapshot_id == snapshot_id)
487            {
488                if let Err(err) = persist_manifest(state) {
489                    tracing::warn!(
490                        "fs_snapshot: failed to persist manifest for snapshot {snapshot_id} in session {session_id} (scope_id={scope_id}, builtin={builtin}): {err}"
491                    );
492                }
493            }
494        }
495        Err(err) => {
496            tracing::warn!(
497                "fs_snapshot: failed to auto-capture `{}` for snapshot {snapshot_id} in session {session_id} (scope_id={scope_id}, builtin={builtin}): {err}",
498                key.display()
499            );
500        }
501    }
502    enforce_byte_cap(bundle, &session_id, Some(&snapshot_id));
503}
504
505fn snapshot_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
506    let raw = dict_arg(SNAPSHOT_BUILTIN, args)?;
507    let dict = raw.as_ref();
508    let session_id = require_string(SNAPSHOT_BUILTIN, dict, "session_id")?;
509    let scope_id = require_string(SNAPSHOT_BUILTIN, dict, "scope_id")?;
510    let paths = optional_string_list(SNAPSHOT_BUILTIN, dict, "paths")?;
511    let root = optional_string(SNAPSHOT_BUILTIN, dict, "root")?.map(PathBuf::from);
512    let result = snapshot(&session_id, &scope_id, &paths, root.as_deref())?;
513    Ok(build_dict([
514        ("snapshot_id", str_value(&result.snapshot_id)),
515        (
516            "captured_paths",
517            VmValue::List(Arc::new(
518                result
519                    .captured_paths
520                    .into_iter()
521                    .map(|path| VmValue::String(Arc::from(path)))
522                    .collect(),
523            )),
524        ),
525        ("byte_count", VmValue::Int(result.byte_count as i64)),
526    ]))
527}
528
529fn restore_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
530    let raw = dict_arg(RESTORE_BUILTIN, args)?;
531    let dict = raw.as_ref();
532    let session_id = require_string(RESTORE_BUILTIN, dict, "session_id")?;
533    let snapshot_id = require_string(RESTORE_BUILTIN, dict, "snapshot_id")?;
534    let paths = optional_string_list(RESTORE_BUILTIN, dict, "paths")?;
535    let result = restore(&session_id, &snapshot_id, &paths)?;
536    Ok(build_dict([
537        ("snapshot_id", str_value(&result.snapshot_id)),
538        (
539            "restored_paths",
540            VmValue::List(Arc::new(
541                result
542                    .restored_paths
543                    .into_iter()
544                    .map(|path| VmValue::String(Arc::from(path)))
545                    .collect(),
546            )),
547        ),
548        (
549            "skipped_paths_with_reasons",
550            VmValue::List(Arc::new(
551                result
552                    .skipped_paths_with_reasons
553                    .into_iter()
554                    .map(|(path, reason)| {
555                        build_dict([("path", str_value(&path)), ("reason", str_value(&reason))])
556                    })
557                    .collect(),
558            )),
559        ),
560    ]))
561}
562
563fn list_snapshots_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
564    let raw = dict_arg(LIST_BUILTIN, args)?;
565    let dict = raw.as_ref();
566    let session_id = require_string(LIST_BUILTIN, dict, "session_id")?;
567    let summaries = list_snapshots(&session_id)?;
568    Ok(build_dict([(
569        "snapshots",
570        VmValue::List(Arc::new(
571            summaries.into_iter().map(snapshot_summary_value).collect(),
572        )),
573    )]))
574}
575
576fn drop_snapshot_builtin(args: &[VmValue]) -> Result<VmValue, HostlibError> {
577    let raw = dict_arg(DROP_BUILTIN, args)?;
578    let dict = raw.as_ref();
579    let session_id = require_string(DROP_BUILTIN, dict, "session_id")?;
580    let snapshot_id = require_string(DROP_BUILTIN, dict, "snapshot_id")?;
581    let result = drop_snapshot(&session_id, &snapshot_id)?;
582    Ok(build_dict([
583        ("snapshot_id", str_value(&result.snapshot_id)),
584        ("dropped", VmValue::Bool(result.dropped)),
585    ]))
586}
587
588fn snapshot_summary_value(summary: SnapshotSummary) -> VmValue {
589    build_dict([
590        ("snapshot_id", str_value(&summary.snapshot_id)),
591        ("scope_id", str_value(&summary.scope_id)),
592        ("taken_at_ms", VmValue::Int(summary.taken_at_ms)),
593        (
594            "captured_paths",
595            VmValue::List(Arc::new(
596                summary
597                    .captured_paths
598                    .into_iter()
599                    .map(|path| VmValue::String(Arc::from(path)))
600                    .collect(),
601            )),
602        ),
603        ("byte_count", VmValue::Int(summary.byte_count as i64)),
604    ])
605}
606
607fn upsert_snapshot(
608    bundle: &mut SessionSnapshots,
609    session_id: &str,
610    scope_id: &str,
611    root: &Path,
612) -> Result<(), HostlibError> {
613    if bundle
614        .snapshots
615        .iter()
616        .any(|snap| snap.snapshot_id == scope_id)
617    {
618        return Ok(());
619    }
620    let state = SnapshotState {
621        snapshot_id: scope_id.to_string(),
622        scope_id: scope_id.to_string(),
623        session_id: session_id.to_string(),
624        root: root.to_path_buf(),
625        taken_at_ms: now_ms(),
626        entries: BTreeMap::new(),
627    };
628    let dir = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id);
629    stdfs::create_dir_all(dir.join("bodies")).map_err(|err| HostlibError::Backend {
630        builtin: SNAPSHOT_BUILTIN,
631        message: format!("mkdir {}: {err}", dir.display()),
632    })?;
633    bundle.snapshots.push(state);
634    Ok(())
635}
636
637fn capture_path(
638    bundle: &mut SessionSnapshots,
639    session_id: &str,
640    snapshot_id: &str,
641    path: &Path,
642    root: &Path,
643) -> Result<Option<u64>, String> {
644    let snap_index = bundle
645        .snapshots
646        .iter()
647        .position(|snap| snap.snapshot_id == snapshot_id)
648        .ok_or_else(|| format!("snapshot `{snapshot_id}` is not registered"))?;
649    if bundle.snapshots[snap_index].entries.contains_key(path) {
650        return Ok(None);
651    }
652    let metadata = stdfs::symlink_metadata(path);
653    let (entry, byte_count) = match metadata {
654        Err(err) if err.kind() == std::io::ErrorKind::NotFound => (SnapshotEntry::Absent, 0u64),
655        Err(err) => {
656            return Err(format!("stat `{}`: {err}", path.display()));
657        }
658        Ok(metadata) if metadata.is_dir() => {
659            return Err(format!(
660                "snapshot of directory `{}` is not supported yet",
661                path.display()
662            ));
663        }
664        Ok(metadata) if metadata.file_type().is_symlink() => {
665            return Err(format!(
666                "snapshot of symlink `{}` is not supported yet",
667                path.display()
668            ));
669        }
670        Ok(metadata) => {
671            let bytes = stdfs::read(path)
672                .map_err(|err| format!("read `{}` for snapshot: {err}", path.display()))?;
673            let body_hash = hex::encode(Sha256::digest(&bytes));
674            let len = bytes.len() as u64;
675            store_body(root, session_id, snapshot_id, &body_hash, &bytes)?;
676            #[cfg(unix)]
677            let mode = {
678                use std::os::unix::fs::MetadataExt;
679                Some(metadata.mode())
680            };
681            #[cfg(not(unix))]
682            let mode = {
683                let _ = &metadata;
684                None
685            };
686            (
687                SnapshotEntry::File {
688                    body_hash,
689                    len,
690                    mode,
691                },
692                len,
693            )
694        }
695    };
696    let snap = &mut bundle.snapshots[snap_index];
697    snap.entries.insert(path.to_path_buf(), entry);
698    bundle.byte_count = bundle.byte_count.saturating_add(byte_count);
699    Ok(Some(byte_count))
700}
701
702fn store_body(
703    root: &Path,
704    session_id: &str,
705    snapshot_id: &str,
706    body_hash: &str,
707    bytes: &[u8],
708) -> Result<(), String> {
709    let bodies = snapshot_dir(root, session_id, snapshot_id).join("bodies");
710    stdfs::create_dir_all(&bodies).map_err(|err| format!("mkdir {}: {err}", bodies.display()))?;
711    let body_path = bodies.join(body_hash);
712    if !body_path.exists() {
713        atomic_write(&body_path, bytes)?;
714    }
715    Ok(())
716}
717
718fn restore_entry(state: &SnapshotState, path: &Path, entry: &SnapshotEntry) -> Result<(), String> {
719    match entry {
720        SnapshotEntry::Absent => match stdfs::symlink_metadata(path) {
721            Ok(metadata) if metadata.is_dir() => stdfs::remove_dir_all(path)
722                .map_err(|err| format!("remove_dir_all {}: {err}", path.display())),
723            Ok(_) => stdfs::remove_file(path)
724                .map_err(|err| format!("remove_file {}: {err}", path.display())),
725            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
726            Err(err) => Err(format!("stat {}: {err}", path.display())),
727        },
728        SnapshotEntry::File {
729            body_hash, mode, ..
730        } => {
731            let body_path = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id)
732                .join("bodies")
733                .join(body_hash);
734            let bytes = stdfs::read(&body_path)
735                .map_err(|err| format!("read snapshot body `{}`: {err}", body_path.display()))?;
736            atomic_write(path, &bytes)?;
737            #[cfg(unix)]
738            if let Some(bits) = mode {
739                use std::os::unix::fs::PermissionsExt;
740                let permissions = stdfs::Permissions::from_mode(*bits);
741                stdfs::set_permissions(path, permissions)
742                    .map_err(|err| format!("set_permissions `{}`: {err}", path.display()))?;
743            }
744            #[cfg(not(unix))]
745            let _ = mode;
746            Ok(())
747        }
748    }
749}
750
751fn persist_manifest(state: &SnapshotState) -> Result<(), String> {
752    let dir = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id);
753    stdfs::create_dir_all(&dir).map_err(|err| format!("mkdir {}: {err}", dir.display()))?;
754    let manifest = Manifest {
755        version: MANIFEST_VERSION,
756        snapshot_id: state.snapshot_id.clone(),
757        scope_id: state.scope_id.clone(),
758        session_id: state.session_id.clone(),
759        root: state.root.to_string_lossy().into_owned(),
760        taken_at_ms: state.taken_at_ms,
761        entries: state
762            .entries
763            .iter()
764            .map(|(path, entry)| (path.to_string_lossy().into_owned(), entry.clone()))
765            .collect(),
766    };
767    let bytes = serde_json::to_vec_pretty(&manifest)
768        .map_err(|err| format!("serialize snapshot manifest: {err}"))?;
769    atomic_write(&dir.join("manifest.json"), &bytes)
770}
771
772fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
773    if let Some(parent) = path.parent() {
774        stdfs::create_dir_all(parent)
775            .map_err(|err| format!("mkdir {}: {err}", parent.display()))?;
776    }
777    let tmp = path.with_extension(format!("tmp-{}-{}", std::process::id(), now_ms()));
778    stdfs::write(&tmp, bytes).map_err(|err| format!("write {}: {err}", tmp.display()))?;
779    match stdfs::rename(&tmp, path) {
780        Ok(()) => Ok(()),
781        Err(rename_err) => {
782            let _ = stdfs::remove_file(path);
783            stdfs::rename(&tmp, path).map_err(|retry| {
784                // Both renames failed; the temp file would otherwise linger
785                // and accumulate in the snapshot directory.
786                let _ = stdfs::remove_file(&tmp);
787                format!(
788                    "rename {} to {}: {rename_err}; retry: {retry}",
789                    tmp.display(),
790                    path.display()
791                )
792            })
793        }
794    }
795}
796
797/// Evict snapshots oldest-first until the session is back under its byte
798/// cap. `protected` names the snapshot currently being written (if any);
799/// it is never evicted, even when it alone exceeds the cap — otherwise the
800/// caller would lose the very snapshot it just captured (and `snapshot`
801/// would panic re-fetching it). A snapshot larger than the whole cap is
802/// therefore retained: rollback for an in-flight write takes precedence
803/// over the soft budget.
804fn enforce_byte_cap(bundle: &mut SessionSnapshots, session_id: &str, protected: Option<&str>) {
805    while bundle.byte_count > bundle.byte_cap {
806        let Some(idx) = bundle
807            .snapshots
808            .iter()
809            .position(|snap| Some(snap.snapshot_id.as_str()) != protected)
810        else {
811            break;
812        };
813        let evicted = bundle.snapshots.remove(idx);
814        bundle.byte_count = bundle.byte_count.saturating_sub(entry_byte_count(&evicted));
815        tracing::info!(
816            "fs_snapshot: evicting snapshot `{}` from session `{session_id}` (over byte cap {})",
817            evicted.snapshot_id,
818            bundle.byte_cap,
819        );
820        remove_snapshot_dir(&evicted);
821    }
822}
823
824fn remove_snapshot_dir(state: &SnapshotState) {
825    let dir = snapshot_dir(&state.root, &state.session_id, &state.snapshot_id);
826    let _ = stdfs::remove_dir_all(&dir);
827}
828
829fn entry_byte_count(state: &SnapshotState) -> u64 {
830    state
831        .entries
832        .values()
833        .map(|entry| match entry {
834            SnapshotEntry::File { len, .. } => *len,
835            SnapshotEntry::Absent => 0,
836        })
837        .sum()
838}
839
840fn select_paths(state: &SnapshotState, paths: &[String]) -> Vec<PathBuf> {
841    if paths.is_empty() {
842        return state.entries.keys().cloned().collect();
843    }
844    let requested: BTreeSet<PathBuf> = paths
845        .iter()
846        .map(|path| normalize_logical(Path::new(path)))
847        .collect();
848    state
849        .entries
850        .keys()
851        .filter(|path| requested.contains(*path))
852        .cloned()
853        .collect()
854}
855
856fn validate_session_id(builtin: &'static str, session_id: &str) -> Result<(), HostlibError> {
857    if session_id.trim().is_empty() {
858        return Err(HostlibError::InvalidParameter {
859            builtin,
860            param: "session_id",
861            message: "must not be empty".to_string(),
862        });
863    }
864    Ok(())
865}
866
867fn validate_scope_id(builtin: &'static str, scope_id: &str) -> Result<(), HostlibError> {
868    if scope_id.trim().is_empty() {
869        let param = match builtin {
870            SNAPSHOT_BUILTIN => "scope_id",
871            _ => "snapshot_id",
872        };
873        return Err(HostlibError::InvalidParameter {
874            builtin,
875            param,
876            message: "must not be empty".to_string(),
877        });
878    }
879    Ok(())
880}
881
882fn active_session_id() -> Option<String> {
883    harn_vm::agent_sessions::current_session_id().filter(|id| !id.trim().is_empty())
884}
885
886fn resolve_root(root: Option<&Path>) -> PathBuf {
887    match root {
888        Some(path) => normalize_logical(path),
889        None => normalize_logical(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))),
890    }
891}
892
893fn snapshot_dir(root: &Path, session_id: &str, snapshot_id: &str) -> PathBuf {
894    let mut dir = root.to_path_buf();
895    for component in STATE_REL {
896        dir.push(component);
897    }
898    dir.push(sanitize_component(session_id));
899    dir.push(sanitize_component(snapshot_id));
900    dir
901}
902
903fn sanitize_component(input: &str) -> String {
904    let sanitized: String = input
905        .chars()
906        .map(|ch| match ch {
907            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => ch,
908            _ => '_',
909        })
910        .collect();
911    if sanitized == input {
912        sanitized
913    } else {
914        let hash = hex::encode(Sha256::digest(input.as_bytes()));
915        format!("{sanitized}-{}", &hash[..12])
916    }
917}
918
919fn normalize_logical(path: &Path) -> PathBuf {
920    let absolute = if path.is_absolute() {
921        path.to_path_buf()
922    } else {
923        std::env::current_dir()
924            .unwrap_or_else(|_| PathBuf::from("."))
925            .join(path)
926    };
927    let mut out = PathBuf::new();
928    for component in absolute.components() {
929        match component {
930            Component::ParentDir => {
931                out.pop();
932            }
933            Component::CurDir => {}
934            other => out.push(other),
935        }
936    }
937    out
938}
939
940fn now_ms() -> i64 {
941    std::time::SystemTime::now()
942        .duration_since(std::time::UNIX_EPOCH)
943        .map(|duration| duration.as_millis() as i64)
944        .unwrap_or(0)
945}
946
947#[cfg(test)]
948mod tests {
949    use super::*;
950    use std::sync::atomic::{AtomicU64, Ordering};
951    use tempfile::TempDir;
952
953    /// Hand each test its own session id so the process-wide `SESSIONS`
954    /// map isolates them by key — no serialization or process-wide
955    /// reset required.
956    fn unique_session(prefix: &str) -> String {
957        static COUNTER: AtomicU64 = AtomicU64::new(0);
958        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
959        format!("{prefix}-{n}-{}", std::process::id())
960    }
961
962    fn unique_scope() -> String {
963        static COUNTER: AtomicU64 = AtomicU64::new(0);
964        format!("tc-{}", COUNTER.fetch_add(1, Ordering::Relaxed))
965    }
966
967    fn enter_session(id: &str) -> harn_vm::agent_sessions::CurrentSessionGuard {
968        harn_vm::agent_sessions::open_or_create(Some(id.to_string()));
969        harn_vm::agent_sessions::enter_current_session(id.to_string())
970    }
971
972    #[test]
973    fn explicit_snapshot_then_restore_round_trips_file_bytes() {
974        let dir = TempDir::new().unwrap();
975        let file = dir.path().join("note.txt");
976        stdfs::write(&file, b"v1").unwrap();
977        let session = unique_session("snap-roundtrip");
978        let scope = unique_scope();
979        let _session_guard = enter_session(&session);
980
981        let result = snapshot(
982            &session,
983            &scope,
984            &[file.to_string_lossy().into_owned()],
985            Some(dir.path()),
986        )
987        .unwrap();
988        assert_eq!(result.snapshot_id, scope);
989        assert_eq!(result.captured_paths.len(), 1);
990        assert_eq!(result.byte_count, 2);
991
992        stdfs::write(&file, b"clobbered").unwrap();
993        let restored = restore(&session, &scope, &[]).unwrap();
994        assert_eq!(restored.restored_paths.len(), 1);
995        assert!(restored.skipped_paths_with_reasons.is_empty());
996        assert_eq!(stdfs::read(&file).unwrap(), b"v1");
997    }
998
999    #[test]
1000    fn restore_reinstates_deleted_file() {
1001        let dir = TempDir::new().unwrap();
1002        let file = dir.path().join("doomed.txt");
1003        stdfs::write(&file, b"alive").unwrap();
1004        let session = unique_session("snap-reinstate");
1005        let scope = unique_scope();
1006        let _session_guard = enter_session(&session);
1007
1008        snapshot(
1009            &session,
1010            &scope,
1011            &[file.to_string_lossy().into_owned()],
1012            Some(dir.path()),
1013        )
1014        .unwrap();
1015        stdfs::remove_file(&file).unwrap();
1016        assert!(!file.exists());
1017        let restored = restore(&session, &scope, &[]).unwrap();
1018        assert_eq!(restored.restored_paths.len(), 1);
1019        assert_eq!(stdfs::read(&file).unwrap(), b"alive");
1020    }
1021
1022    #[test]
1023    fn absent_snapshot_means_restore_deletes_paths_created_during_the_call() {
1024        let dir = TempDir::new().unwrap();
1025        let file = dir.path().join("new.txt");
1026        assert!(!file.exists());
1027        let session = unique_session("snap-absent");
1028        let scope = unique_scope();
1029        let _session_guard = enter_session(&session);
1030
1031        snapshot(
1032            &session,
1033            &scope,
1034            &[file.to_string_lossy().into_owned()],
1035            Some(dir.path()),
1036        )
1037        .unwrap();
1038        stdfs::write(&file, b"created during call").unwrap();
1039        let restored = restore(&session, &scope, &[]).unwrap();
1040        assert_eq!(restored.restored_paths.len(), 1);
1041        assert!(
1042            !file.exists(),
1043            "restore must delete files that the snapshot saw as absent"
1044        );
1045    }
1046
1047    #[test]
1048    fn list_and_drop_round_trip_through_metadata() {
1049        let dir = TempDir::new().unwrap();
1050        let file = dir.path().join("listed.txt");
1051        stdfs::write(&file, b"abc").unwrap();
1052        let session = unique_session("snap-list");
1053        let scope = unique_scope();
1054        let _session_guard = enter_session(&session);
1055
1056        snapshot(
1057            &session,
1058            &scope,
1059            &[file.to_string_lossy().into_owned()],
1060            Some(dir.path()),
1061        )
1062        .unwrap();
1063        let summaries = list_snapshots(&session).unwrap();
1064        assert_eq!(summaries.len(), 1);
1065        assert_eq!(summaries[0].snapshot_id, scope);
1066        assert_eq!(summaries[0].byte_count, 3);
1067
1068        let dropped = drop_snapshot(&session, &scope).unwrap();
1069        assert!(dropped.dropped);
1070        assert!(list_snapshots(&session).unwrap().is_empty());
1071
1072        let again = drop_snapshot(&session, &scope).unwrap();
1073        assert!(!again.dropped, "second drop must be idempotent");
1074    }
1075
1076    #[test]
1077    fn auto_capture_records_pre_image_keyed_by_current_tool_call_id() {
1078        let dir = TempDir::new().unwrap();
1079        let file = dir.path().join("auto.txt");
1080        stdfs::write(&file, b"pre").unwrap();
1081        let session = unique_session("snap-auto");
1082        let scope = unique_scope();
1083        let _session_guard = enter_session(&session);
1084        let _tool_guard = harn_vm::agent_sessions::enter_current_tool_call(scope.clone());
1085
1086        snapshot(&session, &scope, &[], Some(dir.path())).unwrap();
1087        auto_capture_for_write("hostlib_tools_write_file", &file);
1088        stdfs::write(&file, b"post").unwrap();
1089
1090        let restored = restore(&session, &scope, &[]).unwrap();
1091        assert_eq!(restored.restored_paths.len(), 1);
1092        assert_eq!(stdfs::read(&file).unwrap(), b"pre");
1093    }
1094
1095    #[test]
1096    fn byte_cap_evicts_oldest_snapshot_when_exceeded() {
1097        let dir = TempDir::new().unwrap();
1098        let session = unique_session("snap-evict");
1099        let _session_guard = enter_session(&session);
1100
1101        // Per-session cap: only affects this test's session, so other
1102        // tests can run in parallel without seeing the squeeze.
1103        configure_session_byte_cap(&session, 8);
1104
1105        let mk = |name: &str| {
1106            let path = dir.path().join(name);
1107            stdfs::write(&path, b"12345").unwrap();
1108            path
1109        };
1110
1111        let scope_a = unique_scope();
1112        let scope_b = unique_scope();
1113        let a = mk("a.txt");
1114        snapshot(
1115            &session,
1116            &scope_a,
1117            &[a.to_string_lossy().into_owned()],
1118            Some(dir.path()),
1119        )
1120        .unwrap();
1121        let b = mk("b.txt");
1122        snapshot(
1123            &session,
1124            &scope_b,
1125            &[b.to_string_lossy().into_owned()],
1126            Some(dir.path()),
1127        )
1128        .unwrap();
1129
1130        let ids: Vec<String> = list_snapshots(&session)
1131            .unwrap()
1132            .into_iter()
1133            .map(|summary| summary.snapshot_id)
1134            .collect();
1135        assert_eq!(
1136            ids,
1137            vec![scope_b],
1138            "older snapshot must be evicted when the per-session byte cap is exceeded"
1139        );
1140    }
1141
1142    #[test]
1143    fn snapshot_larger_than_cap_is_retained_not_evicted() {
1144        // A single snapshot whose captured bytes exceed the whole cap must
1145        // survive — evicting the snapshot we just took would lose rollback
1146        // for the in-flight write (and previously panicked re-fetching it).
1147        let dir = TempDir::new().unwrap();
1148        let session = unique_session("snap-oversized");
1149        let _session_guard = enter_session(&session);
1150        configure_session_byte_cap(&session, 4);
1151
1152        let scope = unique_scope();
1153        let file = dir.path().join("big.txt");
1154        stdfs::write(&file, b"0123456789").unwrap();
1155        let result = snapshot(
1156            &session,
1157            &scope,
1158            &[file.to_string_lossy().into_owned()],
1159            Some(dir.path()),
1160        )
1161        .unwrap();
1162        assert_eq!(result.byte_count, 10);
1163
1164        let ids: Vec<String> = list_snapshots(&session)
1165            .unwrap()
1166            .into_iter()
1167            .map(|summary| summary.snapshot_id)
1168            .collect();
1169        assert_eq!(
1170            ids,
1171            vec![scope],
1172            "an oversized snapshot must be retained rather than evicting itself"
1173        );
1174    }
1175
1176    #[test]
1177    fn drop_session_snapshots_removes_every_snapshot_for_a_session() {
1178        let dir = TempDir::new().unwrap();
1179        let file = dir.path().join("retained.txt");
1180        stdfs::write(&file, b"x").unwrap();
1181        let session = unique_session("snap-drop-session");
1182        let scope_a = unique_scope();
1183        let scope_b = unique_scope();
1184        let _session_guard = enter_session(&session);
1185
1186        snapshot(
1187            &session,
1188            &scope_a,
1189            &[file.to_string_lossy().into_owned()],
1190            Some(dir.path()),
1191        )
1192        .unwrap();
1193        snapshot(
1194            &session,
1195            &scope_b,
1196            &[file.to_string_lossy().into_owned()],
1197            Some(dir.path()),
1198        )
1199        .unwrap();
1200        assert_eq!(list_snapshots(&session).unwrap().len(), 2);
1201
1202        assert_eq!(drop_session_snapshots(&session), 2);
1203        assert!(list_snapshots(&session).unwrap().is_empty());
1204        assert_eq!(drop_session_snapshots(&session), 0, "idempotent");
1205    }
1206}