Skip to main content

vtcode_commons/
workspace_snapshot.rs

1//! Cheap workspace environment-delta observability.
2//!
3//! Long-horizon agents operate in a *changing environment*: files are written,
4//! processes mutate state, git trees move. The harness needs a fast way to
5//! detect that the environment drifted between turns so it can re-ground
6//! assumptions instead of trusting a stale picture.
7//!
8//! [`WorkspaceSnapshot`] captures a lightweight fingerprint of every tracked
9//! file (size + mtime + a short content hash of the head), and [`diff`]
10//! computes added/changed/removed paths. Snapshots are cheap enough to take at
11//! each turn boundary and to persist as a derived view.
12
13use std::collections::BTreeMap;
14use std::io;
15use std::path::{Path, PathBuf};
16
17use serde::{Deserialize, Serialize};
18
19/// Directories never traversed when capturing a snapshot.
20const SKIP_DIRS: &[&str] = &[
21    ".git",
22    ".svn",
23    "target",
24    "node_modules",
25    "dist",
26    "build",
27    ".vtcode",
28    ".next",
29    "vendor",
30];
31
32/// A compact fingerprint of a single file.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34pub struct FileStat {
35    /// Size in bytes.
36    pub size: u64,
37    /// Modification time in nanoseconds since the Unix epoch.
38    pub mtime_ns: i64,
39    /// FNV-1a hash of the file's first [`HASH_SAMPLE_BYTES`] bytes.
40    pub head_hash: u64,
41}
42
43/// Number of leading bytes sampled for the content fingerprint.
44const HASH_SAMPLE_BYTES: usize = 4096;
45
46/// A point-in-time fingerprint of a workspace's tracked files.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct WorkspaceSnapshot {
49    /// `relative_path -> stat`, sorted for stable diffs.
50    pub files: BTreeMap<String, FileStat>,
51    /// RFC3339 capture timestamp.
52    pub captured_at: String,
53}
54
55/// The difference between two workspace snapshots.
56#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct SnapshotDelta {
58    /// Paths present in `new` but not `old`.
59    pub added: Vec<String>,
60    /// Paths present in both but with a different fingerprint.
61    pub changed: Vec<String>,
62    /// Paths present in `old` but not `new`.
63    pub removed: Vec<String>,
64}
65
66/// Capture a snapshot of `workspace`, skipping VCS/ build/ cache directories.
67///
68/// Files larger than `max_file_bytes` are fingerprinted by size + mtime only
69/// (the head hash is set to 0) to keep capture O(files) rather than O(bytes).
70pub fn capture(workspace: &Path, max_file_bytes: u64) -> io::Result<WorkspaceSnapshot> {
71    let mut files = BTreeMap::new();
72    collect(workspace, workspace, max_file_bytes, &mut files)?;
73    Ok(WorkspaceSnapshot { files, captured_at: now_rfc3339() })
74}
75
76fn collect(
77    root: &Path,
78    dir: &Path,
79    max_file_bytes: u64,
80    out: &mut BTreeMap<String, FileStat>,
81) -> io::Result<()> {
82    for entry in std::fs::read_dir(dir)? {
83        let entry = entry?;
84        let path = entry.path();
85        let ft = entry.file_type()?;
86        if ft.is_dir() {
87            if let Some(name) = path.file_name().and_then(|n| n.to_str())
88                && SKIP_DIRS.contains(&name)
89            {
90                continue;
91            }
92            collect(root, &path, max_file_bytes, out)?;
93        } else if ft.is_file() {
94            let rel = match path.strip_prefix(root).ok().and_then(|p| p.to_str()) {
95                Some(r) => r.to_string(),
96                None => continue,
97            };
98            match entry.metadata() {
99                Ok(meta) => {
100                    let size = meta.len();
101                    let mtime_ns = meta
102                        .modified()
103                        .ok()
104                        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
105                        .map(|d| d.as_nanos() as i64)
106                        .unwrap_or(0);
107                    let head_hash = if size <= max_file_bytes {
108                        hash_head(&path)
109                    } else {
110                        0
111                    };
112                    out.insert(rel, FileStat { size, mtime_ns, head_hash });
113                }
114                Err(_) => continue,
115            }
116        }
117    }
118    Ok(())
119}
120
121/// FNV-1a 64-bit hash of the first [`HASH_SAMPLE_BYTES`] bytes of `path`.
122fn hash_head(path: &Path) -> u64 {
123    const SEED: u64 = 0xcbf29ce484222325;
124    const PRIME: u64 = 0x100000001b3;
125    let mut hash = SEED;
126    let mut buf = [0u8; HASH_SAMPLE_BYTES];
127    if let Ok(mut f) = std::fs::File::open(path) {
128        use std::io::Read;
129        if let Ok(n) = f.read(&mut buf) {
130            for &b in &buf[..n] {
131                hash ^= u64::from(b);
132                hash = hash.wrapping_mul(PRIME);
133            }
134        }
135    }
136    hash
137}
138
139/// Compute the delta from `old` to `new`.
140#[must_use]
141pub fn diff(old: &WorkspaceSnapshot, new: &WorkspaceSnapshot) -> SnapshotDelta {
142    let mut delta = SnapshotDelta::default();
143    for (path, new_stat) in &new.files {
144        match old.files.get(path) {
145            None => delta.added.push(path.clone()),
146            Some(old_stat) if old_stat != new_stat => delta.changed.push(path.clone()),
147            Some(_) => {}
148        }
149    }
150    for path in old.files.keys() {
151        if !new.files.contains_key(path) {
152            delta.removed.push(path.clone());
153        }
154    }
155    delta
156}
157
158/// Whether the delta indicates meaningful environment drift.
159#[must_use]
160pub fn is_drift(delta: &SnapshotDelta) -> bool {
161    !delta.added.is_empty() || !delta.changed.is_empty() || !delta.removed.is_empty()
162}
163
164/// Persist a snapshot as JSON (e.g. as a session derived view).
165pub fn save_json(snapshot: &WorkspaceSnapshot, path: &Path) -> io::Result<()> {
166    if let Some(parent) = path.parent() {
167        std::fs::create_dir_all(parent)?;
168    }
169    let bytes = serde_json::to_vec_pretty(snapshot)
170        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
171    std::fs::write(path, bytes)
172}
173
174/// Load a previously persisted snapshot.
175pub fn load_json(path: &Path) -> io::Result<WorkspaceSnapshot> {
176    let bytes = std::fs::read(path)?;
177    serde_json::from_slice(&bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
178}
179
180fn now_rfc3339() -> String {
181    chrono::Utc::now().to_rfc3339()
182}
183
184/// Resolve the on-disk path for a session's environment snapshot.
185#[must_use]
186pub fn snapshot_path(session_dir: &Path) -> PathBuf {
187    session_dir.join("derived").join("workspace_snapshot.json")
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn capture_and_diff_detects_changes() {
196        let tmp = std::env::temp_dir().join(format!("vtcode-snap-{}", std::process::id()));
197        let ws = tmp.join("ws");
198        std::fs::create_dir_all(&ws).unwrap();
199        std::fs::write(ws.join("a.txt"), b"hello").unwrap();
200        std::fs::write(ws.join("b.txt"), b"world").unwrap();
201
202        let snap1 = capture(&ws, 1_000_000).unwrap();
203        assert_eq!(snap1.files.len(), 2);
204        assert!(snap1.files.contains_key("a.txt"));
205        assert!(snap1.files.contains_key("b.txt"));
206
207        // Mutate + add + remove.
208        std::fs::write(ws.join("a.txt"), b"changed").unwrap();
209        std::fs::write(ws.join("c.txt"), b"new").unwrap();
210        std::fs::remove_file(ws.join("b.txt")).unwrap();
211
212        let snap2 = capture(&ws, 1_000_000).unwrap();
213        let delta = diff(&snap1, &snap2);
214        assert_eq!(delta.added, vec!["c.txt".to_string()]);
215        assert_eq!(delta.changed, vec!["a.txt".to_string()]);
216        assert_eq!(delta.removed, vec!["b.txt".to_string()]);
217        assert!(is_drift(&delta));
218        let _ = std::fs::remove_dir_all(&tmp);
219    }
220
221    #[test]
222    fn json_round_trips() {
223        let tmp = std::env::temp_dir().join(format!("vtcode-snap-json-{}", std::process::id()));
224        let path = tmp.join("snap.json");
225        let snap = WorkspaceSnapshot {
226            files: {
227                let mut m = BTreeMap::new();
228                m.insert("x.rs".to_string(), FileStat { size: 3, mtime_ns: 42, head_hash: 7 });
229                m
230            },
231            captured_at: "2026-01-01T00:00:00Z".to_string(),
232        };
233        save_json(&snap, &path).unwrap();
234        let loaded = load_json(&path).unwrap();
235        assert_eq!(loaded, snap);
236        let _ = std::fs::remove_dir_all(&tmp);
237    }
238}