goosedump 0.6.4

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
// 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::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::message::{ContextListing, TaggedListing};

/// Collect listings from every provider, tagging each with the provider it
/// came from. Providers whose stores are missing or unreadable are skipped, so
/// a partial environment still lists whatever is available.
#[must_use]
pub fn list_all_contexts() -> Vec<TaggedListing> {
    let mut out = Vec::new();
    for client in Client::ALL {
        let provider = client.as_str();
        if let Ok(listings) = list_provider_contexts(client) {
            for listing in listings {
                out.push(TaggedListing { provider, listing });
            }
        }
    }
    out
}

/// Keep the listings whose `<provider>:<id>` tag contains a match for the
/// glob, searched anywhere within the tag.
#[must_use]
pub fn filter_listings(listings: Vec<TaggedListing>, glob: &str) -> Vec<TaggedListing> {
    listings
        .into_iter()
        .filter(|t| {
            let tag = format!("{}:{}", t.provider, t.listing.id);
            crate::text::glob_search(glob, &tag)
        })
        .collect()
}

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("."))
}

/// 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>> {
    match client {
        Client::Claude => {
            let files = find_jsonl_files(&resolve_claude_sessions_dir()?)?;
            Ok(list_file_based(&files, |p| Box::new(ClaudeReader::new(p))))
        }
        Client::Codex => {
            let files = find_jsonl_files(&resolve_codex_sessions_dir()?)?;
            Ok(list_file_based(&files, |p| Box::new(CodexReader::new(p))))
        }
        Client::Opencode => OpenCodeReader::new(resolve_opencode_db()?).list_contexts(),
        Client::Crush => CrushReader::new(resolve_crush_db()?).list_contexts(),
        Client::Pi => {
            let files = find_jsonl_files(&resolve_pi_sessions_dir()?)?;
            Ok(list_file_based(&files, |p| Box::new(JsonlReader::new(p))))
        }
        Client::Gemini => {
            let files = find_gemini_chats(&resolve_gemini_tmp_dir()?)?;
            Ok(list_file_based(&files, |p| Box::new(GeminiReader::new(p))))
        }
        Client::Goose => GooseReader::new(resolve_goose_db()?).list_contexts(),
    }
}

/// Open the reader owning `context_id`. File-based providers locate the single
/// session file; DB-based providers read the context by id from their store.
pub fn open_context(client: Client, context_id: &str) -> anyhow::Result<Box<dyn ContextReader>> {
    match client {
        Client::Claude => {
            let files = find_jsonl_files(&resolve_claude_sessions_dir()?)?;
            open_file_based(&files, context_id, |p| Box::new(ClaudeReader::new(p)))
        }
        Client::Codex => {
            let files = find_jsonl_files(&resolve_codex_sessions_dir()?)?;
            open_file_based(&files, context_id, |p| Box::new(CodexReader::new(p)))
        }
        Client::Opencode => Ok(Box::new(OpenCodeReader::new(resolve_opencode_db()?))),
        Client::Crush => Ok(Box::new(CrushReader::new(resolve_crush_db()?))),
        Client::Pi => {
            let files = find_jsonl_files(&resolve_pi_sessions_dir()?)?;
            open_file_based(&files, context_id, |p| Box::new(JsonlReader::new(p)))
        }
        Client::Gemini => {
            let files = find_gemini_chats(&resolve_gemini_tmp_dir()?)?;
            open_file_based(&files, context_id, |p| Box::new(GeminiReader::new(p)))
        }
        Client::Goose => Ok(Box::new(GooseReader::new(resolve_goose_db()?))),
    }
}

/// Delete the context identified by `context_id` from `client`'s store.
pub fn delete_context(client: Client, context_id: &str) -> anyhow::Result<()> {
    open_context(client, context_id)?.delete_context(context_id)
}

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 detail. 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(|a, b| b.detail.cmp(&a.detail));
    listings
}

/// Locate the single session file owning `context_id` and return its reader.
fn open_file_based(
    files: &[PathBuf],
    context_id: &str,
    make_reader: impl Fn(PathBuf) -> Box<dyn ContextReader>,
) -> anyhow::Result<Box<dyn ContextReader>> {
    if files.is_empty() {
        return Err(anyhow::anyhow!("context '{context_id}' not found"));
    }
    let file_path = resolve_jsonl_file(files, context_id, &make_reader)?;
    Ok(make_reader(file_path))
}

/// 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")
}

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")
}

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.
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 path.extension() == Some(OsStr::new("json")) {
            files.push(path);
        }
    }
    Ok(())
}

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")
}

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")
}

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(())
}

fn resolve_jsonl_file(
    files: &[PathBuf],
    context_id: &str,
    make_reader: impl Fn(PathBuf) -> Box<dyn ContextReader>,
) -> anyhow::Result<PathBuf> {
    for file in files {
        let reader = make_reader(file.clone());
        if let Ok(listings) = reader.list_contexts() {
            if listings.iter().any(|l| l.id == context_id) {
                return Ok(file.clone());
            }
        }
    }

    let prefix_matches: Vec<&PathBuf> = files
        .iter()
        .filter(|f| {
            let reader = make_reader((*f).clone());
            reader
                .list_contexts()
                .is_ok_and(|listings| listings.iter().any(|l| l.id.starts_with(context_id)))
        })
        .collect();

    match prefix_matches.len() {
        0 => Err(anyhow::anyhow!("context '{context_id}' not found")),
        1 => Ok(prefix_matches[0].clone()),
        _ => Err(anyhow::anyhow!("ambiguous context id '{context_id}'")),
    }
}