agentleFS
JayantDevkarJayantDevkar/claude-code-karma/api/CLAUDE.md

claude-code-karma / api

CLAUDE.md328 starsChanged 4 months agoApache-2.0View on GitHub

Claude Code Karma API — FastAPI backend for monitoring and analyzing Claude Code sessions. Parses Claude Code's local storage (~/.claude/) and exposes REST endpoints for the SvelteKit frontend. Project paths are URL-encoded: leading / becomes -, all / become - - /Users/me/repo → -Users-me-repo

  • Installs packages

The file

We split this CLAUDE.md into the rules it gives an agent

1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All Pydantic models use ConfigDict(frozen=True) for immutability.

    line 113

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Project Overview

Claude Code Karma API — FastAPI backend for monitoring and analyzing Claude Code sessions. Parses Claude Code's local storage (~/.claude/) and exposes REST endpoints for the SvelteKit frontend.

Quick Start

# Install dependencies
pip install -e ".[dev]"
pip install -r requirements.txt

# Run API server
uvicorn main:app --reload --port 8020

Commands

# Development
uvicorn main:app --reload --port 8020      # Run dev server

# Testing
pytest                                      # Run all tests
pytest tests/test_session.py -v            # Single test file
pytest tests/api/ -v                       # API tests only
pytest --cov=models --cov=routers          # With coverage

# Linting & Formatting
ruff check models/ tests/ routers/         # Lint
ruff format models/ tests/ routers/        # Format

# Utilities
python session_story.py /path/to/project   # Generate session report
python session_story.py /path/to/project --session-uuid abc123

Architecture

Directory Structure

api/
├── main.py              # FastAPI app entry point
├── config.py            # Settings (CLAUDE_DIR, KARMA_DIR paths)
├── schemas.py           # Pydantic response schemas
├── routers/             # API route handlers
│   ├── projects.py      # Project listing and details
│   ├── sessions.py      # Session data, timeline, tools
│   ├── analytics.py     # Project/session analytics
│   ├── agents.py        # Agent listing
│   ├── agent_analytics.py # Agent usage analytics
│   ├── skills.py        # Skill usage tracking
│   ├── history.py       # File history endpoints
│   ├── live_sessions.py # Real-time session tracking
│   ├── subagent_sessions.py # Subagent session details
│   └── settings.py      # User settings
├── services/            # Business logic layer
│   ├── session_relationships.py  # Chain detection
│   └── tool_results.py           # Tool result handling
├── middleware/          # HTTP middleware
│   └── caching.py       # Response caching
├── models/              # Pydantic models for parsing
│   ├── project.py       # Project entry point
│   ├── session.py       # Session conversation
│   ├── agent.py         # Subagent conversations
│   ├── message.py       # Message types
│   ├── content.py       # Content blocks
│   ├── usage.py         # Token stats
│   ├── live_session.py  # Real-time state
│   ├── session_relationship.py  # Chain links
│   └── compaction_detector.py   # Compaction detection
└── tests/               # Pytest test suite

Model Hierarchy

Project (entry point)
├── Session ({uuid}.jsonl)
│   ├── Message (UserMessage, AssistantMessage, FileHistorySnapshot, SummaryMessage)
│   ├── Agent (subagents in {uuid}/subagents/)
│   ├── ToolResult ({uuid}/tool-results/toolu_*.txt)
│   └── TodoItem (~/.claude/todos/{uuid}-*.json)
└── Agent (standalone: agent-{id}.jsonl)

Claude Code Storage Locations

DataLocation
Session JSONL~/.claude/projects/{encoded-path}/{uuid}.jsonl
Subagents~/.claude/projects/{encoded-path}/{uuid}/subagents/agent-*.jsonl
Tool Results~/.claude/projects/{encoded-path}/{uuid}/tool-results/toolu_*.txt
Debug Logs~/.claude/debug/{uuid}.txt
Todos~/.claude/todos/{uuid}-*.json
Live Sessions~/.claude_karma/live-sessions/{slug}.json

Path Encoding

Project paths are URL-encoded: leading / becomes -, all / become -

  • /Users/me/repo → -Users-me-repo

Key Patterns

Lazy Loading

Messages loaded via iter_messages() to avoid memory issues with large sessions. Access session.messages for list, session.iter_messages() for generator.

Frozen Models

All Pydantic models use ConfigDict(frozen=True) for immutability. Tests must catch ValidationError for mutation attempts.

Session Chains

Related sessions detected via:

  • leaf_uuid in summary messages (95% confidence)
  • Slug matching (85% confidence)

Compaction Detection

Sessions with SummaryMessage indicate compacted/resumed conversations. Use CompactionDetector to identify.

Live Sessions

Real-time state tracked in ~/.claude_karma/live-sessions/{slug}.json via Claude Code hooks (captain-hook library).

API Endpoints

Route PrefixDescription
/projectsProject listing, details, sessions
/sessionsSession data, timeline, tools, file activity
/analyticsProject/session analytics, usage stats
/agentsAgent listing and subagent sessions
/live-sessionsReal-time session state (+ POST /live-sessions/{id}/focus-terminal to raise the session's terminal window)
/historyFile history snapshots
/settingsUser preferences
/skillsSkill usage tracking
/desktop-appInstall/manage the native desktop launcher — GET status, POST install, PUT autostart, DELETE install (localhost-only)

Key Endpoints

MethodEndpointDescription
GET/projectsList all projects
GET/projects/{encoded_name}Project details with sessions
GET/sessions/{uuid}Session details
GET/sessions/{uuid}/timelineEvent timeline
GET/sessions/{uuid}/toolsTool usage breakdown
GET/sessions/{uuid}/file-activityFile operations
GET/sessions/{uuid}/subagentsSubagent activity
GET/analytics/projects/{encoded_name}Project analytics
GET/sessions/resolve/{short_id}Resolve a UUID/prefix to its project (short links)
POST/sessions/{uuid}/resume-in-terminalFocus if live, else launch claude --resume in a new terminal

Core Classes

ClassFilePurpose
Projectmodels/project.pyEntry point, encodes/decodes paths, lists sessions
Sessionmodels/session.pyMain conversation, aggregates usage stats
Agentmodels/agent.pyBoth standalone and subagent conversations
parse_message()models/message.pyParses UserMessage, AssistantMessage, etc.
parse_content_block()models/content.pyParses TextBlock, ToolUseBlock, etc.
TokenUsagemodels/usage.pyToken stats with __add__ for aggregation
LiveSessionmodels/live_session.pyReal-time session state from hooks
SessionRelationshipmodels/session_relationship.pyChain links between sessions
CompactionDetectormodels/compaction_detector.pyIdentifies compacted sessions

Testing

Tests use pytest fixtures in tests/conftest.py that create temporary ~/.claude directory structures with sample JSONL data.

# Run specific test categories
pytest tests/test_session.py       # Model tests
pytest tests/api/                  # Endpoint tests
pytest -k "test_usage"             # Tests matching pattern

Dependencies

  • Python 3.10+
  • FastAPI - Web framework
  • Pydantic 2.x - Data validation
  • aiofiles - Async file I/O
  • cachetools - Response caching
  • pytest - Testing framework
  • ruff - Linting and formatting

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.