claudehistory

package
v0.18.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Package claudehistory reads Claude Code conversation history from ~/.claude/projects/

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChatMessage

type ChatMessage struct {
	ID              string    `json:"id"`
	SessionID       string    `json:"session_id"`
	TurnNumber      int       `json:"turn_number"`
	Role            string    `json:"role"`
	ContentText     string    `json:"content_text,omitempty"`
	ContentThinking string    `json:"content_thinking,omitempty"`
	ContentJSON     string    `json:"content_json,omitempty"`
	TokensIn        int       `json:"tokens_in"`
	TokensOut       int       `json:"tokens_out"`
	Model           string    `json:"model,omitempty"`
	RequestID       string    `json:"request_id,omitempty"`
	Timestamp       time.Time `json:"timestamp"`
	CreatedAt       time.Time `json:"created_at"`
}

ChatMessage represents a chat message stored in the database.

type ContentBlock

type ContentBlock struct {
	Type string `json:"type"` // "thinking", "text", "tool_use", "tool_result"

	// For type="text"
	Text string `json:"text,omitempty"`

	// For type="thinking"
	Thinking string `json:"thinking,omitempty"`

	// For type="tool_use"
	ToolUse *ToolUseBlock `json:"tool_use,omitempty"`

	// For type="tool_result"
	ToolResult *ToolResultBlock `json:"tool_result,omitempty"`
}

ContentBlock represents a block of content within a message. Only one of the content fields will be populated based on Type.

type ImportStatus

type ImportStatus struct {
	SessionID    string    `json:"session_id"`
	FilePath     string    `json:"file_path"`
	FileMtime    time.Time `json:"file_mtime"`
	MessageCount int       `json:"message_count"`
	ImportedAt   time.Time `json:"imported_at"`
}

ImportStatus represents the import status of a session.

type Importer

type Importer struct {
	// contains filtered or unexported fields
}

Importer syncs Claude Code JSONL conversation history to observatory.db. It tracks which files have been imported and only imports new/modified files.

func NewImporter

func NewImporter(db *sql.DB) *Importer

NewImporter creates a new Importer with a database connection.

func NewImporterWithReader

func NewImporterWithReader(db *sql.DB, reader *Reader) *Importer

NewImporterWithReader creates an Importer with a custom reader (for testing).

func (*Importer) GetAllImportStatus

func (i *Importer) GetAllImportStatus(ctx context.Context) ([]*ImportStatus, error)

GetAllImportStatus returns import status for all imported sessions.

func (*Importer) GetChatMessages

func (i *Importer) GetChatMessages(ctx context.Context, sessionID string) ([]*ChatMessage, error)

GetChatMessages retrieves chat messages for a session from the database.

func (*Importer) GetChatMessagesByTimeRange

func (i *Importer) GetChatMessagesByTimeRange(ctx context.Context, sessionID string, start, end time.Time) ([]*ChatMessage, error)

GetChatMessagesByTimeRange retrieves chat messages within a time range. Useful for correlating spans to chat context.

func (*Importer) GetImportStatus

func (i *Importer) GetImportStatus(ctx context.Context, sessionID string) (*ImportStatus, error)

GetImportStatus returns the import status for a session.

func (*Importer) SyncAll

func (i *Importer) SyncAll(ctx context.Context) (*SyncStats, error)

SyncAll imports all new or modified JSONL files from ~/.claude/projects/.

func (*Importer) SyncSession

func (i *Importer) SyncSession(ctx context.Context, sessionID string) (int, error)

SyncSession imports a single session by ID. Returns the number of messages imported.

type JSONLEntry

type JSONLEntry struct {
	SessionID  string `json:"sessionId"`
	Type       string `json:"type"` // "user", "assistant"
	ParentUUID string `json:"parentUuid,omitempty"`
	Timestamp  string `json:"timestamp"`
	UUID       string `json:"uuid,omitempty"`
	Message    *struct {
		Model   string `json:"model,omitempty"`
		ID      string `json:"id,omitempty"` // msg_...
		Role    string `json:"role,omitempty"`
		Content []struct {
			Type     string      `json:"type"`
			Text     string      `json:"text,omitempty"`
			Thinking string      `json:"thinking,omitempty"`
			ID       string      `json:"id,omitempty"`   // For tool_use
			Name     string      `json:"name,omitempty"` // For tool_use
			Input    interface{} `json:"input,omitempty"`
			// For tool_result
			ToolUseID string `json:"tool_use_id,omitempty"`
			Content   string `json:"content,omitempty"`
			IsError   bool   `json:"is_error,omitempty"`
		} `json:"content,omitempty"`
		StopReason string `json:"stop_reason,omitempty"`
		Usage      *struct {
			InputTokens          int `json:"input_tokens"`
			OutputTokens         int `json:"output_tokens"`
			CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
			CacheCreationTokens  int `json:"cache_creation_input_tokens,omitempty"`
		} `json:"usage,omitempty"`
	} `json:"message,omitempty"`
	RequestID string `json:"requestId,omitempty"`
	GitBranch string `json:"gitBranch,omitempty"`
	Cwd       string `json:"cwd,omitempty"`
}

JSONLEntry represents a raw entry from the Claude Code JSONL file. This is the format stored on disk.

type Message

