brokk-sessionwiki 0.30.1

Find, search, and read every AI coding session you've ever had - across Claude Code, Codex, Gemini CLI, OpenCode, Cline, and more.
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
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
use clap::{Parser, Subcommand};
use sessionwiki::{commands, doctor, web};

/// Find, search, and read every AI coding session on your machine - across
/// Claude Code, Codex, Gemini CLI, OpenCode, Cline, and more. 100% local.
#[derive(Parser)]
#[command(name = "sessionwiki", version, about, max_term_width = 100)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Discover session stores on this machine (which tools, where, how much)
    Scan,
    /// List recent sessions across all tools
    List {
        /// Max sessions to show
        #[arg(short = 'n', long, default_value_t = 20)]
        limit: usize,
        /// Filter by tool (claude-code, codex, gemini, prodex, ... - `scan` lists all)
        #[arg(long)]
        tool: Option<String>,
        /// Filter by project path substring
        #[arg(long)]
        project: Option<String>,
        /// Filter by tag
        #[arg(long)]
        tag: Option<String>,
        /// Filter by swapdex account profile (the @badge; needs a swapdex switch history)
        #[arg(long)]
        account: Option<String>,
        /// Include subagent transcripts in the listing
        #[arg(long)]
        all: bool,
        /// Emit as a JSON array (agent-friendly, stable field names)
        #[arg(long)]
        json: bool,
        /// Skip the index sync and query what is already indexed (pair with `sync`)
        #[arg(long)]
        no_sync: bool,
    },
    /// Full-text search across every session of every tool
    Search {
        /// Text to look for (substring match, works for CJK too)
        query: String,
        /// Max sessions to show
        #[arg(short = 'n', long, default_value_t = 10)]
        limit: usize,
        /// Filter by tool (claude-code, codex, gemini, prodex, ... - `scan` lists all)
        #[arg(long)]
        tool: Option<String>,
        /// Filter by project path substring
        #[arg(long)]
        project: Option<String>,
        /// Filter by swapdex account profile (the @badge; needs a swapdex switch history)
        #[arg(long)]
        account: Option<String>,
        /// Emit as a JSON array (agent-friendly, stable field names)
        #[arg(long)]
        json: bool,
        /// Skip the index sync and query what is already indexed (pair with `sync`)
        #[arg(long)]
        no_sync: bool,
    },
    /// Find matching messages inside sessions (sessions are files, messages
    /// are lines)
    ///
    /// The pattern is a fixed string, not a regular expression, and matching is
    /// always case-insensitive: this is what the trigram full-text index can
    /// answer. Without ids, the sessions searched are the index's own top
    /// matches; with ids, exactly those sessions.
    Grep {
        /// Text to look for (fixed string, case-insensitive substring)
        pattern: String,
        /// Sessions to search (id prefix is enough); omit to search the index
        #[arg(value_name = "ID")]
        ids: Vec<String>,
        /// Max sessions to search when no ids are given
        #[arg(short = 'n', long, default_value_t = 20)]
        limit: usize,
        /// Filter by tool (claude-code, codex, gemini, prodex, ... - `scan` lists all)
        #[arg(long)]
        tool: Option<String>,
        /// Filter by project path substring
        #[arg(long)]
        project: Option<String>,
        /// Only sessions started within this window (7d, 2w, 24h, 90m)
        #[arg(long)]
        since: Option<String>,
        /// Stop after this many matching messages per session
        #[arg(short = 'm', long = "max-count", value_name = "N")]
        max_matches: Option<usize>,
        /// Messages of context after a match
        #[arg(short = 'A', value_name = "N", default_value_t = 0)]
        after: usize,
        /// Messages of context before a match
        #[arg(short = 'B', value_name = "N", default_value_t = 0)]
        before: usize,
        /// Messages of context on both sides (sets -A and -B)
        #[arg(short = 'C', value_name = "N")]
        context: Option<usize>,
        /// Characters kept per message, windowed around its first match (0 keeps all)
        #[arg(long, default_value_t = 240)]
        chars: usize,
        /// Print only the ids of sessions that matched
        #[arg(short = 'l', long = "files-with-matches")]
        list: bool,
        /// Print `id:count` per session instead of the matching messages
        #[arg(short = 'c', long = "count")]
        count: bool,
        /// Emit one JSON object per line: {id, i, role, ts, text, matches, omitted_before}
        #[arg(long)]
        json: bool,
        /// Skip the index sync and query what is already indexed (pair with `sync`)
        #[arg(long)]
        no_sync: bool,
    },
    /// Recall past work in one step: search, then brief the top match
    Recall {
        /// What to recall - a topic, error text, or identifier (exact phrasing)
        query: String,
        /// How many candidate matches to list (the top one is briefed)
        #[arg(short = 'n', long, default_value_t = 5)]
        limit: usize,
        /// Filter by tool (claude-code, codex, gemini, prodex, ... - `scan` lists all)
        #[arg(long)]
        tool: Option<String>,
        /// Filter by project path substring
        #[arg(long)]
        project: Option<String>,
        /// Budget for the briefed top match
        #[arg(long, default_value_t = 12000)]
        max_chars: usize,
        /// Emit a JSON object { query, top, candidates } instead
        #[arg(long)]
        json: bool,
        /// Skip the index sync and query what is already indexed (pair with `sync`)
        #[arg(long)]
        no_sync: bool,
    },
    /// Browse and search sessions in a local web UI
    Web {
        /// Port to listen on (localhost only)
        #[arg(long, default_value_t = 7575)]
        port: u16,
        /// Do not open the browser automatically
        #[arg(long)]
        no_open: bool,
        /// Refresh the index once before serving (otherwise it reflects the
        /// last `list`/`search`)
        #[arg(long)]
        sync: bool,
    },
    /// Print one session as a readable transcript
    Show {
        /// Session id (prefix is enough), from list/search output
        id: String,
        /// Include full tool inputs/outputs instead of summaries
        #[arg(long)]
        full: bool,
        /// Emit the parsed session as JSON
        #[arg(long)]
        json: bool,
        /// Emit one JSON object per message per line: {i, role, ts, text}
        #[arg(long, conflicts_with = "json")]
        jsonl: bool,
        /// Show a digest instead: every user turn plus how the session ended
        #[arg(long)]
        outline: bool,
        /// Agent-friendly bounded window: the real turns, but tool outputs
        /// folded to head+tail (add --budget to keep only the recent tail)
        #[arg(long)]
        window: bool,
        /// With --window, cap the render to about this many tokens (recent tail)
        #[arg(long)]
        budget: Option<usize>,
        /// Read the session file directly (0-delay tail), bypassing the index
        #[arg(long)]
        live: bool,
        /// Skip the index sync; only sync if the id is not already indexed
        #[arg(long)]
        no_sync: bool,
    },
    /// Reopen a session in its original tool (claude --resume / codex resume)
    Resume {
        /// Session id (prefix is enough), from list/search output
        id: String,
        /// Print the resume command instead of running it
        #[arg(long)]
        print: bool,
        /// Skip the index sync; only sync if the id is not already indexed
        #[arg(long)]
        no_sync: bool,
    },
    /// Copy a session so it can be resumed from a different project directory
    Migrate {
        /// Session id (prefix is enough), from list/search output
        id: String,
        /// Target project directory to make the session resumable from
        dir: String,
        /// Skip the index sync; only sync if the id is not already indexed
        #[arg(long)]
        no_sync: bool,
        /// Write into THIS account's store instead of the default one - the
        /// slot directory swapdex gives an account (its CLAUDE_CONFIG_DIR).
        /// Without it, `CLAUDE_CONFIG_DIR` is honoured, then `~/.claude`.
        #[arg(long, value_name = "DIR")]
        config_dir: Option<std::path::PathBuf>,
    },
    /// Generate and cache LLM synopses for sessions (uses your own LLM CLI)
    Summarize {
        /// Session id to summarize; omit to batch over recent sessions
        id: Option<String>,
        /// How many recent unsummarized sessions to process in batch mode
        #[arg(long, default_value_t = 10)]
        recent: usize,
        /// Filter batch mode by tool
        #[arg(long)]
        tool: Option<String>,
        /// Summarizer command reading the session on stdin (default: `claude -p`,
        /// or the SESSIONWIKI_SUMMARIZER environment variable)
        #[arg(long)]
        cmd: Option<String>,
        /// Re-summarize even if a cached summary exists
        #[arg(long)]
        force: bool,
    },
    /// Emit a markdown briefing of a session, ready to paste into a new one
    Brief {
        /// Session id (prefix is enough), from list/search output
        id: String,
        /// Budget for the briefing body; the middle of long sessions is omitted
        #[arg(long, default_value_t = 24000)]
        max_chars: usize,
        /// Include tool calls in the briefing
        #[arg(long)]
        tools: bool,
        /// Emit a JSON object { id, tool, project, title, started, source,
        /// markdown } instead of raw markdown
        #[arg(long)]
        json: bool,
        /// Skip the index sync; only sync if the id is not already indexed
        #[arg(long)]
        no_sync: bool,
    },
    /// Tag a session: `tag <id> <tag>...` adds, `--rm <tag>` removes (no id
    /// lists every tag in use). Tags are positional - there is no `add`
    /// keyword, so `tag <id> add foo` would create the tags `add` and `foo`.
    Tag {
        /// Session id (prefix is enough); omit to list every tag in use
        #[arg(default_value = "")]
        id: String,
        /// Tags to add (positional, space-separated)
        #[arg(value_name = "TAG")]
        add: Vec<String>,
        /// Tags to remove
        #[arg(long = "rm", value_name = "TAG")]
        remove: Vec<String>,
    },
    /// Attach or read a freeform note on a session
    Note {
        /// Session id (prefix is enough)
        id: String,
        /// Note text; omit to print the existing note
        text: Option<String>,
    },
    /// Find sessions related to one (shared project, files, and tags)
    Related {
        /// Session id (prefix is enough)
        id: String,
        /// Max related sessions to show
        #[arg(short = 'n', long, default_value_t = 10)]
        limit: usize,
        /// Emit as a JSON array (agent-friendly, stable field names)
        #[arg(long)]
        json: bool,
    },
    /// List the files a session edited or created
    Files {
        /// Session id (prefix is enough), from list/search output
        id: String,
        /// Emit as a JSON array of paths
        #[arg(long)]
        json: bool,
    },
    /// Trace a file back to the AI sessions that edited it (newest first)
    Trace {
        /// File path as it appears in your editor (e.g. src/auth.rs)
        path: String,
        /// Emit as a JSON array (agent-friendly, stable field names)
        #[arg(long)]
        json: bool,
        /// Skip the index sync and query what is already indexed (pair with `sync`)
        #[arg(long)]
        no_sync: bool,
    },
    /// Attribute each line of a file to the AI session most likely behind it (git blame for the AI era)
    Blame {
        /// File path as it appears in your editor (e.g. src/auth.rs)
        file: String,
        /// Restrict to a line range, e.g. -L 40,80
        #[arg(short = 'L', value_name = "START,END", value_parser = parse_line_range)]
        range: Option<(usize, usize)>,
        /// Emit as a JSON array (agent-friendly, stable field names)
        #[arg(long)]
        json: bool,
        /// Skip the index sync and query what is already indexed (pair with `sync`)
        #[arg(long)]
        no_sync: bool,
    },
    /// Permanently drop an archived (or any) session from the index
    Forget {
        /// Session id (prefix is enough), from list/search output
        id: String,
    },
    /// Build or refresh the index now, so later queries can use `--no-sync`
    Sync {
        /// Limit to one tool (claude-code, codex, gemini, opencode, ...)
        #[arg(long)]
        tool: Option<String>,
    },
    /// Markdown rollup of recent sessions by project (files touched, synopses)
    Digest {
        /// Time window: 7d, 2w, 24h, 90m (a bare number is days)
        #[arg(long, default_value = "7d")]
        since: String,
        /// Limit to one tool
        #[arg(long)]
        tool: Option<String>,
        /// Limit to one project (substring match)
        #[arg(long)]
        project: Option<String>,
        /// Emit JSON instead of markdown
        #[arg(long)]
        json: bool,
        /// Skip the index sync; only sync if the id is not already indexed
        #[arg(long)]
        no_sync: bool,
    },
    /// List projects with session counts (a page per project)
    Projects,
    /// Usage breakdown across tools, projects, and months
    Stats,
    /// Diagnose this machine's setup: which stores exist, index health, version
    Doctor {
        /// Emit the checks as JSON
        #[arg(long)]
        json: bool,
    },
    /// Internal hooks for editor integrations (run by Claude Code, not by hand)
    Hook {
        #[command(subcommand)]
        cmd: HookCmd,
    },
    /// Run as an MCP server over stdio (register: claude mcp add sessionwiki -- sessionwiki mcp)
    Mcp,
}

