Skip to main content

Git-backed Claude Code session backup with timeline view, folder analysis, deletion detection, and session restore.

Project description

Claude-Session-Backup

PyPI Release Date Python 3.10+ License: GPL v3 Installs Platform

Git-backed Claude Code session backup with timeline view, folder analysis, deletion detection, and session restore.

The Problem

Claude Code stores session data in ~/.claude/projects/ as JSONL files. These can be silently deleted during upgrades, lossy-compacted via /compact, or lost when session compatibility breaks between versions. Once gone, your conversation history -- including debugging sessions, architectural decisions, and code review context -- is unrecoverable.

csb preserves every session in your existing ~/.claude git repository, builds a searchable metadata index, detects deletions, and can restore lost sessions from git history.

[!WARNING] Prealpha software. csb is functional and all tests pass, but it is not yet feature-complete and has not been broadly tested outside of active dogfooding. Expect bugs, rough edges, and breaking changes until the first alpha/beta releases. Three items gate the next milestone: distilled conversation backup (#12), end-to-end restore verification (#13), and a CLI launcher for claude-code-history-viewer (#14). By all means use it -- and please file issues -- but don't rely on csb as your only backup just yet.

Quick Start

Three commands install everything -- the CLI plus the Claude Code plugin that fires backups automatically on PreCompact and SessionEnd:

# 1. Install the csb CLI
pip install claude-session-backup

# 2. Add the DazzleML marketplace (one-time)
claude plugin marketplace add "DazzleML/Claude-Session-Backup"

# 3. Install the plugin -- registers the PreCompact + SessionEnd hooks
claude plugin install claude-session-backup@dazzle-claude-session-backup

Then verify it works:

# Build the index from existing sessions (no git commits yet)
csb backup --no-commit

# See your session timeline
csb list

# Full backup with git commits (separate noise + user commits, unsigned)
csb backup

[!TIP] Pair with claude-session-logger for the full story. csb preserves Claude Code's session transcripts (projects/<slug>/<uuid>.jsonl). The logger captures the richer per-session data alongside them -- tool calls, shell commands, agent dispatches -- written to ~/.claude/sesslogs/. csb backs up those logger files too (it backs up everything under ~/.claude/ via the noise commits), and csb restore brings the whole footprint back together: transcript + subagents + tool-results + logger state + sesslogs. The two projects are independent (csb works fine without the logger) but they're designed to complement each other.

Features

  • Full session preservation: Every byte of JSONL, subagent data, tool results backed up via git
  • Timeline view: Sessions sorted by last use with relative dates, start folder, and top N working directories
  • Folder analysis: See where work actually happened -- the most-used folder is highlighted
  • Deletion detection: Know when Claude Code removes a session you previously tracked
  • Session restore: Recover deleted sessions from git history with csb restore
  • Two-commit model: Noise (transient state) and user (configs, skills) committed separately
  • Unattended operation: --no-gpg-sign, --quiet, lock file -- designed for cron and Task Scheduler
  • Cross-platform: Works on Windows, Linux, macOS, BSD

Commands

csb backup                            # Scan, index, git commit (noise + user)
csb backup --no-commit                # Scan and index only
csb list [-n 20]                      # Timeline view (default sort: last-used)
csb list [keyword]                    # Filter by keyword in name/project/folders
csb list --sort expiration            # Sort by soonest-to-purge first
csb list --sort {last-used|expiration|started|oldest|messages|size}
csb list --deleted                    # Show deleted sessions
csb scan                              # Find sessions touching cwd (path-prefix)
csb scan <term>                       # Filter by term: name, project, folder paths
csb scan ./<dirname>                  # Shortcut: same as -d <dirname> (no flag to remember)
csb scan -d <pattern>                 # Path-strict: folder + descendants
csb scan -D <pattern>                 # Path-strict: this folder only, no descendants
csb scan -s <pattern>                 # start_folder only ("what sessions originated here?")
csb scan -d <pattern> <term>          # Scope-then-filter combined
csb scan -d <pattern>* / -D <pattern>* / -s <pattern>*  # Trailing-* wildcard
csb scan ... -NU                      # Skip folder-usage search (start_folder only)
csb status                            # Summary stats
csb show <session-id>                 # Detailed session info with folder analysis
csb search "query"                    # Search transcript content (USER/AI/AGENT messages)
csb search -E "regex.*pattern"        # Regex mode (Python re)
csb search "X" -C 3                   # Show 3 events of context before AND after each hit
csb search "X" -A 5 -B 2              # Asymmetric context (5 after, 2 before)
csb search "X" --source convo         # Force a source channel; auto = convo > sesslog > jsonl
csb search "X" --session <uuid>       # Constrain to one session by UUID prefix
csb search "X" --json                 # NDJSON output for piping into jq
csb restore <session-id>              # Restore deleted session from git history
csb resume <session-id>               # Launch claude --resume with full UUID
csb update rebuild-index              # Safely reconstruct SQLite (preserves deleted-session metadata)
csb update build-fts5                 # Build / refresh per-project FTS5 content index
csb update backfill-deleted           # Discover culled sessions from git history; auto-repair sparse rows
csb config [key] [value]              # View/edit csb's own configuration
csb config settings:cleanupPeriodDays         # View Claude Code's session purge TTL
csb config settings:cleanupPeriodDays 365     # Set the TTL (writes ~/.claude/settings.json)

Searching conversations

Use csb search to find old sessions by what was discussed, not just by folder or name. The query is a case-insensitive literal substring by default; -E switches to Python regex.

Under the hood csb search consults per-project FTS5 indexes (SQLite's built-in full-text search engine, the same one that powers many IDE/Mail search bars). Run csb update build-fts5 once to build them; after that, searching tens of thousands of messages is sub-second because FTS5 is an inverted-index lookup, not a LIKE '%word%' linear scan. What's indexed: every USER prompt, AI/assistant response, and subagent (AGENT) sidechain transcript -- plus tool calls and outputs when the raw <uuid>.jsonl is the source (the .convo* / .sesslog* sources from claude-session-logger are USER/AI/AGENT-only by design). csb stores one FTS5 database per project (~/.claude/csb-fts/<project>__<hash>_<user>.db) so search stays fast even when individual projects accumulate years of history.

# Find every session where you talked about OAuth callbacks
csb search "oauth callback"

# Regex with context (3 events above and below each hit)
csb search -E "refresh.*token" -C 3

# Constrain to one session and one source channel
csb search "auth flow" --session 916441e6 --source convo

# Pipe results into another tool
csb search "rate limit" --json | jq -r '.session_id' | sort -u

Per-session source preference is .convo* (preferred, USER/AI/AGENT-only) -> .sesslog* (filtered to USER/AI/AGENT) -> <uuid>.jsonl (authoritative fallback). New sessions logged by claude-session-logger get the cleanest .convo* source; older sessions fall through to JSONL automatically. Hits are sorted by session last-used time, so the most recent matches surface first.

For metadata search (folder paths, project, session name), use csb list <filter> or csb scan <term> -- those are the right tools for "find sessions in this folder" rather than "find sessions about this topic."

Finding sessions at risk of purge

Claude Code auto-deletes sessions after cleanupPeriodDays (default 30). To see which of your sessions are closest to being purged:

csb list --sort expiration -n 20

Sessions are sorted by the JSONL file's modification time, so active sessions (which refresh their mtime on every interaction) stay safe while dormant sessions surface to the top of the expiration list.

To view or change the TTL itself without hand-editing settings.json:

csb config settings:cleanupPeriodDays         # show current value + source + guidance
csb config settings:cleanupPeriodDays 365     # keep transcripts for a year
csb config settings:cleanupPeriodDays 36500   # effectively never purge (~100 years)

The settings: prefix is a fully-qualified namespace: a bare key (e.g. csb config display_top_folders) addresses csb's own config, while a settings: key addresses Claude Code's ~/.claude/settings.json -- the two never collide. The write is a read-merge-write that preserves your other settings and refuses to touch a malformed file.

[!CAUTION] cleanupPeriodDays of 0 does not mean "keep forever" -- Claude Code treats it as disable session persistence and deletes all transcripts at its next startup. csb refuses to write 0 without --force. For "never purge", set a large number instead.

How It Works

flowchart LR
    subgraph GitRepo["~/.claude/ (your git repo)"]
        direction TB
        Data["projects/*.jsonl<br>session-states/<br>file-history/"]
    end

    subgraph CSB["csb Tool"]
        direction TB
        Scripts["scanner.py<br>metadata.py<br><i>(extract names, dates, folders)</i>"]
        Restore["restore.py"]
    end

    DB[("session-backup.db<br>(rebuildable metadata cache)")]

    Data -- "scan & read" --> Scripts
    Scripts -- "upsert" --> DB
    Scripts -- "git add + commit" --> Data
    Data -- "git show {commit}:path" --> Restore

Key principle: Git is the source of truth. The SQLite database is a rebuildable index for fast queries. If the DB is lost or corrupted, csb update rebuild-index reconstructs it while preserving deleted-session metadata. See docs/maintenance.md for the csb update family of maintenance verbs.

Automation

Claude Code Plugin (recommended)

The repository ships as a Claude Code plugin that registers PreCompact and SessionEnd hooks automatically. You can install it straight from GitHub -- no clone required:

# Add the DazzleML marketplace (one-time)
claude plugin marketplace add "DazzleML/Claude-Session-Backup"

# Install the plugin
claude plugin install claude-session-backup@dazzle-claude-session-backup

Alternatively, if you already have a clone for development:

# From a clone of this repo
claude plugin marketplace add ./
claude plugin install claude-session-backup@dazzle-claude-session-backup

The plugin uses a Node.js bootstrapper (run-hook.mjs) to find the correct Python binary on each platform, so it works reliably on Windows, Linux, and macOS without any shell quoting concerns. PreCompact fires synchronously before /compact to preserve full conversation detail; SessionEnd fires on exit to catch any remaining changes.

Manual hook installation

If you prefer to manage hooks yourself, add this to ~/.claude/settings.json:

{
  "hooks": {
    "PreCompact": [{"hooks": [{"type": "command", "command": "csb backup --quiet"}]}],
    "SessionEnd": [{"hooks": [{"type": "command", "command": "csb backup --quiet &"}]}]
  }
}

Or use python install.py in the repo to copy the hook script and print the snippet.

Cron (Linux/Mac)

Belt-and-suspenders periodic backup as a safety net:

*/15 * * * * /usr/local/bin/csb backup --quiet 2>/dev/null

Task Scheduler (Windows)

schtasks /create /tn "Claude Session Backup" /tr "csb backup --quiet" /sc minute /mo 15

Recovery

When Claude Code purges a session you wanted to keep, csb can recover it from your ~/.claude git history. The restore path is byte-exact regardless of host git's core.autocrlf settings, on every platform csb supports.

Finding what was deleted

csb list --deleted                  # Every session csb has flagged deleted, all projects
csb list amd --deleted              # Filtered: only deleted sessions matching "amd"
csb scan --deleted                  # Deleted sessions touching cwd (or any folder)
csb scan -d /path/to/proj --deleted # Scoped to a specific folder (folder + descendants)
csb scan --deleted --all-folders    # Don't truncate the per-session folder list

The default csb list and csb scan hide deleted sessions (active-only view); the bottom of csb list shows a one-line footer when there are deleted sessions matching your filter so you don't have to remember to check.

Recovering one session

csb restore <session-uuid>          # Full UUID required when DB has no row for it
csb restore <prefix>                # Prefix works when the session IS in csb's DB
csb restore <uuid> --dry-run        # Preview commit + target path without writing

If csb's DB doesn't have a row for the session (e.g., on a fresh machine), csb restore falls back to walking git log --all for projects/*/<uuid>.jsonl. It needs the full UUID for the fallback path. To discover deleted sessions from git that aren't in the live DB, use csb update backfill-deleted (see docs/maintenance.md).

Recovering many sessions at once

csb scan -d <pattern> --deleted --restore --dry-run    # Preview the whole set
csb scan -d <pattern> --deleted --restore              # Confirm prompt for >1 file
csb scan -d <pattern> --deleted --restore --yes       # Skip the prompt
csb scan -d <pattern> --deleted --restore --force     # Overwrite existing on-disk files

Bulk restore takes the same backup_lock as csb backup, so it won't race a concurrent backup. Per-file status (OK / SKIP / FAIL) is printed; the final line summarizes counts.

What csb restore does NOT do

  • It does NOT modify any other Claude Code state files. Only the JSONL is written back to its original projects/<slug>/<uuid>.jsonl location.
  • It does NOT preserve the original mtime — restored files have mtime=now (a known limitation; affects the --sort expiration view until the next backup cycle).
  • It does NOT (yet) restore subagent or tool-result subdirectory contents alongside the JSONL — separate follow-up if testing shows the JSONL alone isn't enough for claude --resume.

Requirements

  • Python 3.10+
  • Git (for backup storage)
  • ~/.claude/ initialized as a git repository (git -C ~/.claude init)

Installation

# From PyPI (recommended)
pip install claude-session-backup

# Latest unreleased build from GitHub
pip install git+https://github.com/DazzleML/Claude-Session-Backup.git

# From source (development / contributing)
git clone https://github.com/DazzleML/Claude-Session-Backup.git
cd Claude-Session-Backup
pip install -e ".[dev]"

Contributing

Contributions welcome! See CONTRIBUTING.md.

Acknowledgements

This project draws inspiration and patterns from:

License

Claude-Session-Backup, Copyright (C) 2026 Dustin Darcy

Licensed under the GNU General Public License v3.0 (GPL-3.0) -- see LICENSE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

claude_session_backup-0.3.16.tar.gz (256.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

claude_session_backup-0.3.16-py3-none-any.whl (162.1 kB view details)

Uploaded Python 3

File details

Details for the file claude_session_backup-0.3.16.tar.gz.

File metadata

  • Download URL: claude_session_backup-0.3.16.tar.gz
  • Upload date:
  • Size: 256.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for claude_session_backup-0.3.16.tar.gz
Algorithm Hash digest
SHA256 aa44087981b0cb5f0f47b7d9d55a485c5c00bf264e723ff4a7b2d913268fc0c5
MD5 2eca9986b0a8ec80bcae194315b5adb2
BLAKE2b-256 963af6a0af6166d2482ea439ddfd9da72be510689a4de79be424937111b3084f

See more details on using hashes here.

Provenance

The following attestation bundles were made for claude_session_backup-0.3.16.tar.gz:

Publisher: release.yml on DazzleML/Claude-Session-Backup

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file claude_session_backup-0.3.16-py3-none-any.whl.

File metadata

File hashes

Hashes for claude_session_backup-0.3.16-py3-none-any.whl
Algorithm Hash digest
SHA256 d2a7ec082c4b8f8a40438de458298aa69d9b8ec0773e652ef2745fa955008787
MD5 5143043c334f4efd7e8e3a84dbf4c457
BLAKE2b-256 3617ea07268b43e39bcbefe417e0c871b2de2563edd3fa55a82a9c4a7c069792

See more details on using hashes here.

Provenance

The following attestation bundles were made for claude_session_backup-0.3.16-py3-none-any.whl:

Publisher: release.yml on DazzleML/Claude-Session-Backup

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page