type Message struct {
	UUID       string         `json:"uuid"`
	ParentUUID string         `json:"parent_uuid,omitempty"`
	SessionID  string         `json:"session_id"`
	Type       string         `json:"type"` // "user" or "assistant"
	Timestamp  time.Time      `json:"timestamp"`
	Model      string         `json:"model,omitempty"`
	MessageID  string         `json:"message_id,omitempty"` // Anthropic message ID (msg_...)
	RequestID  string         `json:"request_id,omitempty"` // Anthropic request ID (req_...)
	Content    []ContentBlock `json:"content"`
	Usage      *TokenUsage    `json:"usage,omitempty"`
	GitBranch  string         `json:"git_branch,omitempty"`
	Cwd        string         `json:"cwd,omitempty"`
	StopReason string         `json:"stop_reason,omitempty"`
}

Message represents a single message in a conversation.

type Project

type Project struct {
	Path          string        `json:"path"`           // Escaped path
	Name          string        `json:"name"`           // Human-readable name
	Sessions      []SessionMeta `json:"sessions"`       // Session summaries
	TotalSessions int           `json:"total_sessions"` // Count of sessions
}

Project represents a Claude Code project directory.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Reader reads Claude Code conversation history from disk.

func NewReader

func NewReader() *Reader

NewReader creates a new Reader with the default base directory.

func NewReaderWithBase

func NewReaderWithBase(baseDir string) *Reader

NewReaderWithBase creates a Reader with a custom base directory.

func (*Reader) BaseDir

func (r *Reader) BaseDir() string

BaseDir returns the base directory for Claude Code projects.

func (*Reader) GetMessagesByTimeRange

func (r *Reader) GetMessagesByTimeRange(sessionID string, start, end time.Time) ([]Message, error)

GetMessagesByTimeRange returns messages within a time window. Useful for correlating spans to chat context.

func (*Reader) GetSession

func (r *Reader) GetSession(sessionID string) (*Session, error)

GetSession reads a complete session by ID. The sessionID can be a full session ID or a JSONL filename.

func (*Reader) GetSessionByPath

func (r *Reader) GetSessionByPath(filePath string) (*Session, error)

GetSessionByPath reads a session from a specific file path.

func (*Reader) ListProjects

func (r *Reader) ListProjects() ([]Project, error)

ListProjects returns all projects in the Claude Code projects directory.

func (*Reader) ListSessions

func (r *Reader) ListSessions(projectPath string) ([]SessionMeta, error)

ListSessions returns session metadata for a project.

type Session

type Session struct {
	ID          string    `json:"id"`
	ProjectPath string    `json:"project_path"` // Escaped path (e.g., "-Users-mark-dev-sunholo-ailang")
	ProjectName string    `json:"project_name"` // Human-readable name
	Messages    []Message `json:"messages"`
	StartTime   time.Time `json:"start_time"`
	EndTime     time.Time `json:"end_time"`
	TurnCount   int       `json:"turn_count"`
	TotalIn     int       `json:"total_in"`    // Total input tokens
	TotalOut    int       `json:"total_out"`   // Total output tokens
	CacheRead   int       `json:"cache_read"`  // Total cache read tokens
	CacheWrite  int       `json:"cache_write"` // Total cache creation tokens
	Model       string    `json:"model"`       // Primary model used
	GitBranch   string    `json:"git_branch"`  // Git branch if available
	Cwd         string    `json:"cwd"`         // Working directory
}

Session represents a Claude Code conversation session.

type SessionCorrelation

type SessionCorrelation struct {
	TaskID  sql.NullString
	ChainID sql.NullString
	StageID sql.NullString
}

SessionCorrelation holds task/chain/stage IDs from the sessions table.

type SessionMeta

type SessionMeta struct {
	ID        string    `json:"id"`
	StartTime time.Time `json:"start_time"`
	EndTime   time.Time `json:"end_time"`
	TurnCount int       `json:"turn_count"`
	TotalIn   int       `json:"total_in"`
	TotalOut  int       `json:"total_out"`
	Model     string    `json:"model"`
	FilePath  string    `json:"file_path"` // Full path to JSONL file
	FileSize  int64     `json:"file_size"` // Size in bytes
}

SessionMeta is a lightweight summary of a session (for listing).

type SyncStats

type SyncStats struct {
	ProjectsScanned  int
	SessionsScanned  int
	SessionsImported int
	SessionsSkipped  int
	MessagesImported int
	Errors           []string
}

SyncStats tracks import statistics.

type TokenUsage

type TokenUsage struct {
	InputTokens         int `json:"input_tokens"`
	OutputTokens        int `json:"output_tokens"`
	CacheReadTokens     int `json:"cache_read_input_tokens,omitempty"`
	CacheCreationTokens int `json:"cache_creation_input_tokens,omitempty"`
}

TokenUsage tracks token consumption for a message.

type ToolResultBlock

type ToolResultBlock struct {
	ToolUseID string `json:"tool_use_id"` // References ToolUseBlock.ID
	Content   string `json:"content"`     // Result content
	IsError   bool   `json:"is_error"`    // Whether the tool call failed
}

ToolResultBlock represents the result of a tool call.

type ToolUseBlock

type ToolUseBlock struct {
	ID    string      `json:"id"`    // Tool use ID (toolu_...)
	Name  string      `json:"name"`  // Tool name (e.g., "Read", "Write", "Bash")
	Input interface{} `json:"input"` // Tool input (varies by tool)
}

ToolUseBlock represents a tool call made by Claude.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL