session

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AbsPath added in v0.3.0

func AbsPath(p string) string

AbsPath returns filepath.Abs(p), falling back to p when Abs fails.

func AlignWorktree added in v0.3.0

func AlignWorktree(repoRoot, oldPath, worktreeDir string) (string, error)

AlignWorktree moves a worktree to repoRoot/worktreeDir/branchName. Returns the new path on success.

func CategoryLabel

func CategoryLabel(cat ConfigCategory) string

CategoryLabel returns a short label for the category.

func ConfigCategoryCount

func ConfigCategoryCount() int

ConfigCategoryCount returns the number of config categories.

func DeleteMemoryFiles added in v0.3.0

func DeleteMemoryFiles(projectPath string, fileNames []string) (int, error)

DeleteMemoryFiles removes memory files from a project's memory directory. Returns the number of files deleted.

func EncodeProjectPath

func EncodeProjectPath(path string) string

EncodeProjectPath converts an absolute path to the Claude projects directory name. Claude replaces both '/' and '.' with '-'.

func EntryPreview

func EntryPreview(e Entry) string

func EstimateCost

func EstimateCost(modelTokens map[string]*ModelUsage) float64

EstimateCost computes approximate USD cost from per-model token usage.

func ExtractFileReferences

func ExtractFileReferences(filePath string) []string

ExtractFileReferences parses a file for @path references and returns resolved absolute paths.

func ExtractImageToTemp

func ExtractImageToTemp(homeDir, sessionFilePath, sessionID string, pasteID int) (string, error)

ExtractImageToTemp extracts an image by paste ID from a session JSONL file, decodes the base64 data, writes it to the shared image cache as PNG (so the same path is stable across renders and so the Kitty f=100 PNG protocol accepts it), and returns the path. Falls back to a scratch temp file if the cache directory can't be created.

func ExtractMetadata

func ExtractMetadata(line string) (cwd, gitBranch string)

func ExtractScriptPath

func ExtractScriptPath(cmd string, home string) string

ExtractScriptPath extracts the script file path from a hook command string. Handles patterns like "python3 ~/.claude/hooks/foo.py", "uv run ~/.claude/hooks/bar.py".

func FilterValueFor added in v0.3.0

func FilterValueFor(s Session, cwdProjectPaths []string) string

FilterValueFor returns the space-separated, lowercased token string used for filtering a session. It includes the session's project path, name, branch, short ID, first prompt, and various `is:` / `has:` / `proj:` / `team:` / `win:` / `tag:` marker tokens.

If cwdProjectPaths is non-empty and includes s.ProjectPath (as absolute paths), the token "is:current" is added.

func ImageCachePath

func ImageCachePath(homeDir, sessionID string, pasteID int) string

ImageCachePath returns the cached image file path for an image block's paste ID. Returns empty string if the file doesn't exist.

func ImportMemoryFiles added in v0.3.0

func ImportMemoryFiles(srcPath, dstPath string, fileNames []string) (int, error)

ImportMemoryFiles copies selected memory files from src project to dst project. If a file already exists in dst, it is overwritten. Returns the number of files copied.

func ListProjects

func ListProjects(claudeDir string) []string

ListProjects returns all known project paths from ~/.claude/projects/. It decodes the encoded directory names back to real filesystem paths.

func LoadMessagesSummary

func LoadMessagesSummary(filePath string, headN, tailN int) (head []Entry, tail []Entry, total int, err error)

LoadMessagesSummary loads only the first headN and last tailN messages from a session file, returning them along with the total message count.

func Matches added in v0.3.0

func Matches(filterValue, query string) bool

Matches reports whether filterValue (as produced by FilterValueFor) matches query, using space-separated substring-AND semantics. Empty query matches.

func MoveProject

func MoveProject(oldPath, newPath string) error

MoveProject moves a session's project directory to a new path.

func ResolveBaseRepo added in v0.3.0

func ResolveBaseRepo(projectPath string, worktreeDirs ...string) string

ResolveBaseRepo returns the main repository root for a project path. For git worktrees, it reads the .git file to find the main repo's .git/worktrees/<name> pointer and resolves back to the repo root. For normal repos it returns the path unchanged. Falls back to path-based detection if git info isn't available.

func ResolveMainProjectPath added in v0.3.0

func ResolveMainProjectPath(worktreePath string, worktreeDirs ...string) string

