claude-hindsight 2.1.0

20/20 hindsight for your Claude Code sessions
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
//! Claude Hindsight - 20/20 hindsight for your Claude Code sessions
//!
//! A powerful observability tool for Claude Code that transforms raw JSONL
//! transcripts into beautiful, interactive visualizations.

use clap::{Parser, Subcommand};
use std::process;

mod agents;
mod analyzer;
mod api;
mod commands;
mod config;
mod error;
mod otel;
mod parser;
mod search;
mod server;
mod storage;
mod tui;
mod watcher;

use error::Result;

#[derive(Parser)]
#[command(name = "claude-hindsight")]
#[command(version, about, long_about = None)]
#[command(author = "Codestz <est.estrada@outlook.com>")]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize Claude Hindsight (discover Claude Code sessions)
    Init {
        /// Enable OpenTelemetry integration (optional)
        #[arg(long)]
        enable_otel: bool,
    },

    /// List all Claude Code sessions
    List {
        /// Filter by project name
        #[arg(short, long)]
        project: Option<String>,

        /// Show only sessions with errors
        #[arg(long)]
        errors: bool,

        /// Show last N sessions
        #[arg(short, long)]
        last: Option<usize>,

        /// Show today's sessions only
        #[arg(long)]
        today: bool,

        /// Show sessions with subagents
        #[arg(long)]
        with_subagents: bool,
    },

    /// Watch current session in real-time
    Watch {
        /// Open dashboard in browser
        #[arg(short, long)]
        dashboard: bool,

        /// Session ID (auto-detects current if not provided)
        session_id: Option<String>,
    },

    /// Analyze a session (interactive TUI)
    Show {
        /// Session ID or partial ID
        session_id: String,

        /// Open web dashboard instead of terminal UI
        #[arg(short, long)]
        dashboard: bool,

        /// Port for web dashboard
        #[arg(short, long, default_value = "3939")]
        port: u16,
    },

    /// Search sessions
    Search {
        /// Search query
        query: String,

        /// Filter by tool name
        #[arg(long)]
        tool: Vec<String>,

        /// Show only sessions with errors
        #[arg(long)]
        errors: bool,
    },

    /// Export session to HTML report
    Export {
        /// Session ID
        session_id: String,

        /// Output file path
        #[arg(short, long, default_value = "report.html")]
        output: String,
    },

    /// Manage configuration
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    /// Manage Claude project directories to scan
    Paths {
        #[command(subcommand)]
        action: PathsAction,
    },

    /// Sync index with disk: remove deleted sessions, add new ones, refresh analytics
    Reindex {
        /// Show each session being processed
        #[arg(short, long)]
        verbose: bool,
    },

    /// Start the web dashboard server
    Serve {
        /// Port to listen on
        #[arg(short, long, default_value = "7227")]
        port: u16,

        /// Open browser after starting
        #[arg(long)]
        open: bool,

        /// Port for the embedded OTLP receiver (0 = disable)
        #[arg(long, default_value = "7228")]
        otel_port: u16,
    },

    /// Reset Hindsight state (delete database or entire config directory)
    Clean {
        /// Delete only the sessions database (default)
        #[arg(long)]
        db: bool,

        /// Delete the entire Hindsight config directory (DB + config + all files)
        #[arg(long)]
        all: bool,

        /// Skip confirmation prompt
        #[arg(short, long)]
        yes: bool,
    },

    /// Install Claude Code lifecycle hooks for automatic session indexing
    Integrate {
        /// Remove Hindsight hooks (leave other hooks intact)
        #[arg(long)]
        remove: bool,

        /// Show which settings files have Hindsight hooks installed
        #[arg(long)]
        status: bool,

        /// Install in all configured settings files without prompting
        #[arg(long)]
        all: bool,

        /// Remove and reinstall hooks even if already present (picks up new hooks)
        #[arg(long)]
        force: bool,

        /// Also write OTLP telemetry env vars into settings.json (skips if already set)
        #[arg(long)]
        otel: bool,
    },

    /// Start the OTLP telemetry daemon (background listener on port 7228)
    Daemon {
        /// Port to listen on
        #[arg(short, long, default_value = "7228")]
        port: u16,
        /// Idle timeout in seconds (0 = no timeout). Auto-spawned daemons use 600s.
        #[arg(long, default_value = "0")]
        idle_timeout: u64,
    },

    /// (Internal) Index a session from a Claude Code hook payload on stdin
    #[command(hide = true)]
    HookIndex,

    /// (Internal) Claude Code lifecycle hook dispatcher
    #[command(hide = true)]
    Hook {
        #[command(subcommand)]
        event: HookCommand,
    },
}

