toolpath-cursor 0.2.0

Derive Toolpath provenance documents from Cursor's bubble store and agent transcripts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Filesystem layout for Cursor state.
//!
//! Cursor splits its data across two roots: an Anysphere-specific tree
//! at `~/.cursor/` (used for project slugs and the per-composer JSONL
//! agent transcript), and a VS Code-flavored Electron user-data tree
//! at `~/Library/Application Support/Cursor/` on macOS,
//! `~/.config/Cursor/` on Linux, and
//! `%APPDATA%\Cursor\` on Windows.
//!
//! The source of truth for conversations is the global SQLite database
//! at `<user-data>/User/globalStorage/state.vscdb`. The JSONL
//! transcripts are useful for fast project-keyed listing but lossy.

use crate::error::{CursorError, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Subset of `workspace.json` that Cursor (and VS Code) writes for
/// every workspace folder it's opened. We only care about the
/// `folder` URI — that's what we match on when looking up the
/// workspace id for a given on-disk folder.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct WorkspaceManifest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    folder: Option<String>,
}

/// Outcome of [`PathResolver::ensure_workspace_storage_entry`].
#[derive(Debug, Clone)]
pub struct EnsuredWorkspaceId {
    /// The 32-hex-char id Cursor will see / does see for this
    /// workspace.
    pub id: String,
    /// `true` if we created a new `workspaceStorage/<id>/workspace.json`
    /// just now (folder hadn't been opened in Cursor before).
    pub created: bool,
}

const ANYSPHERE_SUBDIR: &str = ".cursor";
const PROJECTS_SUBDIR: &str = "projects";
const AGENT_TRANSCRIPTS_SUBDIR: &str = "agent-transcripts";
const USER_SUBDIR: &str = "User";
const GLOBAL_STORAGE_SUBDIR: &str = "globalStorage";
const WORKSPACE_STORAGE_SUBDIR: &str = "workspaceStorage";
const WORKSPACE_JSON: &str = "workspace.json";
const DB_FILE: &str = "state.vscdb";

/// Builder-style resolver over Cursor's data directories.
#[derive(Debug, Clone)]
pub struct PathResolver {
    home_dir: Option<PathBuf>,
    /// Override for `~/.cursor/`.
    anysphere_dir: Option<PathBuf>,
    /// Override for the Electron user-data root
    /// (`~/Library/Application Support/Cursor/` on macOS).
    user_data_dir: Option<PathBuf>,
}

impl Default for PathResolver {
    fn default() -> Self {
        Self::new()
    }
}

impl PathResolver {
    pub fn new() -> Self {
        Self {
            home_dir: home_dir(),
            anysphere_dir: None,
            user_data_dir: None,
        }
    }

    pub fn with_home<P: Into<PathBuf>>(mut self, home: P) -> Self {
        self.home_dir = Some(home.into());
        self
    }