ResolveMainProjectPath returns the main (non-worktree) project path for a worktree project path. It strips the worktree dir suffix (e.g. .worktree/{name}). Returns the path unchanged if the pattern is not found.

func SearchSessions

func SearchSessions(sessions []*Session, query SearchQuery, ctx context.Context) <-chan SearchResult

func ShortenPath

func ShortenPath(path, home string) string

func StripXMLTags

func StripXMLTags(s string) string

StripXMLTags removes XML-like tags such as <command-name>, </local-command-stdout>, etc.

func ToolSummary

func ToolSummary(e Entry) string

Types

type BadgeStore added in v0.2.0

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

BadgeStore manages custom user-created badges for sessions

func LoadBadges added in v0.2.0

func LoadBadges(home string) *BadgeStore

LoadBadges loads the badge mapping from ~/.claude/badges.json

func (*BadgeStore) AllBadges added in v0.2.0

func (bs *BadgeStore) AllBadges() []string

AllBadges returns a sorted list of all distinct badge names

func (*BadgeStore) CountBadgeUsage added in v0.2.0

func (bs *BadgeStore) CountBadgeUsage(badgeName string) int

CountBadgeUsage returns how many sessions use a given badge

func (*BadgeStore) Get added in v0.2.0

func (bs *BadgeStore) Get(sessionID string) []string

Get returns the badges for a given session ID

func (*BadgeStore) RemoveBadgeFromAll added in v0.2.0

func (bs *BadgeStore) RemoveBadgeFromAll(badgeName string) int

RemoveBadgeFromAll removes a badge from all sessions and returns count of affected sessions

func (*BadgeStore) Save added in v0.2.0

func (bs *BadgeStore) Save() error

Save persists the badge mapping to disk

func (*BadgeStore) Set added in v0.2.0

func (bs *BadgeStore) Set(sessionID string, badges []string)

Set updates the badges for a session

type ConfigCategory

type ConfigCategory int

ConfigCategory identifies which section a config item belongs to.

const (
	ConfigGlobal  ConfigCategory = iota // CLAUDE.md + memory + contexts + rules
	ConfigProject                       // project-level CLAUDE.md + memory
	ConfigLocal                         // local CLAUDE.md + settings.local.json
	ConfigSkill
	ConfigAgent
	ConfigCommand
	ConfigMCP
	ConfigHook
	ConfigEnterprise // managed enterprise settings
	ConfigKeymap     // keybindings from config.yaml
	ConfigShortcut   // number key shortcuts

)

type ConfigItem

type ConfigItem struct {
	Category    ConfigCategory
	Name        string
	Path        string
	Description string // first heading or frontmatter description
	ModTime     time.Time
	Size        int64
	RefBy       string // path of referencing file (empty for root)
	RefDepth    int    // 0 = root (CLAUDE.md), 1+ = referenced depth
	Group       string // sub-group within category (e.g. hook event type)
}

ConfigItem represents a single discoverable config file.

type ConfigTree

type ConfigTree struct {
	ProjectName string // short project name for header
	ProjectPath string // decoded project path for local lookup
	Items       []ConfigItem
}

ConfigTree holds all discovered config items grouped by category.

func ScanConfig

func ScanConfig(claudeDir, projectPath string) (*ConfigTree, error)

ScanConfig discovers all Claude Code configuration files across three scope levels (global, project, local) plus skills, agents, commands, and MCP configs.

type ContentBlock

type ContentBlock struct {
	Type         string
	Text         string
	ToolName     string
	ToolInput    string
	IsError      bool
	ID           string     // tool_use block ID (e.g., "toolu_01...")
	Hooks        []HookInfo // hooks that ran for this tool_use block
	TagName      string     // for system_tag blocks: the XML tag name (e.g., "system-reminder")
	ImagePasteID int        // for image blocks: the paste ID for cache lookup (0 = not set)
}

type CronItem added in v0.3.0

type CronItem struct {
	ID        string
	Cron      string
	Prompt    string
	Recurring bool
	Status    string // active, deleted
	CreatedAt time.Time
	DeletedAt time.Time
}

func LoadCronsFromEntries added in v0.3.0

func LoadCronsFromEntries(entries []Entry) []CronItem

type Entry

type Entry struct {
	Type      string
	Timestamp time.Time
	IsMeta    bool
	Role      string
	Content   []ContentBlock
	Model     string
	UUID      string
	ParentID  string
	AgentID   string
	RawJSON   string
}

