goosedump 0.12.42

Browse, search, compact, and learn from coding-agent sessions
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
// 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::engine::Client;
use crate::engine::behavior::{Claude, Codex, Crush, Gemini, Goose, Opencode, Pi};
use crate::engine::context::ContextReader;
use crate::engine::context::claude::ClaudeReader;
use crate::engine::context::codex::CodexReader;
use crate::engine::context::crush::CrushReader;
use crate::engine::context::gemini::GeminiReader;
use crate::engine::context::goose::GooseReader;
use crate::engine::context::jsonl::JsonlReader;
use crate::engine::context::opencode::OpenCodeReader;
use crate::engine::index::IndexEntry;
use crate::engine::message::ContextListing;

fn goosedump_data_dir_override() -> Option<PathBuf> {
    std::env::var_os("GOOSEDUMP_DATA_DIR")
        .map(PathBuf::from)
        .filter(|path| path.is_dir())
}

fn opencode_data_dir() -> PathBuf {
    goosedump_data_dir_override()
        .unwrap_or_else(|| {
            std::env::var_os("XDG_DATA_HOME")
                .map(PathBuf::from)
                .filter(|path| path.is_absolute())
                .unwrap_or_else(|| {
                    dirs::home_dir()
                        .unwrap_or_else(|| PathBuf::from("."))
                        .join(".local")
                        .join("share")
                })
        })
        .join("opencode")
}

fn goose_data_dir_from(
    goosedump_data_dir: Option<PathBuf>,
    goose_path_root: Option<PathBuf>,
    platform_data_dir: PathBuf,
) -> PathBuf {
    if let Some(data_dir) = goosedump_data_dir {
        return data_dir.join("goose");
    }
    if let Some(root) = goose_path_root.filter(|path| path.is_absolute()) {
        return root.join("data");
    }
    platform_data_dir
}

#[cfg(not(windows))]
fn goose_platform_data_dir() -> PathBuf {
    std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .unwrap_or_else(|| {
            dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".local")
                .join("share")
        })
        .join("goose")
}

#[cfg(windows)]
fn goose_platform_data_dir() -> PathBuf {
    dirs::data_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join("Block")
        .join("goose")
        .join("data")
}

fn goose_data_dir() -> PathBuf {
    goose_data_dir_from(
        goosedump_data_dir_override(),
        std::env::var_os("GOOSE_PATH_ROOT").map(PathBuf::from),
        goose_platform_data_dir(),
    )
}

/// How a provider opens and enumerates native sessions (read half of
/// [`crate::engine::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()?
        .context("file storage provider does not 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 = opencode_data_dir();
    let db = opencode_db_from(&data_dir, std::env::var_os("OPENCODE_DB").as_deref());
    if db == Path::new(":memory:") {
        return Err(anyhow::anyhow!(
            "cannot inspect OpenCode's in-memory session database"
        ));
    }
    if db.exists() {
        Ok(db)
    } else {
        Err(anyhow::anyhow!(
            "OpenCode database not found at {}",
            db.display()
        ))
    }
}

fn opencode_db_from(data_dir: &Path, configured: Option<&OsStr>) -> PathBuf {
    let Some(configured) = configured.filter(|value| !value.is_empty()) else {
        return data_dir.join("opencode.db");
    };
    let configured = Path::new(configured);
    if configured == Path::new(":memory:") || configured.is_absolute() {
        configured.to_path_buf()
    } else {
        data_dir.join(configured)
    }
}

