Skip to main content

vtcode_core/
loop_memory.rs

1//! Loop memory store for durable loop-engineering state.
2//!
3//! The loop memory store provides append-only markdown files that the agent
4//! writes during a loop run and reads on the next iteration. This is the
5//! "memory" primitive from Osmani's loop engineering pattern:
6//!
7//! > "The agent forgets, the repo doesn't."
8//!
9//! The default implementation writes to `{workspace}/.vtcode/state/notes.md`
10//! and `{workspace}/.vtcode/state/decisions.md`.
11
12use anyhow::{Context, Result};
13use std::fs::{self, OpenOptions};
14use std::io::Write;
15use std::path::{Path, PathBuf};
16
17use crate::loop_state::state_dir;
18
19const NOTES_FILENAME: &str = "notes.md";
20const DECISIONS_FILENAME: &str = "decisions.md";
21
22// ─── Trait ───────────────────────────────────────────────────────────────────
23
24/// A trait for persisting loop-level memory across runs. Implementations may
25/// store notes and decisions in markdown, a database, or any other durable form.
26pub trait LoopMemoryStore: Send + Sync {
27    /// Read all accumulated notes.
28    fn read_notes(&self) -> Result<String>;
29
30    /// Append a note. Notes are agent-written, human-readable, append-only.
31    fn write_note(&self, note: &str) -> Result<()>;
32
33    /// Read all accumulated decisions.
34    fn read_decisions(&self) -> Result<String>;
35
36    /// Append a decision entry. Decisions are the agent's choices that should
37    /// survive across loop iterations.
38    fn write_decision(&self, decision: &str) -> Result<()>;
39}
40
41// ─── Markdown Implementation ─────────────────────────────────────────────────
42
43/// Markdown-backed loop memory store. Writes to `.vtcode/state/notes.md` and
44/// `.vtcode/state/decisions.md` under the workspace root.
45pub struct MarkdownLoopMemory {
46    notes_path: PathBuf,
47    decisions_path: PathBuf,
48}
49
50impl MarkdownLoopMemory {
51    /// Create a new markdown loop memory store for the given workspace.
52    pub fn new(workspace_root: &Path) -> Self {
53        let dir = state_dir(workspace_root);
54        Self {
55            notes_path: dir.join(NOTES_FILENAME),
56            decisions_path: dir.join(DECISIONS_FILENAME),
57        }
58    }
59
60    /// Create a new markdown loop memory store with explicit paths (for testing).
61    pub fn with_paths(notes_path: PathBuf, decisions_path: PathBuf) -> Self {
62        Self { notes_path, decisions_path }
63    }
64}
65
66impl LoopMemoryStore for MarkdownLoopMemory {
67    fn read_notes(&self) -> Result<String> {
68        read_markdown_file(&self.notes_path)
69    }
70
71    fn write_note(&self, note: &str) -> Result<()> {
72        append_markdown_entry(&self.notes_path, note, "# Loop Notes\n\n")
73    }
74
75    fn read_decisions(&self) -> Result<String> {
76        read_markdown_file(&self.decisions_path)
77    }
78
79    fn write_decision(&self, decision: &str) -> Result<()> {
80        append_markdown_entry(&self.decisions_path, decision, "# Loop Decisions\n\n")
81    }
82}
83
84// ─── Helpers ─────────────────────────────────────────────────────────────────
85
86fn read_markdown_file(path: &Path) -> Result<String> {
87    if !path.exists() {
88        return Ok(String::new());
89    }
90    fs::read_to_string(path).with_context(|| format!("Failed to read {}", path.display()))
91}
92
93fn append_markdown_entry(path: &Path, content: &str, header: &str) -> Result<()> {
94    let trimmed = content.trim();
95    if trimmed.is_empty() {
96        return Ok(());
97    }
98
99    if let Some(parent) = path.parent() {
100        fs::create_dir_all(parent).with_context(|| format!("Failed to create directory {}", parent.display()))?;
101    }
102
103    let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
104    let entry = format!("- [{timestamp}] {trimmed}\n");
105
106    // Open a single file handle with read+append+create to avoid TOCTOU race
107    // between checking whether the header exists and writing the entry.
108    let mut file = OpenOptions::new()
109        .read(true)
110        .create(true)
111        .append(true)
112        .open(path)
113        .with_context(|| format!("Failed to open {} for appending", path.display()))?;
114
115    // Check if the file is empty (needs a header) using the same handle.
116    let needs_header = {
117        let metadata = file.metadata().with_context(|| format!("Failed to stat {}", path.display()))?;
118        metadata.len() == 0
119    };
120
121    if needs_header {
122        file.write_all(header.as_bytes())
123            .with_context(|| format!("Failed to write header to {}", path.display()))?;
124    }
125
126    file.write_all(entry.as_bytes())
127        .with_context(|| format!("Failed to append to {}", path.display()))?;
128    Ok(())
129}
130
131// ─── Sqlite Implementation ───────────────────────────────────────────────────
132
133/// Sqlite-backed loop memory store for faster queries. Enabled behind the
134/// `sqlite` feature flag. Stores notes and decisions in a single database
135/// file under `.vtcode/state/loop_memory.db`.
136#[cfg(feature = "sqlite")]
137pub struct SqliteLoopMemory {
138    conn: std::sync::Mutex<rusqlite::Connection>,
139}
140
141#[cfg(feature = "sqlite")]
142impl SqliteLoopMemory {
143    /// Create a new sqlite loop memory store for the given workspace.
144    pub fn new(workspace_root: &Path) -> Result<Self> {
145        let dir = state_dir(workspace_root);
146        let db_path = dir.join("loop_memory.db");
147        Self::from_path(db_path)
148    }
149
150    /// Create with an explicit database path (for testing).
151    pub fn with_path(db_path: PathBuf) -> Result<Self> {
152        Self::from_path(db_path)
153    }
154
155    fn from_path(db_path: PathBuf) -> Result<Self> {
156        let conn = rusqlite::Connection::open(&db_path)?;
157        // A second vtcode process on the same workspace must wait out a
158        // writer instead of failing immediately with `SQLITE_BUSY`.
159        conn.busy_timeout(std::time::Duration::from_secs(5))?;
160        conn.execute_batch(
161            "CREATE TABLE IF NOT EXISTS notes (
162                id INTEGER PRIMARY KEY AUTOINCREMENT,
163                timestamp TEXT NOT NULL,
164                content TEXT NOT NULL
165            );
166            CREATE TABLE IF NOT EXISTS decisions (
167                id INTEGER PRIMARY KEY AUTOINCREMENT,
168                timestamp TEXT NOT NULL,
169                content TEXT NOT NULL
170            );",
171        )?;
172        Ok(Self { conn: std::sync::Mutex::new(conn) })
173    }
174}
175
176#[cfg(feature = "sqlite")]
177impl LoopMemoryStore for SqliteLoopMemory {
178    fn read_notes(&self) -> Result<String> {
179        let conn = self.conn.lock().map_err(|e| anyhow::anyhow!("Lock poisoned: {e}"))?;
180        let mut stmt = conn.prepare("SELECT timestamp, content FROM notes ORDER BY id")?;
181        let rows = stmt.query_map([], |row| {
182            let ts: String = row.get(0)?;
183            let content: String = row.get(1)?;
184            Ok(format!("- [{ts}] {content}"))
185        })?;
186
187        let entries: Vec<String> = rows.collect::<Result<Vec<_>, _>>()?;
188        // Match Markdown behavior: return empty string when no entries exist.
189        if entries.is_empty() {
190            return Ok(String::new());
191        }
192        let mut output = String::from("# Loop Notes\n\n");
193        for entry in entries {
194            output.push_str(&entry);
195            output.push('\n');
196        }
197        Ok(output)
198    }
199
200    fn write_note(&self, note: &str) -> Result<()> {
201        let trimmed = note.trim();
202        if trimmed.is_empty() {
203            return Ok(());
204        }
205        let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
206        let conn = self.conn.lock().map_err(|e| anyhow::anyhow!("Lock poisoned: {e}"))?;
207        conn.execute(
208            "INSERT INTO notes (timestamp, content) VALUES (?1, ?2)",
209            rusqlite::params![timestamp.to_string(), trimmed],
210        )?;
211        Ok(())
212    }
213
214    fn read_decisions(&self) -> Result<String> {
215        let conn = self.conn.lock().map_err(|e| anyhow::anyhow!("Lock poisoned: {e}"))?;
216        let mut stmt = conn.prepare("SELECT timestamp, content FROM decisions ORDER BY id")?;
217        let rows = stmt.query_map([], |row| {
218            let ts: String = row.get(0)?;
219            let content: String = row.get(1)?;
220            Ok(format!("- [{ts}] {content}"))
221        })?;
222
223        let entries: Vec<String> = rows.collect::<Result<Vec<_>, _>>()?;
224        if entries.is_empty() {
225            return Ok(String::new());
226        }
227        let mut output = String::from("# Loop Decisions\n\n");
228        for entry in entries {
229            output.push_str(&entry);
230            output.push('\n');
231        }
232        Ok(output)
233    }
234
235    fn write_decision(&self, decision: &str) -> Result<()> {
236        let trimmed = decision.trim();
237        if trimmed.is_empty() {
238            return Ok(());
239        }
240        let timestamp = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");
241        let conn = self.conn.lock().map_err(|e| anyhow::anyhow!("Lock poisoned: {e}"))?;
242        conn.execute(
243            "INSERT INTO decisions (timestamp, content) VALUES (?1, ?2)",
244            rusqlite::params![timestamp.to_string(), trimmed],
245        )?;
246        Ok(())
247    }
248}
249
250// ─── Tests ───────────────────────────────────────────────────────────────────
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use tempfile::TempDir;
256
257    #[test]
258    fn markdown_memory_read_empty_when_no_files() {
259        let tmp = TempDir::new().expect("temp dir");
260        let memory = MarkdownLoopMemory::new(tmp.path());
261        assert_eq!(memory.read_notes().expect("read"), "");
262        assert_eq!(memory.read_decisions().expect("read"), "");
263    }
264
265    #[test]
266    fn markdown_memory_write_and_read_notes() {
267        let tmp = TempDir::new().expect("temp dir");
268        let memory = MarkdownLoopMemory::new(tmp.path());
269
270        memory.write_note("First observation").expect("write");
271        memory.write_note("Second observation").expect("write");
272
273        let notes = memory.read_notes().expect("read");
274        assert!(notes.contains("First observation"));
275        assert!(notes.contains("Second observation"));
276        assert!(notes.starts_with("# Loop Notes"));
277    }
278
279    #[test]
280    fn markdown_memory_write_and_read_decisions() {
281        let tmp = TempDir::new().expect("temp dir");
282        let memory = MarkdownLoopMemory::new(tmp.path());
283
284        memory.write_decision("Use retry with backoff").expect("write");
285        memory.write_decision("Skip tests for now").expect("write");
286
287        let decisions = memory.read_decisions().expect("read");
288        assert!(decisions.contains("Use retry with backoff"));
289        assert!(decisions.contains("Skip tests for now"));
290        assert!(decisions.starts_with("# Loop Decisions"));
291    }
292
293    #[test]
294    fn markdown_memory_ignores_empty_entries() {
295        let tmp = TempDir::new().expect("temp dir");
296        let memory = MarkdownLoopMemory::new(tmp.path());
297
298        memory.write_note("").expect("write");
299        memory.write_note("   ").expect("write");
300
301        let notes = memory.read_notes().expect("read");
302        assert_eq!(notes, "");
303    }
304
305    #[test]
306    fn markdown_memory_entries_are_timestamped() {
307        let tmp = TempDir::new().expect("temp dir");
308        let notes_path = tmp.path().join("notes.md");
309        let decisions_path = tmp.path().join("decisions.md");
310        let memory = MarkdownLoopMemory::with_paths(notes_path.clone(), decisions_path);
311
312        memory.write_note("test entry").expect("write");
313
314        let content = fs::read_to_string(&notes_path).expect("read");
315        // Should contain a timestamp in [YYYY-MM-DDTHH:MM:SSZ] format
316        assert!(content.contains("[20"));
317        assert!(content.contains("] test entry"));
318    }
319
320    #[test]
321    fn markdown_memory_append_is_durable() {
322        let tmp = TempDir::new().expect("temp dir");
323        let notes_path = tmp.path().join("notes.md");
324        let decisions_path = tmp.path().join("decisions.md");
325
326        {
327            let memory = MarkdownLoopMemory::with_paths(notes_path.clone(), decisions_path.clone());
328            memory.write_note("first run note").expect("write");
329        }
330        // Simulate a new run (drop and recreate)
331        {
332            let memory = MarkdownLoopMemory::with_paths(notes_path, decisions_path);
333            memory.write_note("second run note").expect("write");
334            let notes = memory.read_notes().expect("read");
335            assert!(notes.contains("first run note"));
336            assert!(notes.contains("second run note"));
337        }
338    }
339
340    #[cfg(feature = "sqlite")]
341    mod sqlite_tests {
342        use super::super::*;
343        use tempfile::TempDir;
344
345        #[test]
346        fn sqlite_memory_read_empty_when_no_data() {
347            let tmp = TempDir::new().expect("temp dir");
348            let db_path = tmp.path().join("test.db");
349            let memory = SqliteLoopMemory::with_path(db_path).expect("create");
350            // Empty state matches Markdown behavior: returns empty string.
351            assert_eq!(memory.read_notes().expect("read"), "");
352            assert_eq!(memory.read_decisions().expect("read"), "");
353        }
354
355        #[test]
356        fn sqlite_memory_write_and_read_notes() {
357            let tmp = TempDir::new().expect("temp dir");
358            let db_path = tmp.path().join("test.db");
359            let memory = SqliteLoopMemory::with_path(db_path).expect("create");
360
361            memory.write_note("First observation").expect("write");
362            memory.write_note("Second observation").expect("write");
363
364            let notes = memory.read_notes().expect("read");
365            assert!(notes.contains("First observation"));
366            assert!(notes.contains("Second observation"));
367            assert!(notes.starts_with("# Loop Notes"));
368        }
369
370        #[test]
371        fn sqlite_memory_write_and_read_decisions() {
372            let tmp = TempDir::new().expect("temp dir");
373            let db_path = tmp.path().join("test.db");
374            let memory = SqliteLoopMemory::with_path(db_path).expect("create");
375
376            memory.write_decision("Use retry with backoff").expect("write");
377            memory.write_decision("Skip tests for now").expect("write");
378
379            let decisions = memory.read_decisions().expect("read");
380            assert!(decisions.contains("Use retry with backoff"));
381            assert!(decisions.contains("Skip tests for now"));
382            assert!(decisions.starts_with("# Loop Decisions"));
383        }
384
385        #[test]
386        fn sqlite_memory_ignores_empty_entries() {
387            let tmp = TempDir::new().expect("temp dir");
388            let db_path = tmp.path().join("test.db");
389            let memory = SqliteLoopMemory::with_path(db_path).expect("create");
390
391            memory.write_note("").expect("write");
392            memory.write_note("   ").expect("write");
393
394            let notes = memory.read_notes().expect("read");
395            // Empty entries are skipped, so the result is empty (no rows).
396            assert_eq!(notes, "");
397        }
398
399        #[test]
400        fn sqlite_memory_survives_reopen() {
401            let tmp = TempDir::new().expect("temp dir");
402            let db_path = tmp.path().join("test.db");
403
404            {
405                let memory = SqliteLoopMemory::with_path(db_path.clone()).expect("create");
406                memory.write_note("first run note").expect("write");
407            }
408            {
409                let memory = SqliteLoopMemory::with_path(db_path).expect("reopen");
410                memory.write_note("second run note").expect("write");
411                let notes = memory.read_notes().expect("read");
412                assert!(notes.contains("first run note"));
413                assert!(notes.contains("second run note"));
414            }
415        }
416
417        #[test]
418        fn sqlite_memory_waits_out_a_concurrent_writer() {
419            let tmp = TempDir::new().expect("temp dir");
420            let db_path = tmp.path().join("test.db");
421            let memory = SqliteLoopMemory::with_path(db_path.clone()).expect("create");
422
423            // A second connection holds an open write transaction, simulating
424            // another vtcode process mid-write on the same workspace database.
425            let holder = rusqlite::Connection::open(&db_path).expect("second connection");
426            holder
427                .execute_batch("BEGIN IMMEDIATE; INSERT INTO notes (timestamp, content) VALUES ('held', 'held');")
428                .expect("hold write lock");
429
430            // Without `busy_timeout` this fails immediately with SQLITE_BUSY;
431            // with it, the write waits for the holder to commit.
432            let writer = std::thread::spawn(move || {
433                memory.write_note("after concurrent writer").expect("write waits out the lock");
434            });
435            std::thread::sleep(std::time::Duration::from_millis(200));
436            holder.execute_batch("COMMIT;").expect("release write lock");
437            writer.join().expect("writer thread");
438
439            let memory = SqliteLoopMemory::with_path(db_path).expect("reopen");
440            assert!(memory.read_notes().expect("read").contains("after concurrent writer"));
441        }
442    }
443}