func LoadMessages

func LoadMessages(filePath string) ([]Entry, error)

func ParseEntry

func ParseEntry(line string) (Entry, error)

type GlobalStats

type GlobalStats struct {
	SessionCount  int
	TotalMessages int
	TotalUserMsgs int
	TotalAsstMsgs int
	TotalDuration time.Duration
	AvgDuration   time.Duration

	TotalInputTokens         int64
	TotalOutputTokens        int64
	TotalCacheReadTokens     int64
	TotalCacheCreationTokens int64

	ToolCounts    map[string]int
	MCPToolCounts map[string]int
	SkillCounts   map[string]int
	CommandCounts map[string]int
	Models        map[string]int

	TotalWrites, TotalEdits, TotalFiles int
	TotalToolResults, TotalToolErrors   int
	TotalCompactions                    int
	SessionsWithCompaction              int

	TotalCostUSD float64
	ModelTokens  map[string]*ModelUsage

	TotalModelSwitches   int
	SessionsWithSwitches int

	ToolErrors    map[string]int
	SkillErrors   map[string]int
	CommandErrors map[string]int

	AgentCounts map[string]int // subagent_type -> total count across sessions

	AllTurnsPerRequest []int

	SessionDurations   []time.Duration
	SessionTokens      []int64
	SessionStarts      []time.Time
	AllErrorTimestamps []time.Time

	AllToolCallTimestamps  map[string][]time.Time
	AllToolErrorTimestamps map[string][]time.Time

	AllMsgTimestamps []time.Time

	HookCounts      map[string]int         // command -> total invocations
	HookEventCounts map[string]int         // event type -> count
	HookTimestamps  map[string][]time.Time // command -> timestamps

	ProjectStats []ProjectStats // per-project aggregated stats, sorted by cost desc
}

GlobalStats holds aggregated statistics across all sessions.

func AggregateStats

func AggregateStats(sessions []Session, worktreeDirs ...string) GlobalStats

AggregateStats scans all session files and aggregates their statistics.

type HookInfo

type HookInfo struct {
	Event   string // "PreToolUse", "PostToolUse", "Stop"
	Name    string // "PostToolUse:Read"
	Command string // "uv run ~/.claude/hooks/go_vet.py"

}

type MarketplaceInfo

type MarketplaceInfo struct {
	SourceType string // "git" or "github"
	SourceURL  string // URL or "owner/repo"
}

MarketplaceInfo from known_marketplaces.json.

type MemoryFile added in v0.3.0

type MemoryFile struct {
	Name     string // filename (e.g., "user_role.md")
	Path     string // full path
	Size     int64
	ExistsIn bool // true if a file with the same name exists in the target
}

MemoryFile represents a memory file from a project's memory directory.

func ListProjectMemory added in v0.3.0

func ListProjectMemory(projectPath string) ([]MemoryFile, error)

ListProjectMemory returns all .md files in a project's memory directory.

func ListProjectMemoryConflicts added in v0.3.0

func ListProjectMemoryConflicts(srcPath, dstPath string) ([]MemoryFile, error)

ListProjectMemoryConflicts lists memory files from src and marks which ones already exist in dst project.

type ModelUsage

type ModelUsage struct {
	InputTokens         int64
	OutputTokens        int64
	CacheReadTokens     int64
	CacheCreationTokens int64
}

ModelUsage tracks token counts per model for cost estimation.

type Plugin

type Plugin struct {
	ID          string // "plugin-name@marketplace"
	Name        string // just the plugin name part
	Marketplace string // just the marketplace part
	Installed   bool
	Enabled     bool // from settings.json enabledPlugins
	Install     PluginInstall
	Manifest    *PluginManifest
	Components  []PluginComponent
	SubPlugins  []SubPlugin
	Blocked     bool
	BlockReason string
}

Plugin is a fully resolved plugin for display.

type PluginComponent

type PluginComponent struct {
	Type string // "agent", "hook", "command", "mcp", "skill", "script", "setting", "memory", "lsp"
	Name string
	Path string
	Size int64
}

PluginComponent represents a discovered file within a plugin.

type PluginInstall

type PluginInstall struct {
	Scope        string
	InstallPath  string
	Version      string
	InstalledAt  time.Time
	LastUpdated  time.Time
	GitCommitSha string
}

PluginInstall represents one installation entry from installed_plugins.json.

