Skip to main content

vtcode_memory/
lib.rs

1#![allow(
2    dead_code,
3    unused_imports,
4    reason = "Intentional compatibility, platform, or test-only suppression."
5)]
6#![expect(
7    unused_results,
8    clippy::let_underscore_must_use,
9    clippy::cast_possible_truncation,
10    clippy::cast_possible_wrap,
11    clippy::string_slice,
12    reason = "The memory store uses compact persisted counters, bounded timestamp conversions, and side-effect-only index maintenance."
13)]
14//! Unified per-session state store for VT Code.
15//!
16//! This crate is the single source of truth for an agent session's state,
17//! context, and history. Each session is persisted under
18//! `.vtcode/sessions/<session_id>/` as:
19//!
20//! - `events.jsonl` — the canonical append-only [`ThreadEvent`](vtcode_exec_events::ThreadEvent)
21//!   log (schema-versioned). Everything else is derived from this.
22//! - `manifest.json` — session metadata and counters.
23//! - `index/turns.json` — byte-offset index enabling O(1) turn reconstruction.
24//! - `derived/` — regenerated views (`trajectory.jsonl`, `memory.json`, …).
25//!
26//! The store is intentionally append-only and off the agent's hot path: the
27//! live conversation stays in memory and is never reloaded from disk into
28//! context. Reads happen only for revert, compaction, analytics, and
29//! long-term-learning queries.
30
31pub mod error;
32pub mod event_log;
33/// Manifest and turn-index persistence helpers.
34pub mod manifest;
35pub mod migration;
36/// Digest-verified audit packs for sessions.
37pub mod pack;
38pub mod progress;
39pub mod query;
40pub mod retention;
41
42pub use error::SessionStoreError;
43pub use event_log::{
44    DEFAULT_MAX_EVENTS, EvictionSummaryHook, SessionEventLog, SessionManifest, TurnIndex, TurnIndexEntry,
45};
46pub use migration::{MigrationReport, migrate_legacy};
47pub use pack::{
48    AUDIT_PACK_SCHEMA_VERSION, AuditPackEntry, AuditVerification, SessionAuditPack, audit_pack_path, create_audit_pack,
49    read_audit_pack, verify_audit_pack, write_audit_pack,
50};
51pub use progress::{
52    GoalClassifierVerdict, GoalEvent, GoalHistoryEntry, GoalOrchestration, GoalPauseReason, GoalPhase, GoalStatus,
53    GoalTracker, Milestone, MilestoneStatus, ProgressLedger, load_progress, progress_path, save_progress,
54};
55pub use query::{
56    FactRecord, MemorySearchResult, SessionMemoryView, SessionSummary, query_facts, recent_sessions, search_memory,
57    session_memory_facts, write_session_memory_view,
58};
59pub use retention::{RetentionPolicy, apply_retention, apply_retention_preserving, gc_legacy};
60
61use std::path::{Path, PathBuf};
62
63/// Directory (relative to the workspace) holding all per-session stores.
64const SESSIONS_DIR: &str = ".vtcode/sessions";
65
66/// Sub-directory inside a session holding regenerated views.
67const DERIVED_DIR: &str = "derived";
68
69/// Schema version for the on-disk session store layout.
70const SESSION_STORE_SCHEMA_VERSION: u32 = 1;
71
72/// Resolve the sessions root directory for a workspace.
73#[must_use]
74pub(crate) fn sessions_root(workspace: &Path) -> PathBuf {
75    workspace.join(SESSIONS_DIR)
76}
77
78/// Resolve the directory for a single session.
79#[must_use]
80pub(crate) fn session_dir(workspace: &Path, session_id: &str) -> PathBuf {
81    sessions_root(workspace).join(sanitize_id(session_id))
82}
83
84/// Return the canonical directory for a session.
85///
86/// Derived exporters and diagnostics must live beneath this directory so the
87/// session store remains the single persistence root for interactive and exec
88/// sessions.
89#[must_use]
90pub fn session_directory(workspace: &Path, session_id: &str) -> PathBuf {
91    session_dir(workspace, session_id)
92}
93
94/// Open (creating if necessary) the event log for a session.
95///
96/// This is the canonical entry point for recording a session's events. Multiple
97/// handles opened for the same session share an `Arc`-backed file and state,
98/// allowing concurrent `append` calls from the runloop's event sink to use one
99/// coordinated turn index.
100pub fn open(workspace: &Path, session_id: &str, max_events: usize) -> Result<SessionEventLog, SessionStoreError> {
101    SessionEventLog::open(workspace, session_id, max_events)
102}
103
104/// Open a session log with a callback that persists summaries before cap
105/// eviction. A callback failure leaves the canonical event log unchanged.
106pub fn open_with_eviction_summary(
107    workspace: &Path,
108    session_id: &str,
109    max_events: usize,
110    eviction_summary_hook: EvictionSummaryHook,
111) -> Result<SessionEventLog, SessionStoreError> {
112    SessionEventLog::open_with_eviction_summary(workspace, session_id, max_events, eviction_summary_hook)
113}
114
115/// Ensure a session-store directory exists with private permissions.
116pub(crate) fn ensure_private_directory(path: &Path) -> Result<(), SessionStoreError> {
117    vtcode_commons::VtCodePaths::ensure_user_dir(path).map_err(|error| SessionStoreError::CreateDir {
118        path: path.to_path_buf(),
119        source: std::io::Error::other(error),
120    })?;
121
122    #[cfg(unix)]
123    {
124        use std::os::unix::fs::PermissionsExt;
125
126        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
127            .map_err(|error| SessionStoreError::io(path.to_path_buf(), error))?;
128    }
129
130    Ok(())
131}
132
133/// Sanitize a session id so it is safe to use as a directory name.
134fn sanitize_id(id: &str) -> String {
135    let mut out = String::with_capacity(id.len());
136    for c in id.chars() {
137        if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' {
138            out.push(c);
139        } else {
140            out.push('_');
141        }
142    }
143    // Strip leading dots to avoid creating hidden directories.
144    let out = out.trim_start_matches('.').to_string();
145    if out.is_empty() { "session".to_string() } else { out }
146}
147
148#[cfg(test)]
149mod tests;