pub(crate) fn resolve_goose_db() -> anyhow::Result<PathBuf> {
    let db = goose_data_dir().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")?;
    let boundary = crush_project_boundary(&cwd);

    let config_paths = crush_config_paths(&cwd, &boundary);
    if let Some(data_dir) = configured_crush_data_dir(&cwd, &config_paths)? {
        let db = data_dir.join("crush.db");
        if db.exists() {
            return Ok(db);
        }
        return Err(anyhow::anyhow!("crush.db not found at {}", db.display()));
    }

    let mut current = cwd.as_path();
    loop {
        let db = current.join(".crush").join("crush.db");
        if db.exists() {
            return Ok(db);
        }
        if current == boundary {
            break;
        }
        let Some(parent) = current.parent() else {
            break;
        };
        current = parent;
    }

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

fn crush_project_boundary(cwd: &Path) -> PathBuf {
    let output = std::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .current_dir(cwd)
        .output();
    let Ok(output) = output else {
        return cwd.to_path_buf();
    };
    if !output.status.success() {
        return cwd.to_path_buf();
    }
    let root = String::from_utf8_lossy(&output.stdout);
    let root = PathBuf::from(root.trim());
    if root.is_absolute() && cwd.starts_with(&root) {
        root
    } else {
        cwd.to_path_buf()
    }
}

fn crush_config_paths(cwd: &Path, boundary: &Path) -> Vec<PathBuf> {
    let mut paths = crush_global_config_paths();
    let mut directories = Vec::new();
    let mut current = cwd;
    loop {
        directories.push(current);
        if current == boundary {
            break;
        }
        let Some(parent) = current.parent() else {
            break;
        };
        current = parent;
    }

    for directory in directories.into_iter().rev() {
        paths.push(directory.join("crush.json"));
        paths.push(directory.join(".crush.json"));
    }
    paths
}

fn crush_global_config_paths() -> Vec<PathBuf> {
    let mut paths = Vec::new();
    #[cfg(not(windows))]
    paths.push(PathBuf::from("/etc/crush/crush.json"));

    let config = std::env::var_os("CRUSH_GLOBAL_CONFIG")
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("XDG_CONFIG_HOME")
                .map(PathBuf::from)
                .filter(|path| path.is_absolute())
                .or_else(|| dirs::home_dir().map(|home| home.join(".config")))
                .map(|root| root.join("crush"))
        })
        .map(|root| root.join("crush.json"));
    let data = std::env::var_os("CRUSH_GLOBAL_DATA")
        .map(PathBuf::from)
        .or_else(crush_data_root)
        .map(|root| root.join("crush.json"));
    paths.extend(config);
    paths.extend(data);
    paths
}

#[cfg(not(windows))]
fn crush_data_root() -> Option<PathBuf> {
    std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .or_else(|| dirs::home_dir().map(|home| home.join(".local").join("share")))
        .map(|root| root.join("crush"))
}

#[cfg(windows)]
fn crush_data_root() -> Option<PathBuf> {
    std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .or_else(dirs::data_local_dir)
        .map(|root| root.join("crush"))
}

fn configured_crush_data_dir(
    cwd: &Path,
    config_paths: &[PathBuf],
) -> anyhow::Result<Option<PathBuf>> {
    let mut configured = None;
    for config_path in config_paths.iter().filter(|path| path.is_file()) {
        let contents = fs::read_to_string(config_path)
            .with_context(|| format!("read {}", config_path.display()))?;
        let config: serde_json::Value = serde_json::from_str(&contents)
            .with_context(|| format!("parse {}", config_path.display()))?;
        if let Some(value) = config.pointer("/options/data_directory") {
            let path = value.as_str().with_context(|| {
                format!(
                    "{}.options.data_directory must be a string",
                    config_path.display()
                )
            })?;
            configured = (!path.is_empty()).then(|| PathBuf::from(path));
        }
    }

    Ok(configured.map(|path| {
        if path.is_absolute() {
            path
        } else {
            cwd.join(path)
        }
    }))
}

/// 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 CLI's `GEMINI_CLI_HOME` home-directory override. Returned
/// without an existence check so the writer can create the project subtree.
pub(crate) fn gemini_tmp_base() -> PathBuf {
    gemini_global_dir().join("tmp")
}

pub(crate) fn gemini_projects_registry() -> PathBuf {
    gemini_global_dir().join("projects.json")
}

fn gemini_global_dir() -> PathBuf {
    let home = std::env::var("GEMINI_CLI_HOME").map_or_else(
        |_| dirs::home_dir().unwrap_or_else(|| PathBuf::from(".")),
        PathBuf::from,
    );
    home.join(".gemini")
}

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 path.extension().and_then(OsStr::to_str) == Some("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(())
}