#[derive(Subcommand)]
enum HookCmd {
    /// Claude Code SessionStart: print a fenced recall brief for the launch project
    SessionStart,
}

fn main() {
    restore_default_sigpipe();
    let cli = Cli::parse();
    let result = match cli.command {
        Command::Scan => commands::scan(),
        Command::List {
            limit,
            tool,
            project,
            tag,
            account,
            all,
            json,
            no_sync,
        } => commands::list(
            limit,
            tool.as_deref(),
            project.as_deref(),
            tag.as_deref(),
            account.as_deref(),
            all,
            json,
            no_sync,
        ),
        Command::Search {
            query,
            limit,
            tool,
            project,
            account,
            json,
            no_sync,
        } => commands::search(
            &query,
            limit,
            tool.as_deref(),
            project.as_deref(),
            account.as_deref(),
            json,
            no_sync,
        ),
        Command::Grep {
            pattern,
            ids,
            limit,
            tool,
            project,
            since,
            max_matches,
            after,
            before,
            context,
            chars,
            list,
            count,
            json,
            no_sync,
        } => commands::grep(
            &pattern,
            &commands::GrepArgs {
                ids: &ids,
                limit,
                tool: tool.as_deref(),
                project: project.as_deref(),
                since: since.as_deref(),
                max_matches,
                // The library keeps one symmetric context width, so a lopsided
                // -A/-B widens to the larger of the two.
                context: context.unwrap_or_else(|| after.max(before)),
                chars,
                list,
                count,
                json,
                no_sync,
            },
        ),
        Command::Recall {
            query,
            limit,
            tool,
            project,
            max_chars,
            json,
            no_sync,
        } => commands::recall(
            &query,
            limit,
            tool.as_deref(),
            project.as_deref(),
            max_chars,
            json,
            no_sync,
        ),
        Command::Web {
            port,
            no_open,
            sync,
        } => web::serve(port, no_open, sync),
        Command::Show {
            id,
            full,
            json,
            jsonl,
            outline,
            window,
            budget,
            live,
            no_sync,
        } => commands::show(
            &id, full, json, jsonl, outline, window, budget, live, no_sync,
        ),
        Command::Resume { id, print, no_sync } => commands::resume_cmd(&id, print, no_sync),
        Command::Migrate {
            id,
            dir,
            no_sync,
            config_dir,
        } => commands::migrate_cmd(&id, &dir, no_sync, config_dir.as_deref()),
        Command::Summarize {
            id,
            recent,
            tool,
            cmd,
            force,
        } => commands::summarize(
            id.as_deref(),
            recent,
            tool.as_deref(),
            cmd.as_deref(),
            force,
        ),
        Command::Brief {
            id,
            max_chars,
            tools,
            json,
            no_sync,
        } => commands::brief(&id, max_chars, tools, json, no_sync),
        Command::Tag { id, add, remove } => commands::tag(&id, &add, &remove),
        Command::Note { id, text } => commands::note(&id, text.as_deref()),
        Command::Related { id, limit, json } => commands::related(&id, limit, json),
        Command::Files { id, json } => commands::files(&id, json),
        Command::Trace {
            path,
            json,
            no_sync,
        } => commands::trace(&path, json, no_sync),
        Command::Blame {
            file,
            range,
            json,
            no_sync,
        } => commands::blame(&file, range, json, no_sync),
        Command::Forget { id } => commands::forget(&id),
        Command::Sync { tool } => commands::sync_cmd(tool.as_deref()),
        Command::Digest {
            since,
            tool,
            project,
            json,
            no_sync,
        } => commands::digest(&since, tool.as_deref(), project.as_deref(), json, no_sync),
        Command::Projects => commands::projects(),
        Command::Stats => commands::stats(),
        Command::Doctor { json } => doctor::run(json),
        Command::Hook {
            cmd: HookCmd::SessionStart,
        } => {
            // Always exit 0 with whatever was printed; never the exit(1) path.
            sessionwiki::hook::session_start();
            return;
        }
        Command::Mcp => {
            sessionwiki::mcp::serve();
            return;
        }
    };
    if let Err(e) = result {
        eprintln!("error: {e:#}");
        std::process::exit(1);
    }
}

/// Parse a `-L START,END` line range into validated integers (so the raw token
/// is never forwarded to git). 1-based, inclusive, START <= END.
fn parse_line_range(s: &str) -> Result<(usize, usize), String> {
    let (a, b) = s.split_once(',').ok_or("expected START,END")?;
    let start: usize = a.trim().parse().map_err(|_| "START must be a number")?;
    let end: usize = b.trim().parse().map_err(|_| "END must be a number")?;
    if start == 0 || end < start {
        return Err("require 1 <= START <= END".into());
    }
    Ok((start, end))
}

/// Let a closed pipe end the process quietly.
///
/// The Rust runtime ignores SIGPIPE before `main`, so writing to a pipe whose
/// reader has gone (`sessionwiki grep -l ... | head`) fails with EPIPE and
/// `println!` panics. Restoring the default disposition makes the process exit
/// on the signal the way grep and cat do, with nothing on stderr.
fn restore_default_sigpipe() {
    #[cfg(unix)]
    // SAFETY: setting a signal disposition before any other thread exists.
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
}