goosedump 0.12.5

Coding agent context data browser
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) Jarkko Sakkinen 2026

use std::ffi::OsStr;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::Context as _;

use crate::Client;
use crate::behavior::{Claude, Codex, Crush, Gemini, Goose, Opencode, Pi};
use crate::context::ContextReader;
use crate::context::claude::ClaudeReader;
use crate::context::codex::CodexReader;
use crate::context::crush::CrushReader;
use crate::context::gemini::GeminiReader;
use crate::context::goose::GooseReader;
use crate::context::jsonl::JsonlReader;
use crate::context::opencode::OpenCodeReader;
use crate::index::IndexEntry;
use crate::message::ContextListing;

fn data_dir_override() -> PathBuf {
    if let Ok(dir) = std::env::var("GOOSEDUMP_DATA_DIR") {
        let path = PathBuf::from(&dir);
        if path.is_dir() {
            return path;
        }
    }
    dirs::data_dir().unwrap_or_else(|| PathBuf::from("."))
}

/// How a provider opens and enumerates native sessions (read half of
/// [`crate::behavior::ClientBehavior`]).
pub(crate) trait ProviderStore {
    /// Open a context reader at `path`. File-backed providers read the
    /// transcript file; SQLite-backed providers read their database, with the
    /// session row id carried by the caller.
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader>;

    /// Session files for file-backed providers. Returns `None` for `SQLite`
    /// providers, whose contexts are enumerated via [`Self::list_contexts`].
    fn session_files(&self) -> Option<anyhow::Result<Vec<PathBuf>>> {
        None
    }

    /// Every context this provider currently exposes.
    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>>;
}

impl ProviderStore for Claude {
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader> {
        Box::new(ClaudeReader::new(path))
    }

    fn session_files(&self) -> Option<anyhow::Result<Vec<PathBuf>>> {
        Some(resolve_claude_sessions_dir().and_then(|d| find_jsonl_files(&d)))
    }

    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
        list_file_store(self)
    }
}

impl ProviderStore for Codex {
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader> {
        Box::new(CodexReader::new(path))
    }

    fn session_files(&self) -> Option<anyhow::Result<Vec<PathBuf>>> {
        Some(resolve_codex_sessions_dir().and_then(|d| find_jsonl_files(&d)))
    }

    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
        list_file_store(self)
    }
}

impl ProviderStore for Pi {
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader> {
        Box::new(JsonlReader::new(path))
    }

    fn session_files(&self) -> Option<anyhow::Result<Vec<PathBuf>>> {
        Some(resolve_pi_sessions_dir().and_then(|d| find_jsonl_files(&d)))
    }

    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
        list_file_store(self)
    }
}

impl ProviderStore for Gemini {
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader> {
        Box::new(GeminiReader::new(path))
    }

    fn session_files(&self) -> Option<anyhow::Result<Vec<PathBuf>>> {
        Some(resolve_gemini_tmp_dir().and_then(|d| find_gemini_chats(&d)))
    }

    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
        list_file_store(self)
    }
}

impl ProviderStore for Goose {
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader> {
        Box::new(GooseReader::new(path))
    }

    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
        GooseReader::new(resolve_goose_db()?).list_contexts()
    }
}

impl ProviderStore for Crush {
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader> {
        Box::new(CrushReader::new(path))
    }

    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
        CrushReader::new(resolve_crush_db()?).list_contexts()
    }
}

impl ProviderStore for Opencode {
    fn open_context(&self, path: PathBuf) -> Box<dyn ContextReader> {
        Box::new(OpenCodeReader::new(path))
    }

    fn list_contexts(&self) -> anyhow::Result<Vec<ContextListing>> {
        OpenCodeReader::new(resolve_opencode_db()?).list_contexts()
    }
}

fn list_file_store(store: &dyn ProviderStore) -> anyhow::Result<Vec<ContextListing>> {
    let files = store
        .session_files()
        .transpose()?
        .expect("file storage providers expose session files");
    Ok(list_file_based(&files, |p| store.open_context(p)))
}

impl Client {
    /// The client's session store, dispatched through a vtable rather than a
    /// per-call-site `match`.
    pub(crate) fn store(self) -> &'static dyn ProviderStore {
        match self {
            Self::Claude => &Claude,
            Self::Codex => &Codex,
            Self::Crush => &Crush,
            Self::Gemini => &Gemini,
            Self::Goose => &Goose,
            Self::Opencode => &Opencode,
            Self::Pi => &Pi,
        }
    }

    /// Open a context reader at `path`.
    #[must_use]
    pub(crate) fn open_context(self, path: PathBuf) -> Box<dyn ContextReader> {
        self.store().open_context(path)
    }

    /// Session files for file-backed providers. Returns `None` for `SQLite`
    /// providers, whose contexts are enumerated via [`list_provider_contexts`].
    pub(crate) fn session_files(self) -> Option<anyhow::Result<Vec<PathBuf>>> {
        self.store().session_files()
    }
}

