agentslog
v0.11.0
Published
Query your Claude Code session history as a local SQLite database
Maintainers
Readme
Every Claude Code session writes a full JSONL transcript to ~/.claude/projects/—every tool call, file edit, token count, and error. That data is already on your disk. You just couldn't ask it anything. Until now.
agentslog indexes all your local agent activity into a blazing-fast SQLite database and gives you a CLI to query across every session you've ever run.
No cloud. No SDK. No account. It runs entirely on your machine and works on your existing history the moment you install it.
💡 Why do I need this?
If you use AI coding agents, you've likely experienced this:
- 🔍 Rogue edits. An agent touched a file it shouldn't have last week. Which session was that, and what else did it change in the same run?
- 💸 Runaway token spend. Your Anthropic bill spiked. Which project, which model, which session is eating all the tokens?
- 🧪 Failed runs. A task that worked yesterday broke today. How did the two runs diverge—different tools, different files, more errors?
The transcripts hold all the answers. agentslog makes them instantly queryable.
🚀 Quick Start
Requires Node.js ≥ 20.
# Install globally
npm install -g agentslog
# Index your existing history (fast & idempotent)
agentslog ingest
# Start querying!
agentslog statsOr wire everything up in one command
agentslog setup does the whole thing automatically — registers the MCP server
for every project, writes the memory instruction, and indexes your history —
and prints exactly what it changed:
agentslog setup # MCP + global memory (zero-latency default)
agentslog setup --with-hooks # also install the error-avoidance + learning hooks
agentslog setup -i # pick each component (Enter = recommended)
agentslog setup --dry-run # preview every change, write nothingEverything is opt-out (--no-mcp, --no-memory, --no-ingest) and idempotent —
re-run it any time; it reports what's already configured. Open a fresh Claude Code
session afterward and run /mcp to confirm.
PERIOD all time
SESSIONS 35
TOKENS 5.1M (in: 160.1k out: 4.9M cached: 614M)
TOOLS 4,102 (errors: 186, 4.5%)
TOP FILES TOUCHES
page.tsx 118
translations.ts 49
CLAUDE.md 34
PRs.md 29
TOP TOOLS CALLS
Bash 1,055
Read 953
Edit 857
Write 279🏗️ How it works
agentslog never touches the network. It reads the transcript files your agents already write, streams them through per-source parsers, links sub-agent runs to the session that spawned them, and builds a structured local index you can query in milliseconds.
flowchart LR
A1["Claude Code<br/>~/.claude/projects"] --> B[Source<br/>adapters]
A2["Cline<br/>(experimental)"] --> B
A3["Aider<br/>(experimental)"] --> B
B -->|streaming parse,<br/>skip corrupt lines| C{Extract}
C --> D[sessions<br/>+ sub-agent links]
C --> E[tool_calls]
C --> F[files_touched]
D --> G[(SQLite<br/>WAL mode)]
E --> G
F --> G
G --> H[agentslog CLI]
H --> I[query · stats · errors<br/>show · diff]
style A1 fill:#1e293b,stroke:#475569,color:#e2e8f0
style A2 fill:#1e293b,stroke:#475569,color:#94a3b8
style A3 fill:#1e293b,stroke:#475569,color:#94a3b8
style G fill:#0f766e,stroke:#14b8a6,color:#f0fdfa
style I fill:#7c3aed,stroke:#a78bfa,color:#f5f3ffA live watch daemon keeps the index fresh as new sessions land:
sequenceDiagram
participant CC as Claude Code
participant FS as ~/.claude/projects
participant W as agentslog watch
participant DB as SQLite (WAL)
participant You as agentslog query
CC->>FS: writes session.jsonl
W-->>FS: chokidar detects change
W->>W: debounce 2s
W->>DB: ingest (atomic txn)
You->>DB: query --file auth.ts
DB-->>You: results (no lock contention)📖 Cookbook
Real problems, one command each.
🔍 Track down a rogue edit
"Something changed
auth.tsand I don't know which run did it."
agentslog query --file auth.tssessions touching auth.ts
SESSION ID TITLE PROJECT MODEL STARTED TOKENS
a1f3c8d2 Refactor auth middleware my-api opus-4-8 4h ago 88.1k
7be09c14 Add rate limiting my-api sonnet-4-6 2d ago 41.7kThen open the offending run in full (see Investigate a session).
💸 Find what's eating your token budget
"My API bill doubled this month. Where did it go?"
agentslog stats --last 30d
agentslog sessions --last 30d # sorted newest-first, with per-session token totals
agentslog sessions --project my-api # narrow to one project🧪 Investigate a failed run
"What exactly did this session do—every tool call, every file, every error?"
agentslog show a1f3c8d2 # accepts any unique id prefixRefactor auth middleware
Session a1f3c8d2-0975-48c8-9b0c-1e10ca3c3a53
Project ~/projects/my-api
Model opus-4-8
Duration 1h 16m
User turns 9
Tokens
Billed in 5,754
Output 140,022
Cache read 9.6M, created 476.1k
Est. cost $23.88 (opus-4-8 list price)
Tool calls: 61 (10 errors)
Bash 25
Edit 15
Agent 8
…
Files touched: 3
FILE R W E
src/auth.ts 1 1 10
src/middleware.ts 2 0 5
README.md 1 0 0
Sub-agents (3)
ID MODEL TOKENS TOOLS TITLE
agent-ad opus-4-8 65.7k 55 research market
agent-ae opus-4-8 45.0k 36 validate idea
agent-ab opus-4-8 60.8k 82 build mvp
Rolled up (session + sub-agents)
Tokens 287,638 (in: 145.6k out: 142.1k)
Tool calls 213 (18 errors)
Est. cost $85.41 (est.)
Transcript: ~/.claude/projects/my-api/a1f3c8d2-…jsonlSub-agent runs (e.g. anything spawned by the Agent tool) are indexed as their
own rows and rolled up into the parent — so the tokens, tool calls, and cost
you see reflect the whole job, not just the main thread.
🪞 Compare two runs of the same task
"Why did today's run fail when yesterday's worked?"
agentslog diff a1f3c8d2 7be09c14 A: a1f3c8d2 B: 7be09c14
title Refactor auth middleware Add rate limiting
model opus-4-8 sonnet-4-6
tokens 146.8k 116.1k
tool calls 63 40
Tool usage (A vs B)
Bash 27 11 -16
Edit 15 1 -14
PowerShell 0 21 +21🚨 Triage what's been failing
"What tool calls have been erroring lately, and in which sessions?"
agentslog errors --last 7dRecent tool-call failures (last 7d) — showing 3
✗ Bash · my-api · 2d ago
$ npm run build
Exit code 1: error TS2345: Argument of type 'string' is not assignable…
↳ session a1f3c8d2 "Refactor auth middleware"
✗ Edit · my-api · 2d ago
src/auth.ts
<tool_use_error>String to replace not found in file.
↳ session a1f3c8d2 "Refactor auth middleware"A sub-agent failure is attributed to the top-level session that spawned it, so
the ↳ session line is always something you can open with agentslog show.
⚙️ Audit a specific tool's usage
"Which sessions spawned sub-agents / ran shell commands / hit the web?"
agentslog query --tool Agent # sessions that spawned sub-agents
agentslog query --tool Bash # sessions that ran shell commands📡 Keep the index live
"Index new sessions automatically as I work."
agentslog watch # run in the background; indexes on the flyTime windows:
--lastacceptsNs,Nm,Nh,Nd,Nw(seconds, minutes, hours, days, weeks). Machine-readable: add--jsontosessions,query, andstatsfor piping intojqor scripts.
🧠 Give your agent a memory
The same history is even more useful to the agent than to you. Coding agents are stateless — they forget everything between sessions. agentslog can feed that memory back so an agent stops repeating its own mistakes.
Stop repeating failures (a PreToolUse hook). Before every tool call,
agentslog checks whether the same kind of command failed before — and whether any
recorded lesson applies — and warns in real time:
$ echo '{"tool_name":"Bash","tool_input":{"command":"ls -Recurse src"}}' | agentslog hook check
⚠ agentslog memory: you (or a past session) hit 1 similar Bash failure(s) before:
- 15h ago: `ls "C:/…/src" -Recurse -Name` → Exit code 2: ls: unknown option -- e
Consider adjusting before running this.Lesson hits are recorded only when a lesson actually fires here — not in bulk at
session start — so agentslog lessons hit counts reflect real recall, not noise.
Block known-fatal calls, don't just warn (opt-in enforcement). Advisories are
non-blocking by default — the agent can ignore them, and sometimes does. For
deterministic gotchas (a command/file whose mere presence guarantees failure,
e.g. python3 on a Windows box, or a PowerShell cmdlet inside the Bash tool),
mark the lesson enforce and a matching PreToolUse is escalated from a warning
to a permission decision:
agentslog lesson add --rule "Use python, not python3 — python3 hits the MS Store stub" \
--trigger python3 --tool Bash --enforceEnforcement is opt-in twice over: a lesson must carry the enforce flag and
AGENTSLOG_ENFORCE must not be off. It defaults to ask (a permission prompt,
always overridable); set AGENTSLOG_ENFORCE=deny to harden to an outright block,
or AGENTSLOG_ENFORCE=off as a global kill switch. Heuristic lessons (a cd or
gh nudge) stay advisory — only flagged, trigger-bearing lessons can ever block,
so common commands are never caught.
Warm up subagents too (a SubagentStart hook). A subagent spawned by the
Agent tool never gets a SessionStart, so it used to start cold — with no
lesson digest. The SubagentStart hook injects the top lessons up front so a
subagent begins with the same gotchas the parent session got. (The PreToolUse
hook fires inside subagents regardless; this just front-loads the context.)
Learn automatically after each session (a Stop hook). After every session
agentslog re-indexes the transcript and runs reflectOnSession — if the same
command failed ≥ 2 times, a lesson is recorded automatically so the next session
is warned before it tries again.
Query history mid-task (MCP server). Register agentslog as an MCP server and
the agent gets read tools — recent_errors, find_sessions_by_file,
search_reasoning, and more — to consult its own past on demand:
claude mcp add agentslog -- agentslog mcp # this project onlyTurn it on for every project (global setup). The easy way is one command —
agentslog setup (see Quick Start) does both steps below for
you and prints what it changed. Prefer to do it by hand? Register the server at
user scope so every Claude Code session gets the tools, then add a short
instruction to your global memory so the agent actually reaches for them:
# 1. Register once, globally (any project picks it up at startup)
claude mcp add agentslog --scope user -- agentslog mcp<!-- 2. Add to ~/.claude/CLAUDE.md so the agent uses the tools by reflex -->
## agentslog — your own coding history
You have the `agentslog` MCP server: a searchable index of your past
coding-agent sessions across every project on this machine. Use it to avoid
repeating past mistakes.
- **Before a tricky, slow, or destructive shell command**, call `recent_errors`
to check whether you (or a past session) already failed at it, and why.
- **Before editing a file you've struggled with**, call `find_sessions_by_file`
to see what changed there before and what broke.
- **Check `list_lessons`** when unsure how to do something in a project.
- **When you hit a non-obvious gotcha**, call `record_lesson` (with a short
exact `trigger`, e.g. `ls -Recurse`) so future sessions avoid it.
### When something breaks, diagnose with agentslog first
Treat agentslog as the first diagnostic step for any error or "this used to
work" regression — before guessing or re-reading code. Chain the tools like a
debugger:
- An **error or failed command** → `recent_errors` (filter by the failing tool
and project) to see if it happened before and how it was resolved.
- A **file misbehaving** → `find_sessions_by_file`, then `get_session` on the
suspect run for its full tool-call trace.
- **"It worked yesterday"** → find the last good run and `get_session` both to
compare what diverged.
- **Before undoing past work** → `search_reasoning` to recover the original
intent so you don't reintroduce a bug a past session fixed.
- **After the fix** → `record_lesson` so the next occurrence is caught instantly.MCP servers load at session start, so open a fresh Claude Code session after registering, then run
/mcpto confirmagentslogis connected. This is the zero-latency path — no hooks required; the tools are simply available and the memory instruction nudges the agent to use them.
Is it actually helping? (agentslog impact). Once the agent has started
using agentslog, this contrasts your activity before vs after adoption — the
cutover is auto-detected from the first session that called an agentslog tool:
agentslog impactagentslog impact — before vs after adoption
cutover: 2026-05-18 (first agentslog tool use)
BEFORE AFTER Δ
Sessions 40 37 —
Avg tool calls / session 188.4 151.0 -19.9%
Avg tokens / session 210.6k 176.2k -16.3%
Error rate 5.3% 3.1% -41.5%
Avg errors / session 10.0 4.7 -53.0%It's an honest correlation, not a controlled experiment — but it's a quick
read on whether the agent is repeating fewer mistakes. Override the baseline with
--since 30d / --since 2026-01-01, or add --json for scripting.
Recall the why, not just the what (reasoning search). Opt in to indexing the agent's thinking and search the reasoning behind past decisions:
agentslog ingest --reasoning
agentslog reasoning "why natural sort"Learn from its own mistakes (self-improvement). agentslog flags inefficient runs and turns them into durable lessons — recorded automatically on repeated failures, by the agent via an MCP tool, or by you — then recalls them before the agent repeats itself:
agentslog review --last 7d # which runs were inefficient, and why
agentslog lesson add --rule "Use Get-ChildItem, not ls -Recurse" --trigger "ls -Recurse"
agentslog lessons # the rules it has learnedLessons live only in your local DB (never auto-written to CLAUDE.md) and
resurface at PreToolUse and SessionStart.
Full setup — hooks, MCP, reasoning indexing, and the learning loop — is in docs/AGENT-INTEGRATION.md.
🔒 Architecture & Privacy
Everything stays on your machine. Here's what makes it trustworthy and fast:
- Local-only, zero network.
agentslogmakes no outbound calls—ever. It only reads transcript files your agents already wrote. - Streaming parser. Transcripts are read line-by-line via Node's
readline, so multi-megabyte sessions index with constant memory. Partially-written or corrupt lines (from a crash orCtrl+Cmid-session) are skipped silently rather than halting the ingest. - Sub-agent rollup. Sub-agent (sidechain) transcripts are indexed as their own rows and linked to the parent that spawned them, so tokens, tool calls, files, and cost roll up into the top-level session everywhere you look.
- Honest token accounting.
input_tokensis the sum of every assistant usage block—what you were actually billed. Because every request re-sends the full history, this is large by design, and it's the number that matters for cost. - Cost estimates, clearly labelled. Per-model list prices (overridable) turn token counts into an estimated dollar figure in
statsandshow. Unknown models are reported as a lower bound, never a misleading$0. - Idempotent ingest. Re-ingesting a session replaces its rows atomically in one transaction. Run
ingestorwatchas often as you like; nothing duplicates. - Safe under concurrency. The database runs in WAL mode with a busy timeout, so the
watchdaemon and a manual query can hit it at the same time without locking each other out. - Stable project grouping. Sessions are grouped by their
~/.claude/projects/directory name (project_hash), which never changes even if you rename the folder. The displayed path is the most recentcwdseen for that group.
Storage
The database lives in your OS application-data directory (resolved via env-paths), never inside ~/.claude/—so a Claude Code update can't wipe it.
| OS | Location |
|----|----------|
| macOS | ~/Library/Application Support/agentslog/ |
| Linux | ~/.local/share/agentslog/ |
| Windows | %LOCALAPPDATA%\agentslog\ |
Data model
erDiagram
sessions ||--o{ tool_calls : has
sessions ||--o{ files_touched : has
sessions {
text id PK
text parent_session_id FK
text source
text project_hash
text ai_title
text model
int input_tokens
int output_tokens
int error_count
}
tool_calls {
text id PK
text session_id FK
int sequence_num
text tool_name
text file_path
int success
}
files_touched {
text session_id FK
text file_path
int read_count
int write_count
int edit_count
}🛠️ Development
This project uses pnpm.
git clone https://github.com/MohammadYusif/agentslog.git
cd agentslog
pnpm install
pnpm build
pnpm link --global # installs the `agentslog` binary globally
pnpm dev # rebuild on change
pnpm test # vitest suite
pnpm check # biome lint + format check
pnpm typecheck # tsc --noEmitSee CONTRIBUTING.md and docs/ADAPTERS.md to add support for another agent.
🧩 Other sources (experimental)
Beyond Claude Code, agentslog can ingest other agents' histories. The Cline and
Aider adapters have been hardened against a range of real-world transcripts:
- Cline — validated against its published message schema and real tasks
spanning 2024–2026: the modern timeline (
say:"tool") and older transcripts where tool use lives inapi_conversation_history.json(nativetool_useblocks or XML tags), which the parser recovers automatically. Newersaytypes (reasoning,checkpoint_created) are ignored cleanly; token sums verified exact throughout. - Aider — fuzzed across many real
.aider.chat.history.mdfiles (through v0.86) including thediff-fencededit format, file reads/edits, and Windows paths; edit/read/token extraction matched a raw cross-check on every file. - Odysseus — a self-hosted AI workspace that stores chats in a SQLite database rather than transcript files. agentslog opens that DB read-only and emits one session per non-archived chat, deriving tokens and tool/file activity from the session columns and per-message metadata. Unlike Cline/Aider, this adapter is not yet validated against real-world databases — it's best-effort.
They're all marked experimental because that sampling (or, for Odysseus, the lack of it) can't cover every version and model — not because the basics are unproven. Please report any format mismatches you hit.
Cline (
saoudrizwan.claude-dev): auto-detected from VS Code'sglobalStorage. PointAGENTSLOG_CLINE_DIRat a non-standard location (VS Codium, Cursor) if needed.Aider: Aider writes
.aider.chat.history.mdinto each repo, so there's no central location—tellagentslogwhere to look:# one or more repos / history files, delimited like PATH AGENTSLOG_AIDER_PATHS="~/code/project-a:~/code/project-b" agentslog ingest agentslog sessions --source aiderOdysseus: no central registry—point
agentslogat its SQLite database directly:AGENTSLOG_ODYSSEUS_DB="~/odysseus/data/app.db" agentslog ingest agentslog sessions --source odysseus
Pricing for non-Claude models isn't built in; add your own via a pricing.json
in the app-data directory or the AGENTSLOG_PRICING env var.
⚠️ Limitations
- Cline & Aider are experimental. Their parsers are validated against real sample transcripts and Cline's published schema, but not across every version and config—Claude Code remains the fully-supported path.
- Cost is an estimate. Figures use per-model list prices, not your actual invoice; prices change and historical sessions may have been billed differently.
impactis a correlation. The before/after comparison reflects how your activity changed around adoption—not a controlled experiment proving causation.- Terminal only. Plain colored output—no web UI or TUI.
License
MIT © MohammadYusif