#[derive(Subcommand)]
enum HookCommand {
    SessionStart,
    Stop,
    SessionEnd,
    UserPromptSubmit,
    PreToolUse,
    PostToolUse,
    PostToolUseFailure,
    SubagentStart,
    SubagentStop,
    PreCompact,
    PermissionRequest,
    TaskCompleted,
    WorktreeCreate,
    WorktreeRemove,
    ConfigChange,
}

#[derive(Subcommand)]
enum PathsAction {
    /// List all configured scan directories
    List,

    /// Add a directory to scan for Claude sessions
    Add {
        /// Path to add (e.g. ~/.claudep/projects)
        path: String,

        /// Optional human-readable name for this directory (e.g., Work, Personal)
        #[arg(long)]
        name: Option<String>,
    },

    /// Remove a directory (the default ~/.claude/projects cannot be removed)
    Remove {
        /// Path to remove
        path: String,
    },
}

#[derive(Subcommand)]
enum ConfigAction {
    /// Show current configuration
    Show,

    /// Edit configuration in $EDITOR
    Edit,

    /// Reset configuration to defaults
    Reset,

    /// Validate configuration file
    Validate,
}

fn main() {
    if let Err(e) = run() {
        eprintln!("Error: {}", e);
        process::exit(1);
    }
}