type PluginManifest

type PluginManifest struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Version     string `json:"version"`
	Category    string `json:"category"`
	Strict      bool   `json:"strict"`
	Source      string `json:"source"`
	Author      struct {
		Name  string `json:"name"`
		Email string `json:"email"`
	} `json:"author"`
	LspServers map[string]json.RawMessage `json:"lspServers"`
}

PluginManifest represents .claude-plugin/plugin.json contents.

type PluginTree

type PluginTree struct {
	Plugins      []Plugin
	Marketplaces map[string]MarketplaceInfo
}

PluginTree holds all discovered plugins grouped by marketplace.

func ScanPlugins

func ScanPlugins(claudeDir string) (*PluginTree, error)

ScanPlugins discovers installed and available plugins from claudeDir/plugins/.

type ProjectStats added in v0.3.0

type ProjectStats struct {
	ProjectName              string
	ProjectPath              string
	RepoPath                 string
	SessionCount             int
	TotalInputTokens         int64
	TotalOutputTokens        int64
	TotalCacheReadTokens     int64
	TotalCacheCreationTokens int64
	CostUSD                  float64
	TotalMessages            int
	TotalDuration            time.Duration
}

ProjectStats holds aggregated stats for a single project.

type SearchQuery

type SearchQuery struct {
	Terms    []string // AND-matched terms (lowercased)
	Phrases  []string // Exact phrases (lowercased)
	Exclude  []string // Negated terms (lowercased)
	ToolName string   // Filter by tool name
	Role     string   // "user" or "assistant"
}

func ParseSearchQuery

func ParseSearchQuery(input string) SearchQuery

func (SearchQuery) IsEmpty

func (q SearchQuery) IsEmpty() bool

type SearchResult

type SearchResult struct {
	Session *Session
	Entry   *Entry
	Block   *ContentBlock
	Snippet string
}

type Session

type Session struct {
	ID           string
	ShortID      string
	FilePath     string
	ProjectPath  string
	ProjectName  string
	GitBranch    string
	ModTime      time.Time
	MsgCount     int
	FirstPrompt  string
	Created      time.Time
	IsWorktree   bool
	IsLive       bool
	IsResponding bool
	HasMemory    bool
	HasTodos     bool
	Todos        []TodoItem
	HasTasks     bool
	HasCrons     bool
	HasPlan      bool
	PlanSlug     string   // first plan slug (kept for compat)
	PlanSlugs    []string // all distinct plan slugs in order
	Tasks        []TaskItem
	Crons        []CronItem
	TeamName     string // e.g. "supports-build"
	TeamRole     string // "leader", "teammate", ""
	TeammateName string // e.g. "build-deploy" (teammate only)

	ParentSessionID string // UUID of parent session (empty if not a fork)

	HasAgents     bool
	HasCompaction bool
	HasSkills     bool
	HasMCP        bool

	CustomBadges []string // user-created badge tags

	TmuxWindowName string // tmux window name (set if pane CWD matches ProjectPath)

	// Remote execution
	IsRemote        bool   // virtual remote session
	RemotePodName   string // K8s pod name
	RemoteContext   string // kubectl context
	RemoteNamespace string // K8s namespace
	RemoteStatus    string // setup progress / running / stopped
}

func LoadCachedSessions

func LoadCachedSessions(claudeDir string) []Session

LoadCachedSessions loads all sessions from the cache file without any filesystem scanning. Returns nil if no cache exists. Used for instant first paint at startup.

func ScanSessions

func ScanSessions(claudeDir string) ([]Session, error)

ScanSessions scans for Claude Code sessions. If claudeDir is empty, defaults to ~/.claude. Uses a metadata cache to avoid re-scanning unchanged files.

func ScanSessionsForPaths

func ScanSessionsForPaths(claudeDir string, projectPaths []string) ([]Session, error)

ScanSessionsForPaths scans only the most recently modified session file in each project directory matching the given absolute project paths. This is designed for fast live-session detection at startup.

type SessionStats