/// Collect every context a provider exposes. File-based providers aggregate
/// one listing per session file; DB-based providers query their store.
pub fn list_provider_contexts(client: Client) -> anyhow::Result<Vec<ContextListing>> {
    client.store().list_contexts()
}

/// Open a context directly from an index entry. File-based entries point at the
/// transcript file; SQLite-backed entries point at their provider database and
/// carry the session row id in `id`.
#[must_use]
pub fn open_indexed_context(entry: &IndexEntry) -> Box<dyn ContextReader> {
    entry.provider.open_context(entry.path.clone())
}

#[must_use]
pub(crate) fn open_listed_context(
    client: Client,
    listing: &ContextListing,
) -> Box<dyn ContextReader> {
    client.open_context(listing.path.clone())
}

pub(crate) fn resolve_opencode_db() -> anyhow::Result<PathBuf> {
    let data_dir = data_dir_override();
    let db = data_dir.join("opencode").join("opencode.db");
    if db.exists() {
        Ok(db)
    } else {
        Err(anyhow::anyhow!("opencode.db not found at {}", db.display()))
    }
}

pub(crate) fn resolve_goose_db() -> anyhow::Result<PathBuf> {
    let data_dir = data_dir_override();
    let db = data_dir.join("goose").join("sessions").join("sessions.db");
    if db.exists() {
        Ok(db)
    } else {
        Err(anyhow::anyhow!(
            "goose sessions.db not found at {}",
            db.display()
        ))
    }
}

pub(crate) fn resolve_crush_db() -> anyhow::Result<PathBuf> {
    let cwd = std::env::current_dir().context("cwd")?;

    if let Some(config_path) = find_crush_config(&cwd) {
        let config: serde_json::Value = {
            let contents = fs::read_to_string(&config_path)
                .with_context(|| format!("read {}", config_path.display()))?;
            serde_json::from_str(&contents)?
        };

        let data_dir = config["options"]["data_directory"]
            .as_str()
            .or_else(|| config["data_directory"].as_str());

        if let Some(dir) = data_dir {
            let db = config_path
                .parent()
                .unwrap_or(Path::new("."))
                .join(dir)
                .join("crush.db");
            if db.exists() {
                return Ok(db);
            }
        }
    }

    Err(anyhow::anyhow!("crush.db not found"))
}

fn find_crush_config(cwd: &Path) -> Option<PathBuf> {
    let mut current = Some(cwd.to_path_buf());
    while let Some(dir) = current {
        if let Some(path) = [".crush.json", "crush.json"]
            .into_iter()
            .map(|name| dir.join(name))
            .find(|path| path.exists())
        {
            return Some(path);
        }
        current = dir.parent().map(std::path::Path::to_path_buf);
    }
    None
}

/// Aggregate one listing per session file for a file-based provider (claude,
/// codex, gemini, pi), sorted newest-first by provider id. Files that fail to parse
/// are skipped so a partial store still lists what is readable.
fn list_file_based(
    files: &[PathBuf],
    make_reader: impl Fn(PathBuf) -> Box<dyn ContextReader>,
) -> Vec<ContextListing> {
    let mut listings = Vec::new();
    for file in files {
        if let Ok(mut l) = make_reader(file.clone()).list_contexts() {
            listings.append(&mut l);
        }
    }
    listings.sort_by_key(|b| std::cmp::Reverse(b.provider_id.from));
    listings
}

/// The `claude/projects` directory `import` writes into, honoring
/// `CLAUDE_CONFIG_DIR`. Returned without an existence check so the writer can
/// create it.
pub(crate) fn claude_projects_base() -> PathBuf {
    let config_dir = std::env::var("CLAUDE_CONFIG_DIR").map_or_else(
        |_| {
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".claude")
        },
        PathBuf::from,
    );
    config_dir.join("projects")
}

pub(crate) fn resolve_claude_sessions_dir() -> anyhow::Result<PathBuf> {
    let projects = claude_projects_base();
    if projects.is_dir() {
        return Ok(projects);
    }

    Err(anyhow::anyhow!(
        "claude projects directory not found at {}",
        projects.display()
    ))
}