fn run() -> Result<()> {
    let cli = Cli::parse();

    // If no command provided, check config for default view
    let command = match cli.command {
        Some(cmd) => cmd,
        None => {
            // Load config to determine default view
            let config = config::Config::load()?;

            match config.ui.default_view.as_str() {
                "last_session" => {
                    // Find and open the most recent session
                    return run_last_session();
                }
                _ => {
                    // Default to projects hub
                    return run_hub();
                }
            }
        }
    };

    // Auto-index new sessions silently before any command (except those that
    // manage indexing themselves, or the hidden hook-index command).
    let skip_auto_index = matches!(
        command,
        Commands::Init { .. }
            | Commands::Reindex { .. }
            | Commands::HookIndex
            | Commands::Hook { .. }
            | Commands::Clean { .. }
            | Commands::Daemon { .. }
    );

    if !skip_auto_index {
        if let Ok(mut index) = storage::SessionIndex::new() {
            match index.sync_new_only() {
                Ok(n) if n > 0 => {
                    eprintln!("  {} new session(s) indexed.", n);
                }
                _ => {}
            }
        }
    }

    match command {
        Commands::Init { enable_otel } => {
            commands::init::run(enable_otel)?;
        }
        Commands::List {
            project,
            errors,
            last,
            today,
            with_subagents,
        } => {
            commands::list::run(project, errors, last, today, with_subagents)?;
        }
        Commands::Watch {
            dashboard,
            session_id,
        } => {
            commands::watch::run(session_id, dashboard)?;
        }
        Commands::Show {
            session_id,
            dashboard,
            port,
        } => {
            commands::show::run(session_id, dashboard, port)?;
        }
        Commands::Search {
            query,
            tool,
            errors,
        } => {
            commands::search::run(query, tool, errors)?;
        }
        Commands::Export { session_id, output } => {
            commands::export::run(session_id, output)?;
        }
        Commands::Paths { action } => match action {
            PathsAction::List => commands::paths::list()?,
            PathsAction::Add { path, name } => commands::paths::add(path, name)?,
            PathsAction::Remove { path } => commands::paths::remove(path)?,
        },
        Commands::Config { action } => match action {
            ConfigAction::Show => commands::config::show_config()?,
            ConfigAction::Edit => commands::config::edit_config()?,
            ConfigAction::Reset => commands::config::reset_config()?,
            ConfigAction::Validate => commands::config::validate_config()?,
        },
        Commands::Reindex { verbose } => {
            commands::reindex::run(verbose)?;
        }
        Commands::Serve { port, open, otel_port } => {
            commands::serve::run(port, open, otel_port)?;
        }
        Commands::Clean { db, all, yes } => {
            commands::clean::run(db, all, yes)?;
        }
        Commands::Integrate { remove, status, all, force, otel } => {
            commands::integrate::run(remove, status, all, force, otel)?;
        }
        Commands::Daemon { port, idle_timeout } => {
            commands::daemon::run(port, idle_timeout)?;
        }
        Commands::HookIndex => {
            commands::hook_index::run()?;
        }
        Commands::Hook { event } => match event {
            HookCommand::SessionStart => commands::hook::run_session_start()?,
            HookCommand::Stop => commands::hook::run_stop()?,
            HookCommand::SessionEnd => commands::hook::run_session_end()?,
            HookCommand::UserPromptSubmit => commands::hook::run_user_prompt_submit()?,
            HookCommand::PreToolUse => commands::hook::run_pre_tool_use()?,
            HookCommand::PostToolUse => commands::hook::run_post_tool_use()?,
            HookCommand::PostToolUseFailure => commands::hook::run_post_tool_use_failure()?,
            HookCommand::SubagentStart => commands::hook::run_subagent_start()?,
            HookCommand::SubagentStop => commands::hook::run_subagent_stop()?,
            HookCommand::PreCompact => commands::hook::run_pre_compact()?,
            HookCommand::PermissionRequest => commands::hook::run_permission_request()?,
            HookCommand::TaskCompleted => commands::hook::run_task_completed()?,
            HookCommand::WorktreeCreate => commands::hook::run_worktree_create()?,
            HookCommand::WorktreeRemove => commands::hook::run_worktree_remove()?,
            HookCommand::ConfigChange => commands::hook::run_config_change()?,
        },
    }

    Ok(())
}

/// Run the main TUI hub
fn run_hub() -> Result<()> {
    use tui::router::Router;
    use tui::EventHandler;

    // Initialize router
    let mut router = Router::new()?;

    // Initialize terminal
    let mut terminal = tui::init()?;
    let mut event_handler = EventHandler::new(250);

    // Main loop
    loop {
        terminal.draw(|f| router.render(f))?;

        if let tui::Event::Key(key) = event_handler.poll()? {
            router.handle_key(key)?;
        }

        // Process periodic updates (debounced search, etc.)
        router.tick();

        if router.should_quit {
            break;
        }
    }

    // Restore terminal
    tui::restore()?;
    Ok(())
}

/// Run the TUI opening the most recent session
fn run_last_session() -> Result<()> {
    use storage::SessionIndex;
    use tui::router::Router;
    use tui::EventHandler;

    // Get the most recent session
    let index = SessionIndex::new()?;
    let latest = index.get_latest()?;

    match latest {
        Some(session_file) => {
            // Create router with the session
            let mut router = Router::new_with_session(session_file.session_id)?;

            // Initialize terminal
            let mut terminal = tui::init()?;
            let mut event_handler = EventHandler::new(250);

            // Main loop
            loop {
                terminal.draw(|f| router.render(f))?;

                if let tui::Event::Key(key) = event_handler.poll()? {
                    router.handle_key(key)?;
                }

                // Process periodic updates (debounced search, etc.)
                router.tick();

                if router.should_quit {
                    break;
                }
            }

            // Restore terminal
            tui::restore()?;
            Ok(())
        }
        None => {
            eprintln!("No sessions found. Run 'hindsight init' to discover sessions.");
            eprintln!("Falling back to projects view...");
            run_hub()
        }
    }
}