type SessionStats struct {
	// Token usage
	TotalInputTokens         int64
	TotalOutputTokens        int64
	TotalCacheReadTokens     int64
	TotalCacheCreationTokens int64

	// Per-assistant-message output token counts (chronological, for sparkline)
	OutputTokenSeries []int

	// Tool usage: tool name -> call count
	ToolCounts map[string]int

	// Code activity
	WriteCount   int
	EditCount    int
	ReadCount    int
	BashCount    int
	FilesTouched map[string]bool

	// Errors
	ToolResultCount int
	ToolErrorCount  int
	ToolErrors      map[string]int // tool name -> error count
	SkillErrors     map[string]int // skill name -> error count
	CommandErrors   map[string]int // command name -> error count
	ErrorTimestamps []time.Time    // when errors occurred (for timeline)

	// Per-tool timestamps for timeline sparklines
	ToolCallTimestamps  map[string][]time.Time // tool name -> call timestamps
	ToolErrorTimestamps map[string][]time.Time // tool name -> error timestamps

	// MCP tools: name -> count (subset of ToolCounts for mcp__ prefixed tools)
	MCPToolCounts map[string]int

	// Commands: slash command name -> count (e.g. "/commit" -> 2)
	CommandCounts map[string]int

	// Skills: skill name -> count (from Skill tool_use)
	SkillCounts map[string]int

	// Agents: subagent_type -> count (from Agent tool_use)
	AgentCounts map[string]int

	// Timeline
	FirstTimestamp time.Time
	LastTimestamp  time.Time
	MessageCount   int
	UserMsgCount   int
	AsstMsgCount   int

	// Compaction
	CompactionCount int

	// Turns per user request
	TurnsPerRequest []int

	// Per-model token usage
	ModelTokens map[string]*ModelUsage

	// Model switching
	ModelSwitches int

	// Message timing
	AvgMsgGap time.Duration
	MaxMsgGap time.Duration

	// Per-message timestamps for timeline visualization
	MsgTimestamps []time.Time

	// Models used
	Models map[string]int

	// Hook usage: command -> count, event -> count
	HookCounts      map[string]int         // command path -> total invocations
	HookEventCounts map[string]int         // event type ("PreToolUse", "PostToolUse", "Stop") -> count
	HookTimestamps  map[string][]time.Time // command -> timestamps
}

SessionStats holds aggregated statistics extracted from a session JSONL file.

func ScanSessionStats

func ScanSessionStats(path string) (SessionStats, error)

ScanSessionStats scans a session JSONL file and computes aggregate statistics using byte-level pre-filtering for performance.

type SubPlugin

type SubPlugin struct {
	Name        string
	Description string
	Version     string
	Components  []PluginComponent
}

SubPlugin is a named sub-plugin defined in a marketplace manifest.

type Subagent

type Subagent struct {
	ID          string
	ShortID     string
	FilePath    string
	MsgCount    int
	FirstPrompt string
	Timestamp   time.Time
	AgentType   string
}

func FindSubagents

func FindSubagents(sessionFile string) ([]Subagent, error)

type TaskItem

type TaskItem struct {
	ID          string   `json:"id"`
	Subject     string   `json:"subject"`
	Status      string   `json:"status"`
	Description string   `json:"description"`
	ActiveForm  string   `json:"activeForm"`
	Blocks      []string `json:"blocks"`
	BlockedBy   []string `json:"blockedBy"`
}

func LoadTasksFromEntries added in v0.3.0

func LoadTasksFromEntries(entries []Entry) []TaskItem

LoadTasksFromEntries extracts the latest task states from parsed conversation entries. This is used as a fallback when task files have been cleaned up from disk.

type TodoItem

type TodoItem struct {
	Content string `json:"content"`
	Status  string `json:"status"` // pending, in_progress, completed
}

type WorktreeInfo added in v0.3.0

type WorktreeInfo struct {
	Path   string
	Branch string
	IsMain bool
}

WorktreeInfo from `git worktree list --porcelain`.

func ListWorktrees added in v0.3.0

func ListWorktrees(repoRoot string) ([]WorktreeInfo, error)

ListWorktrees parses `git worktree list --porcelain` output for the given repo root.

func MisalignedWorktrees added in v0.3.0

func MisalignedWorktrees(repoRoot string, worktrees []WorktreeInfo, worktreeDir string) []WorktreeInfo

MisalignedWorktrees returns worktrees whose paths are not under repoRoot/worktreeDir. The main worktree is always excluded.

func ParseWorktreePorcelain added in v0.3.0

func ParseWorktreePorcelain(output string) []WorktreeInfo

ParseWorktreePorcelain parses the porcelain output of `git worktree list --porcelain`. Blocks are separated by blank lines. The first block is the main worktree.

Jump to

Keyboard shortcuts

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