/// The `gemini/tmp` directory `import` writes session subtrees into, honoring
/// `GEMINI_DIR`. Returned without an existence check so the writer can create
/// the `<projectHash>/chats` path beneath it.
pub(crate) fn gemini_tmp_base() -> PathBuf {
    let home = std::env::var("GEMINI_DIR").map_or_else(
        |_| {
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".gemini")
        },
        PathBuf::from,
    );
    home.join("tmp")
}

pub(crate) fn resolve_gemini_tmp_dir() -> anyhow::Result<PathBuf> {
    let tmp = gemini_tmp_base();
    if tmp.is_dir() {
        return Ok(tmp);
    }

    Err(anyhow::anyhow!(
        "gemini tmp directory not found at {}",
        tmp.display()
    ))
}

/// Gemini stores recorded sessions per project under
/// `<tmp>/<project-hash>/chats/`; the sibling `logs.json` keystroke files live
/// directly under the project hash and are deliberately not collected.
pub(crate) fn find_gemini_chats(tmp_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    let entries =
        fs::read_dir(tmp_dir).with_context(|| format!("read dir {}", tmp_dir.display()))?;
    for entry in entries {
        let entry = entry?;
        let chats = entry.path().join("chats");
        if chats.is_dir() {
            collect_json_files(&chats, &mut files)
                .with_context(|| format!("read dir {}", chats.display()))?;
        }
    }
    files.sort();
    Ok(files)
}

fn collect_json_files(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
    let entries = fs::read_dir(dir)?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_json_files(&path, files)?;
        } else if matches!(
            path.extension().and_then(OsStr::to_str),
            Some("json" | "jsonl")
        ) {
            files.push(path);
        }
    }
    Ok(())
}

pub(crate) fn resolve_codex_sessions_dir() -> anyhow::Result<PathBuf> {
    if let Ok(dir) = std::env::var("CODEX_HOME") {
        let sessions = PathBuf::from(&dir).join("sessions");
        if sessions.is_dir() {
            return Ok(sessions);
        }
    }

    let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
    let sessions = home.join(".codex").join("sessions");
    if sessions.is_dir() {
        return Ok(sessions);
    }

    Err(anyhow::anyhow!("codex sessions directory not found"))
}

/// The `codex/sessions` directory `import` writes date-bucketed rollouts into,
/// honoring `CODEX_HOME`. Returned without an existence check so the writer can
/// create the `YYYY/MM/DD` path beneath it.
pub(crate) fn codex_sessions_base() -> PathBuf {
    if let Ok(dir) = std::env::var("CODEX_HOME") {
        return PathBuf::from(dir).join("sessions");
    }
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".codex")
        .join("sessions")
}

pub(crate) fn resolve_pi_sessions_dir() -> anyhow::Result<PathBuf> {
    if let Ok(dir) = std::env::var("PI_CODING_AGENT_SESSION_DIR") {
        let path = PathBuf::from(&dir);
        if path.is_dir() {
            return Ok(path);
        }
    }

    let agent_dir = std::env::var("PI_CODING_AGENT_DIR").unwrap_or_else(|_| {
        let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
        home.join(".pi/agent").display().to_string()
    });

    let sessions = PathBuf::from(&agent_dir).join("sessions");
    if sessions.is_dir() {
        return Ok(sessions);
    }

    Err(anyhow::anyhow!("pi sessions directory not found"))
}

/// The pi sessions directory `import` writes into, honoring
/// `PI_CODING_AGENT_SESSION_DIR` then `PI_CODING_AGENT_DIR`. Returned without an
/// existence check so the writer can create it.
pub(crate) fn pi_sessions_base() -> PathBuf {
    if let Ok(dir) = std::env::var("PI_CODING_AGENT_SESSION_DIR") {
        return PathBuf::from(dir);
    }
    let agent_dir = std::env::var("PI_CODING_AGENT_DIR").unwrap_or_else(|_| {
        dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".pi/agent")
            .display()
            .to_string()
    });
    PathBuf::from(agent_dir).join("sessions")
}

pub(crate) fn find_jsonl_files(dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    collect_jsonl_files(dir, &mut files).with_context(|| format!("read dir {}", dir.display()))?;
    files.sort();
    Ok(files)
}

fn collect_jsonl_files(dir: &Path, files: &mut Vec<PathBuf>) -> std::io::Result<()> {
    let entries = fs::read_dir(dir)?;
    for entry in entries {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_jsonl_files(&path, files)?;
        } else if path.extension() == Some(OsStr::new("jsonl")) {
            files.push(path);
        }
    }
    Ok(())
}