    /// Override `~/.cursor/` directly.
    pub fn with_anysphere_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.anysphere_dir = Some(dir.into());
        self
    }

    /// Override the Electron user-data root. On macOS this defaults
    /// to `<home>/Library/Application Support/Cursor`.
    pub fn with_user_data_dir<P: Into<PathBuf>>(mut self, dir: P) -> Self {
        self.user_data_dir = Some(dir.into());
        self
    }

    pub fn home_dir(&self) -> Result<&Path> {
        self.home_dir.as_deref().ok_or(CursorError::NoHomeDirectory)
    }

    /// Path to `~/.cursor/`.
    pub fn anysphere_dir(&self) -> Result<PathBuf> {
        if let Some(d) = &self.anysphere_dir {
            return Ok(d.clone());
        }
        Ok(self.home_dir()?.join(ANYSPHERE_SUBDIR))
    }

    /// Path to `~/.cursor/projects/`.
    pub fn projects_dir(&self) -> Result<PathBuf> {
        Ok(self.anysphere_dir()?.join(PROJECTS_SUBDIR))
    }

    /// Path to the agent-transcripts folder for a project slug.
    pub fn project_transcripts_dir(&self, slug: &str) -> Result<PathBuf> {
        Ok(self.projects_dir()?.join(slug).join(AGENT_TRANSCRIPTS_SUBDIR))
    }

    /// Path to the JSONL transcript file for a composer in a project.
    pub fn transcript_path(&self, slug: &str, composer_id: &str) -> Result<PathBuf> {
        Ok(self
            .project_transcripts_dir(slug)?
            .join(composer_id)
            .join(format!("{composer_id}.jsonl")))
    }

    /// Path to the Electron user-data root.
    pub fn user_data_dir(&self) -> Result<PathBuf> {
        if let Some(d) = &self.user_data_dir {
            return Ok(d.clone());
        }
        Ok(default_user_data_dir(self.home_dir()?))
    }

    /// Path to `<user-data>/User/`.
    pub fn user_dir(&self) -> Result<PathBuf> {
        Ok(self.user_data_dir()?.join(USER_SUBDIR))
    }

    /// Path to `<user-data>/User/globalStorage/`.
    pub fn global_storage_dir(&self) -> Result<PathBuf> {
        Ok(self.user_dir()?.join(GLOBAL_STORAGE_SUBDIR))
    }

    /// Path to the primary cross-workspace SQLite database
    /// (`<user-data>/User/globalStorage/state.vscdb`).
    pub fn db_path(&self) -> Result<PathBuf> {
        Ok(self.global_storage_dir()?.join(DB_FILE))
    }

    /// Path to `<user-data>/User/workspaceStorage/`. Cursor stores
    /// one subdirectory per workspace folder it's been opened
    /// against, named by the workspace id (an opaque 32-hex-char
    /// hash Cursor computes from the folder URI). Each subdir
    /// contains a `workspace.json` with the canonical `folder` URI
    /// that subdir is bound to.
    pub fn workspace_storage_dir(&self) -> Result<PathBuf> {
        Ok(self.user_dir()?.join(WORKSPACE_STORAGE_SUBDIR))
    }

    /// Look up Cursor's workspace id for a given folder, if it has
    /// been opened in Cursor.app before. Scans every
    /// `workspaceStorage/<id>/workspace.json`, returning the `<id>`
    /// whose recorded `folder` URI canonicalizes to `folder`.
    ///
    /// Returns `Ok(None)` when the folder hasn't been opened yet —
    /// the caller can decide whether to synthesize one via
    /// [`Self::ensure_workspace_storage_entry`].
    pub fn find_workspace_id(&self, folder: &Path) -> Result<Option<String>> {
        let storage_root = match self.workspace_storage_dir() {
            Ok(p) => p,
            Err(_) => return Ok(None),
        };
        if !storage_root.exists() {
            return Ok(None);
        }
        let target = std::fs::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf());

        for entry in std::fs::read_dir(&storage_root)? {
            let entry = entry?;
            if !entry.file_type()?.is_dir() {
                continue;
            }
            let manifest = entry.path().join(WORKSPACE_JSON);
            let Ok(raw) = std::fs::read_to_string(&manifest) else {
                continue;
            };
            let Ok(parsed) = serde_json::from_str::<WorkspaceManifest>(&raw) else {
                continue;
            };
            let Some(folder_uri) = parsed.folder.as_deref() else {
                continue;
            };
            let Some(path_part) = folder_uri.strip_prefix("file://") else {
                continue;
            };
            let recorded = std::fs::canonicalize(path_part)
                .unwrap_or_else(|_| PathBuf::from(path_part));
            if recorded == target {
                let id = entry
                    .file_name()
                    .to_string_lossy()
                    .into_owned();
                return Ok(Some(id));
            }
        }
        Ok(None)
    }

    /// Look up the workspace id for `folder`; if none exists, create
    /// `workspaceStorage/<synthesized-id>/workspace.json` recording
    /// the folder URI and return the synthesized id. The next time
    /// Cursor.app opens that folder it'll scan workspaceStorage,
    /// match by URI, and adopt our id — so any composer we projected
    /// with `workspaceIdentifier.id = <our-id>` lights up in the
    /// sidebar.
    ///
    /// `synthesize_id` decides what id to assign for new folders.
    /// Production callers should pass a stable hash (e.g. the
    /// first 32 hex chars of SHA-256 of the folder path) so re-runs
    /// don't accumulate orphaned workspaceStorage entries.
    pub fn ensure_workspace_storage_entry(
        &self,
        folder: &Path,
        synthesize_id: impl FnOnce(&Path) -> String,
    ) -> Result<EnsuredWorkspaceId> {
        if let Some(id) = self.find_workspace_id(folder)? {
            return Ok(EnsuredWorkspaceId {
                id,
                created: false,
            });
        }
        let id = synthesize_id(folder);
        let dir = self.workspace_storage_dir()?.join(&id);
        std::fs::create_dir_all(&dir)?;
        let canonical = std::fs::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf());
        let folder_uri = format!("file://{}", canonical.to_string_lossy());
        let manifest = WorkspaceManifest {
            folder: Some(folder_uri),
        };
        let json = serde_json::to_string_pretty(&manifest)?;
        std::fs::write(dir.join(WORKSPACE_JSON), json)?;
        Ok(EnsuredWorkspaceId { id, created: true })
    }

    /// Whether Cursor's user-data tree exists.
    pub fn exists(&self) -> bool {
        self.user_data_dir().map(|p| p.exists()).unwrap_or(false)
    }

    /// Whether the primary global SQLite database exists.
    pub fn db_exists(&self) -> bool {
        self.db_path().map(|p| p.exists()).unwrap_or(false)
    }
}

/// Slugify an absolute filesystem path into Cursor's project-slug form
/// (the directory name under `~/.cursor/projects/`).
///
/// Cursor encodes `/Users/ben/projects/temp/cursortest` →
/// `Users-ben-projects-temp-cursortest` (strip leading `/`, replace `/`
/// with `-`). Tmp-dir workspaces and remote/untitled workspaces use
/// different slugs we don't try to reconstruct here.
pub fn slug_from_abs_path(abs: &str) -> String {
    abs.trim_start_matches('/').replace('/', "-")
}

fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
}

#[cfg(target_os = "macos")]
fn default_user_data_dir(home: &Path) -> PathBuf {
    home.join("Library/Application Support/Cursor")
}

#[cfg(target_os = "linux")]
fn default_user_data_dir(home: &Path) -> PathBuf {
    home.join(".config/Cursor")
}

#[cfg(target_os = "windows")]
fn default_user_data_dir(home: &Path) -> PathBuf {
    if let Some(appdata) = std::env::var_os("APPDATA") {
        PathBuf::from(appdata).join("Cursor")
    } else {
        home.join("AppData/Roaming/Cursor")
    }
}

#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn default_user_data_dir(home: &Path) -> PathBuf {
    home.join(".config/Cursor")
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn setup() -> (TempDir, PathResolver) {
        let temp = TempDir::new().unwrap();
        let resolver = PathResolver::new()
            .with_home(temp.path())
            .with_anysphere_dir(temp.path().join(".cursor"))
            .with_user_data_dir(temp.path().join("UserData"));
        (temp, resolver)
    }

    #[test]
    fn anysphere_dir_defaults_to_home_dotcursor() {
        let temp = TempDir::new().unwrap();
        let r = PathResolver::new().with_home(temp.path());
        assert_eq!(r.anysphere_dir().unwrap(), temp.path().join(".cursor"));
    }

    #[test]
    fn db_path_under_global_storage() {
        let (_t, r) = setup();
        assert!(
            r.db_path()
                .unwrap()
                .ends_with("UserData/User/globalStorage/state.vscdb")
        );
    }

    #[test]
    fn transcript_path_uses_double_uuid() {
        let (_t, r) = setup();
        let uuid = "724686cd-875e-47da-a90b-dbc3e523efb8";
        let p = r.transcript_path("my-project", uuid).unwrap();
        assert!(p.ends_with(format!("agent-transcripts/{uuid}/{uuid}.jsonl")));
    }

    #[test]
    fn slug_strips_leading_slash_and_replaces() {
        assert_eq!(
            slug_from_abs_path("/Users/ben/projects/temp/cursortest"),
            "Users-ben-projects-temp-cursortest"
        );
        assert_eq!(slug_from_abs_path("/a"), "a");
    }

    #[test]
    fn exists_reflects_user_data_dir() {
        let (_t, r) = setup();
        std::fs::create_dir_all(r.user_data_dir().unwrap()).unwrap();
        assert!(r.exists());
        let missing = PathResolver::new().with_user_data_dir("/never/exists");
        assert!(!missing.exists());
    }

    #[test]
    fn find_workspace_id_matches_by_folder_uri() {
        let (t, r) = setup();
        let folder = t.path().join("project");
        std::fs::create_dir_all(&folder).unwrap();
        let canonical = std::fs::canonicalize(&folder).unwrap();
        let folder_uri = format!("file://{}", canonical.to_string_lossy());

        let storage = r.workspace_storage_dir().unwrap();
        let ws_dir = storage.join("deadbeefdeadbeefdeadbeefdeadbeef");
        std::fs::create_dir_all(&ws_dir).unwrap();
        std::fs::write(
            ws_dir.join("workspace.json"),
            format!(r#"{{"folder": "{folder_uri}"}}"#),
        )
        .unwrap();

        let found = r.find_workspace_id(&folder).unwrap();
        assert_eq!(found.as_deref(), Some("deadbeefdeadbeefdeadbeefdeadbeef"));

        let other = t.path().join("nope");
        std::fs::create_dir_all(&other).unwrap();
        assert!(r.find_workspace_id(&other).unwrap().is_none());
    }

    #[test]
    fn ensure_workspace_storage_creates_entry_when_missing() {
        let (t, r) = setup();
        let folder = t.path().join("brand-new");
        std::fs::create_dir_all(&folder).unwrap();

        let ensured = r
            .ensure_workspace_storage_entry(&folder, |_| "11feedbeef00000000000000feedbeef".into())
            .unwrap();
        assert!(ensured.created);
        assert_eq!(ensured.id, "11feedbeef00000000000000feedbeef");

        // Manifest is written and points back at our folder.
        let manifest_path = r
            .workspace_storage_dir()
            .unwrap()
            .join(&ensured.id)
            .join("workspace.json");
        let raw = std::fs::read_to_string(&manifest_path).unwrap();
        let canonical = std::fs::canonicalize(&folder).unwrap();
        assert!(raw.contains(&format!("file://{}", canonical.to_string_lossy())));

        // Second call finds the existing one — doesn't re-create.
        let again = r
            .ensure_workspace_storage_entry(&folder, |_| "should-not-be-used".into())
            .unwrap();
        assert!(!again.created);
        assert_eq!(again.id, ensured.id);
    }
}