Skip to main content

winx_code_agent/state/
persistence.rs

1//! Bash state persistence module
2//!
3//! Provides disk persistence for `BashState`, compatible with WCGW Python implementation.
4//! State is stored in `~/.local/share/wcgw/bash_state/` as JSON files.
5
6use anyhow::{Context, Result};
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::fs;
10use std::path::{Path, PathBuf};
11use tracing::{debug, error, info, warn};
12
13use crate::types::{
14    AllowedCommands, AllowedGlobs, BashCommandMode, BashMode, FileEditMode, Modes, WriteIfEmptyMode,
15};
16
17use super::bash_state::FileWhitelistData;
18
19/// Snapshot of `BashState` that can be serialized to disk
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct BashStateSnapshot {
22    pub bash_command_mode: BashCommandModeSnapshot,
23    pub file_edit_mode: FileEditModeSnapshot,
24    pub write_if_empty_mode: WriteIfEmptyModeSnapshot,
25    pub whitelist_for_overwrite: HashMap<String, FileWhitelistDataSnapshot>,
26    pub mode: String,
27    pub workspace_root: String,
28    pub chat_id: String,
29    #[serde(default, skip_serializing_if = "String::is_empty")]
30    pub cwd: String,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct BashCommandModeSnapshot {
35    pub bash_mode: String,
36    pub allowed_commands: AllowedCommandsSnapshot,
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40#[serde(untagged)]
41pub enum AllowedCommandsSnapshot {
42    All(String),
43    List(Vec<String>),
44}
45
46#[derive(Debug, Clone, Serialize, Deserialize)]
47pub struct FileEditModeSnapshot {
48    pub allowed_globs: AllowedGlobsSnapshot,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct WriteIfEmptyModeSnapshot {
53    pub allowed_globs: AllowedGlobsSnapshot,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
57#[serde(untagged)]
58pub enum AllowedGlobsSnapshot {
59    All(String),
60    List(Vec<String>),
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct FileWhitelistDataSnapshot {
65    pub file_hash: String,
66    pub line_ranges_read: Vec<(usize, usize)>,
67    pub total_lines: usize,
68}
69
70pub fn get_state_dir() -> Result<PathBuf> {
71    let home = home::home_dir().unwrap_or_else(|| {
72        warn!(
73            "$HOME is not set; persisting bash session state under /tmp \
74             (ephemeral across reboots, and shared if multiple users hit the same thread_id)"
75        );
76        PathBuf::from("/tmp")
77    });
78    let bash_state_dir = home.join(".local/share/wcgw/bash_state");
79    if !bash_state_dir.exists() {
80        fs::create_dir_all(&bash_state_dir)?;
81    }
82    Ok(bash_state_dir)
83}
84
85fn get_state_file_path(thread_id: &str) -> Result<PathBuf> {
86    Ok(get_state_dir()?.join(format!("{thread_id}_bash_state.json")))
87}
88
89/// Write `content` to `path` atomically: a uniquely-named temp file in the same
90/// directory, renamed over the target. A reader (or a concurrent writer for the
91/// same `thread_id`) sees either the complete old file or the complete new one —
92/// never a half-written, un-parseable JSON.
93///
94/// No `fsync`: `persist_state` runs several times per tool call, and a per-write
95/// fsync would add real latency there. The atomic rename already prevents torn
96/// writes; we trade only durability-against-power-loss, which is fine for
97/// resumable session state.
98fn atomic_write(path: &Path, content: &[u8]) -> Result<()> {
99    use std::io::Write;
100    let parent =
101        path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
102    let mut tmp = tempfile::Builder::new()
103        .prefix(".winx-state-")
104        .tempfile_in(parent)
105        .with_context(|| format!("create temp state file in {}", parent.display()))?;
106    tmp.write_all(content)?;
107    tmp.persist(path).map_err(|e| e.error)?;
108    Ok(())
109}
110
111/// Parse a state snapshot, quarantining the file on corruption.
112///
113/// A corrupt state file must not silently re-fail every boot. We move it aside to
114/// `<name>.corrupt`, log loudly (the saved session — including its security mode —
115/// is gone), and return the parse error. Callers currently treat that as "no
116/// saved state"; the loud log makes the loss visible instead of silent.
117fn parse_state_or_quarantine(path: &Path, json: &str) -> Result<BashStateSnapshot> {
118    match serde_json::from_str(json) {
119        Ok(snapshot) => Ok(snapshot),
120        Err(parse_err) => {
121            let quarantine = path.with_extension("json.corrupt");
122            match fs::rename(path, &quarantine) {
123                Ok(()) => error!(
124                    path = %path.display(),
125                    quarantine = %quarantine.display(),
126                    "corrupt bash state quarantined; saved session (incl. its mode) lost: {parse_err}"
127                ),
128                Err(rename_err) => warn!(
129                    path = %path.display(),
130                    "failed to quarantine corrupt bash state: {rename_err}"
131                ),
132            }
133            Err(parse_err).context("parsing persisted bash state")
134        }
135    }
136}
137
138pub fn save_bash_state(thread_id: &str, state: &BashStateSnapshot) -> Result<()> {
139    if thread_id.is_empty() {
140        return Ok(());
141    }
142    let json = serde_json::to_string_pretty(state)?;
143    atomic_write(&get_state_file_path(thread_id)?, json.as_bytes())?;
144    Ok(())
145}
146
147pub fn save_bash_state_to_path(path: &Path, state: &BashStateSnapshot) -> Result<()> {
148    let json = serde_json::to_string_pretty(state)?;
149    atomic_write(path, json.as_bytes())?;
150    Ok(())
151}
152
153pub fn load_bash_state(thread_id: &str) -> Result<Option<BashStateSnapshot>> {
154    if thread_id.is_empty() {
155        return Ok(None);
156    }
157    let path = get_state_file_path(thread_id)?;
158    if !path.exists() {
159        return Ok(None);
160    }
161    let json = fs::read_to_string(&path)?;
162    Ok(Some(parse_state_or_quarantine(&path, &json)?))
163}
164
165pub fn load_bash_state_from_path(path: &Path) -> Result<Option<BashStateSnapshot>> {
166    if !path.exists() {
167        return Ok(None);
168    }
169    let json = fs::read_to_string(path)?;
170    Ok(Some(parse_state_or_quarantine(path, &json)?))
171}
172
173pub fn delete_bash_state(thread_id: &str) -> Result<()> {
174    if thread_id.is_empty() {
175        return Ok(());
176    }
177    let path = get_state_file_path(thread_id)?;
178    if path.exists() {
179        fs::remove_file(path)?;
180    }
181    Ok(())
182}
183
184impl BashStateSnapshot {
185    pub fn from_state(
186        cwd: &str,
187        workspace_root: &str,
188        mode: &Modes,
189        bash_command_mode: &BashCommandMode,
190        file_edit_mode: &FileEditMode,
191        write_if_empty_mode: &WriteIfEmptyMode,
192        whitelist: &HashMap<String, FileWhitelistData>,
193        thread_id: &str,
194    ) -> Self {
195        Self {
196            bash_command_mode: BashCommandModeSnapshot::from(bash_command_mode),
197            file_edit_mode: FileEditModeSnapshot::from(file_edit_mode),
198            write_if_empty_mode: WriteIfEmptyModeSnapshot::from(write_if_empty_mode),
199            whitelist_for_overwrite: whitelist
200                .iter()
201                .map(|(k, v)| (k.clone(), FileWhitelistDataSnapshot::from(v)))
202                .collect(),
203            mode: mode.to_string(),
204            workspace_root: workspace_root.to_string(),
205            chat_id: thread_id.to_string(),
206            cwd: if cwd == workspace_root { String::new() } else { cwd.to_string() },
207        }
208    }
209
210    pub fn to_state_components(
211        &self,
212    ) -> (
213        String,
214        String,
215        Modes,
216        BashCommandMode,
217        FileEditMode,
218        WriteIfEmptyMode,
219        HashMap<String, FileWhitelistData>,
220        String,
221    ) {
222        let mode = match self.mode.as_str() {
223            "architect" => Modes::Architect,
224            "code_writer" => Modes::CodeWriter,
225            _ => Modes::Wcgw,
226        };
227        let whitelist = self
228            .whitelist_for_overwrite
229            .iter()
230            .map(|(k, v)| (k.clone(), v.to_whitelist_data()))
231            .collect();
232        let cwd = if self.cwd.is_empty() { self.workspace_root.clone() } else { self.cwd.clone() };
233        (
234            cwd,
235            self.workspace_root.clone(),
236            mode,
237            self.bash_command_mode.to_bash_command_mode(),
238            self.file_edit_mode.to_file_edit_mode(),
239            self.write_if_empty_mode.to_write_if_empty_mode(),
240            whitelist,
241            self.chat_id.clone(),
242        )
243    }
244}
245
246impl From<&BashCommandMode> for BashCommandModeSnapshot {
247    fn from(mode: &BashCommandMode) -> Self {
248        Self {
249            bash_mode: match mode.bash_mode {
250                BashMode::RestrictedMode => "restricted_mode".to_string(),
251                BashMode::NormalMode => "normal_mode".to_string(),
252            },
253            allowed_commands: match &mode.allowed_commands {
254                AllowedCommands::All(s) => AllowedCommandsSnapshot::All(s.clone()),
255                AllowedCommands::List(l) => AllowedCommandsSnapshot::List(l.clone()),
256            },
257        }
258    }
259}
260
261impl BashCommandModeSnapshot {
262    fn to_bash_command_mode(&self) -> BashCommandMode {
263        BashCommandMode {
264            bash_mode: if self.bash_mode == "restricted_mode" {
265                BashMode::RestrictedMode
266            } else {
267                BashMode::NormalMode
268            },
269            allowed_commands: match &self.allowed_commands {
270                AllowedCommandsSnapshot::All(s) => AllowedCommands::All(s.clone()),
271                AllowedCommandsSnapshot::List(l) => AllowedCommands::List(l.clone()),
272            },
273        }
274    }
275}
276
277impl From<&FileEditMode> for FileEditModeSnapshot {
278    fn from(mode: &FileEditMode) -> Self {
279        Self {
280            allowed_globs: match &mode.allowed_globs {
281                AllowedGlobs::All(s) => AllowedGlobsSnapshot::All(s.clone()),
282                AllowedGlobs::List(l) => AllowedGlobsSnapshot::List(l.clone()),
283            },
284        }
285    }
286}
287
288impl FileEditModeSnapshot {
289    fn to_file_edit_mode(&self) -> FileEditMode {
290        FileEditMode {
291            allowed_globs: match &self.allowed_globs {
292                AllowedGlobsSnapshot::All(s) => AllowedGlobs::All(s.clone()),
293                AllowedGlobsSnapshot::List(l) => AllowedGlobs::List(l.clone()),
294            },
295        }
296    }
297}
298
299impl From<&WriteIfEmptyMode> for WriteIfEmptyModeSnapshot {
300    fn from(mode: &WriteIfEmptyMode) -> Self {
301        Self {
302            allowed_globs: match &mode.allowed_globs {
303                AllowedGlobs::All(s) => AllowedGlobsSnapshot::All(s.clone()),
304                AllowedGlobs::List(l) => AllowedGlobsSnapshot::List(l.clone()),
305            },
306        }
307    }
308}
309
310impl WriteIfEmptyModeSnapshot {
311    fn to_write_if_empty_mode(&self) -> WriteIfEmptyMode {
312        WriteIfEmptyMode {
313            allowed_globs: match &self.allowed_globs {
314                AllowedGlobsSnapshot::All(s) => AllowedGlobs::All(s.clone()),
315                AllowedGlobsSnapshot::List(l) => AllowedGlobs::List(l.clone()),
316            },
317        }
318    }
319}
320
321impl From<&FileWhitelistData> for FileWhitelistDataSnapshot {
322    fn from(d: &FileWhitelistData) -> Self {
323        Self {
324            file_hash: d.file_hash.clone(),
325            line_ranges_read: d.line_ranges_read.clone(),
326            total_lines: d.total_lines,
327        }
328    }
329}
330
331impl FileWhitelistDataSnapshot {
332    fn to_whitelist_data(&self) -> FileWhitelistData {
333        FileWhitelistData {
334            file_hash: self.file_hash.clone(),
335            line_ranges_read: self.line_ranges_read.clone(),
336            total_lines: self.total_lines,
337        }
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use super::{atomic_write, load_bash_state_from_path};
344    use anyhow::Result;
345
346    #[test]
347    fn atomic_write_round_trips_and_replaces() -> Result<()> {
348        let dir = tempfile::tempdir()?;
349        let path = dir.path().join("data.bin");
350        atomic_write(&path, b"hello atomic")?;
351        assert_eq!(std::fs::read(&path)?, b"hello atomic");
352        // Overwriting is also atomic and leaves a single clean file.
353        atomic_write(&path, b"second")?;
354        assert_eq!(std::fs::read(&path)?, b"second");
355        Ok(())
356    }
357
358    #[test]
359    fn missing_state_file_is_ok_none() -> Result<()> {
360        let dir = tempfile::tempdir()?;
361        let path = dir.path().join("absent_bash_state.json");
362        assert!(load_bash_state_from_path(&path)?.is_none());
363        Ok(())
364    }
365
366    #[test]
367    fn corrupt_state_is_quarantined_and_surfaces_error() -> Result<()> {
368        let dir = tempfile::tempdir()?;
369        let path = dir.path().join("t1_bash_state.json");
370        std::fs::write(&path, "{ not valid json ")?;
371        // Corruption must NOT degrade into Ok(None) (a silent fresh session).
372        assert!(load_bash_state_from_path(&path).is_err());
373        // The bad file is moved aside so it doesn't re-fail every boot.
374        assert!(!path.exists(), "corrupt file should be quarantined");
375        assert!(path.with_extension("json.corrupt").exists(), "quarantine file should exist");
376        Ok(())
377    }
378}