context

package
v0.0.0-...-0e19dcc Latest Latest
Warning

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

Go to latest
Published: May 10, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func EstimateTokens

func EstimateTokens(content string) int

EstimateTokens estimates the token count for a string. Uses a simple heuristic: ~4 characters per token on average.

func ExtractTermsPublic

func ExtractTermsPublic(query string) []string

ExtractTermsPublic is a public wrapper for extractTerms (for testing).

func FindTestFilePublic

func FindTestFilePublic(filePath string) string

FindTestFilePublic is a public wrapper for findTestFile (for testing).

func FindTestedFilePublic

func FindTestedFilePublic(testPath string) string

FindTestedFilePublic is a public wrapper for findTestedFile (for testing).

func IsTestFilePublic

func IsTestFilePublic(path string) bool

IsTestFilePublic is a public wrapper for isTestFile (for testing).

func IsTestForFilePublic

func IsTestForFilePublic(testFile, focusFile string) bool

IsTestForFilePublic is a public wrapper for isTestForFile (for testing).

Types

type BudgetConfig

type BudgetConfig struct {
	MaxTokens        int                        `json:"max_tokens"`      // Maximum total tokens
	ReservedTokens   int                        `json:"reserved_tokens"` // Reserved for system/response
	MinAvailable     int                        `json:"min_available"`   // Minimum tokens to keep available
	EvictionPolicy   string                     `json:"eviction_policy"` // "lru", "priority", "relevance"
	PriorityWeights  map[BudgetPriority]float64 `json:"priority_weights"`
	ContentTypeBonus map[ContentType]float64    `json:"content_type_bonus"`
}

BudgetConfig holds configuration for the budget manager.

func DefaultBudgetConfig

func DefaultBudgetConfig() *BudgetConfig

DefaultBudgetConfig returns default configuration.

type BudgetItem

type BudgetItem struct {
	ID             string         `json:"id"`
	Type           ContentType    `json:"type"`
	Priority       BudgetPriority `json:"priority"`
	Content        string         `json:"content"`
	TokenCount     int            `json:"token_count"`
	Source         string         `json:"source,omitempty"`          // File path or source identifier
	SymbolName     string         `json:"symbol_name,omitempty"`     // For symbol items
	RelevanceScore float64        `json:"relevance_score,omitempty"` // 0.0-1.0 relevance to current task
	AddedAt        time.Time      `json:"added_at"`
	LastAccessed   time.Time      `json:"last_accessed"`
	AccessCount    int            `json:"access_count"`
}

BudgetItem represents a single item in the context budget.

type BudgetManager

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

BudgetManager manages the token budget for context allocation.

func NewBudgetManager

func NewBudgetManager(config *BudgetConfig, logger *slog.Logger) *BudgetManager

NewBudgetManager creates a new budget manager.

func (*BudgetManager) AddItem

func (bm *BudgetManager) AddItem(ctx context.Context, item *BudgetItem) error

AddItem adds an item to the budget, evicting if necessary.

func (*BudgetManager) CanFit

func (bm *BudgetManager) CanFit(tokenCount int) bool

CanFit returns true if an item of the given size can fit.

func (*BudgetManager) Clear

func (bm *BudgetManager) Clear()

Clear removes all items from the budget.

func (*BudgetManager) GetAvailableTokens

func (bm *BudgetManager) GetAvailableTokens() int

GetAvailableTokens returns the number of available tokens.

func (*BudgetManager) GetContent

func (bm *BudgetManager) GetContent(ctx context.Context) string

GetContent returns all content that fits within the budget.

func (*BudgetManager) GetItem

func (bm *BudgetManager) GetItem(id string) *BudgetItem

GetItem retrieves an item and updates its access time.

func (*BudgetManager) GetStats

func (bm *BudgetManager) GetStats() BudgetStats

GetStats returns current budget statistics.

func (*BudgetManager) PrioritizeRelevance

func (bm *BudgetManager) PrioritizeRelevance(relevantIDs map[string]float64)

PrioritizeRelevance adjusts priorities based on relevance scores.

func (*BudgetManager) RemoveItem

func (bm *BudgetManager) RemoveItem(id string) bool

RemoveItem removes an item from the budget.

func (*BudgetManager) ResizeBudget

func (bm *BudgetManager) ResizeBudget(maxTokens int) error

ResizeBudget changes the maximum token budget.

func (*BudgetManager) ToMarkdown

func (bm *BudgetManager) ToMarkdown() string

ToMarkdown generates a markdown representation of the budget state.

type BudgetPriority

type BudgetPriority int

BudgetPriority represents the priority level of context content.

const (
	PriorityCritical BudgetPriority = iota // Must include (e.g., current file, error messages)
	PriorityHigh                           // Important context (e.g., related files, imports)
	PriorityMedium                         // Useful context (e.g., documentation, comments)
	PriorityLow                            // Optional context (e.g., test files, examples)
)

type BudgetStats

type BudgetStats struct {
	TotalTokens     int                    `json:"total_tokens"`
	MaxTokens       int                    `json:"max_tokens"`
	ReservedTokens  int                    `json:"reserved_tokens"`
	UsedTokens      int                    `json:"used_tokens"`
	AvailableTokens int                    `json:"available_tokens"`
	ItemCount       int                    `json:"item_count"`
	ByPriority      map[BudgetPriority]int `json:"by_priority"`
	ByType          map[ContentType]int    `json:"by_type"`
	Utilization     float64                `json:"utilization"` // 0.0-1.0
}

BudgetStats holds statistics about the context budget.

type ContentType

type ContentType string

ContentType represents the type of context content.

const (
	ContentTypeFile        ContentType = "file"
	ContentTypeSymbol      ContentType = "symbol"
	ContentTypeImport      ContentType = "import"
	ContentTypeDoc         ContentType = "doc"
	ContentTypeError       ContentType = "error"
	ContentTypeTest        ContentType = "test"
	ContentTypeHistory     ContentType = "history"
	ContentTypeSystem      ContentType = "system"
	ContentTypeInstruction ContentType = "instruction"
)

type Dependency

type Dependency struct {
	FromFile   string         `json:"from_file"`
	ToFile     string         `json:"to_file"`
	Kind       DependencyKind `json:"kind"`
	ImportPath string         `json:"import_path,omitempty"`
	Line       int            `json:"line,omitempty"`
	Strength   int            `json:"strength"` // 1-10, based on usage frequency
}

Dependency represents a single dependency relationship between files.

type DependencyAnalyzer

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

DependencyAnalyzer analyzes cross-file dependencies.

func NewDependencyAnalyzer

func NewDependencyAnalyzer(config *DependencyConfig, logger *slog.Logger) *DependencyAnalyzer

NewDependencyAnalyzer creates a new dependency analyzer.

func (*DependencyAnalyzer) Analyze

func (a *DependencyAnalyzer) Analyze(ctx context.Context, rootPath string) (*DependencyGraph, error)

Analyze performs dependency analysis on a repository.

type DependencyConfig

type DependencyConfig struct {
	IncludeTests     bool     // Include test file dependencies
	IncludeVendor    bool     // Include vendor dependencies
	IncludeGenerated bool     // Include generated file dependencies
	MaxDepth         int      // Maximum dependency chain depth to analyze
	ExcludePatterns  []string // Files to exclude from analysis
}

DependencyConfig holds configuration for dependency analysis.

func DefaultDependencyConfig

func DefaultDependencyConfig() *DependencyConfig

DefaultDependencyConfig returns default configuration.

type DependencyGraph

type DependencyGraph struct {
	RootPath     string       `json:"root_path"`
	Dependencies []Dependency `json:"dependencies"`

	// Stats
	TotalFiles int           `json:"total_files"`
	TotalDeps  int           `json:"total_deps"`
	Cycles     [][]string    `json:"cycles,omitempty"`
	Timestamp  time.Time     `json:"timestamp"`
	Duration   time.Duration `json:"duration"`
	// contains filtered or unexported fields
}

DependencyGraph represents the complete dependency graph of a repository.

func (*DependencyGraph) GetAllFiles

func (g *DependencyGraph) GetAllFiles() []string

GetAllFiles returns all files in the dependency graph.

func (*DependencyGraph) GetDependencies

func (g *DependencyGraph) GetDependencies(file string) []*Dependency

GetDependencies returns all dependencies from a file.

func (*DependencyGraph) GetDependents

func (g *DependencyGraph) GetDependents(file string) []*Dependency

GetDependents returns all files that depend on a file.

func (*DependencyGraph) GetRelatedFiles

func (g *DependencyGraph) GetRelatedFiles(file string, maxDepth int) []string

GetRelatedFiles returns all files related to a file (both dependencies and dependents).

func (*DependencyGraph) GetTopologicalOrder

func (g *DependencyGraph) GetTopologicalOrder() []string

GetTopologicalOrder returns files in topological order (dependencies first).

func (*DependencyGraph) HasCycles

func (g *DependencyGraph) HasCycles() bool

HasCycles returns true if the graph has circular dependencies.

func (*DependencyGraph) ToMarkdown

func (g *DependencyGraph) ToMarkdown() string

ToMarkdown generates a markdown representation of the dependency graph.

type DependencyKind

type DependencyKind string

DependencyKind represents the type of dependency relationship.

const (
	DependencyImport    DependencyKind = "import"    // Direct import
	DependencyEmbed     DependencyKind = "embed"     // Go embed directive
	DependencyGenerated DependencyKind = "generated" // Generated from another file
	DependencyTest      DependencyKind = "test"      // Test file dependency
)

type FileChange

type FileChange struct {
	Path       string    `json:"path"`
	OldHash    string    `json:"old_hash,omitempty"`
	NewHash    string    `json:"new_hash,omitempty"`
	ChangeType string    `json:"change_type"` // "added", "modified", "deleted"
	OldModTime time.Time `json:"old_mod_time,omitempty"`
	NewModTime time.Time `json:"new_mod_time,omitempty"`
	TokensDiff int       `json:"tokens_diff"` // Token difference
}

FileChange represents a change to a file.

type FileInfo

type FileInfo struct {
	Path         string
	Basename     string
	Ext          string
	Dir          string
	LastAccessed time.Time
	IsOpen       bool
	IsHidden     bool
}

FileInfo holds information about a file for matching.

type FileMap

type FileMap struct {
	Path     string   `json:"path"`
	Language string   `json:"language"`
	Package  string   `json:"package,omitempty"`
	Imports  []Import `json:"imports,omitempty"`
	Symbols  []Symbol `json:"symbols"`
}

FileMap represents the symbols in a single file.

type FilePrioritizer

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

FilePrioritizer intelligently prioritizes files for context inclusion.

func NewFilePrioritizer

func NewFilePrioritizer(
	config *FilePriorityConfig,
	depAnalyzer *DependencyAnalyzer,
	budgetMgr *BudgetManager,
	repoMapGen *RepoMapGenerator,
	logger *slog.Logger,
) *FilePrioritizer

NewFilePrioritizer creates a new file prioritizer.

func (*FilePrioritizer) GetConfig

func (fp *FilePrioritizer) GetConfig() *FilePriorityConfig

GetConfig returns the current configuration.

func (*FilePrioritizer) PrioritizeForFile

func (fp *FilePrioritizer) PrioritizeForFile(ctx context.Context, focusFile string, availableFiles []string) (*PrioritizationResult, error)

PrioritizeForFile returns prioritized files for a given focus file.

func (*FilePrioritizer) PrioritizeForQuery

func (fp *FilePrioritizer) PrioritizeForQuery(ctx context.Context, query string, availableFiles []string) (*PrioritizationResult, error)

PrioritizeForQuery returns prioritized files based on a search query.

func (*FilePrioritizer) UpdateConfig

func (fp *FilePrioritizer) UpdateConfig(config *FilePriorityConfig)

UpdateConfig updates the prioritizer configuration.

type FilePriority

type FilePriority struct {
	Path          string    `json:"path"`
	Score         float64   `json:"score"`
	TokenEstimate int       `json:"token_estimate"`
	Reason        string    `json:"reason"`
	Dependencies  []string  `json:"dependencies,omitempty"`
	Dependents    []string  `json:"dependents,omitempty"`
	IsTest        bool      `json:"is_test"`
	LastModified  time.Time `json:"last_modified"`
}

FilePriority represents a file with its priority score.

type FilePriorityConfig

type FilePriorityConfig struct {
	MaxFiles            int     `json:"max_files"`             // Maximum files to include
	MaxTokens           int     `json:"max_tokens"`            // Token budget
	FocusFileWeight     float64 `json:"focus_file_weight"`     // Weight for focus file
	DirectDepWeight     float64 `json:"direct_dep_weight"`     // Weight for direct dependencies
	TransitiveDepWeight float64 `json:"transitive_dep_weight"` // Weight for transitive dependencies
	TestFileWeight      float64 `json:"test_file_weight"`      // Weight for test files
	RecentChangeWeight  float64 `json:"recent_change_weight"`  // Weight for recently changed files
	SimilarityWeight    float64 `json:"similarity_weight"`     // Weight for content similarity
}

FilePriorityConfig holds configuration for file prioritization.

func DefaultFilePriorityConfig

func DefaultFilePriorityConfig() *FilePriorityConfig

DefaultFilePriorityConfig returns default configuration.

type FileSnapshot

type FileSnapshot struct {
	Path     string    `json:"path"`
	Hash     string    `json:"hash"`
	ModTime  time.Time `json:"mod_time"`
	Size     int64     `json:"size"`
	TokenEst int       `json:"token_est"`
}

FileSnapshot represents a snapshot of file state.

type FileSummary

type FileSummary struct {
	Path     string    `json:"path"`
	Name     string    `json:"name"`
	Ext      string    `json:"ext"`
	Size     int64     `json:"size"`
	ModTime  time.Time `json:"mod_time"`
	IsDir    bool      `json:"is_dir"`
	IsHidden bool      `json:"is_hidden"`
	TokenEst int       `json:"token_est"`
	Priority int       `json:"priority"` // Higher = more important
}

FileSummary represents a summary of a file.

type FolderContextConfig

type FolderContextConfig struct {
	MaxFiles           int           `json:"max_files"`           // Max files per folder
	MaxDepth           int           `json:"max_depth"`           // Max recursion depth
	MaxTotalSize       int64         `json:"max_total_size"`      // Max total size in bytes
	ExcludePatterns    []string      `json:"exclude_patterns"`    // Patterns to exclude
	IncludeHidden      bool          `json:"include_hidden"`      // Include hidden files
	PriorityExtensions []string      `json:"priority_extensions"` // Extensions to prioritize
	SummaryMode        string        `json:"summary_mode"`        // "full", "structure", "stats"
	CacheTTL           time.Duration `json:"cache_ttl"`           // Cache time-to-live
}

FolderContextConfig holds configuration for folder context.

func DefaultFolderContextConfig

func DefaultFolderContextConfig() *FolderContextConfig

DefaultFolderContextConfig returns default configuration.

type FolderContextManager

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

FolderContextManager manages folder-level context gathering.

func NewFolderContextManager

func NewFolderContextManager(config *FolderContextConfig, logger *slog.Logger) *FolderContextManager

NewFolderContextManager creates a new folder context manager.

func (*FolderContextManager) ClearCache

func (fcm *FolderContextManager) ClearCache()

ClearCache clears the folder cache.

func (*FolderContextManager) GatherFolder

func (fcm *FolderContextManager) GatherFolder(ctx context.Context, folderPath string, depth int) (*FolderContextResult, error)

GatherFolder gathers context for a folder.

func (*FolderContextManager) GatherMultipleFolders

func (fcm *FolderContextManager) GatherMultipleFolders(ctx context.Context, folderPaths []string, depth int) ([]*FolderContextResult, error)

GatherMultipleFolders gathers context for multiple folders.

func (*FolderContextManager) GetFolderStructure

func (fcm *FolderContextManager) GetFolderStructure(ctx context.Context, folderPath string, maxDepth int) (string, error)

GetFolderStructure returns a tree structure of the folder.

func (*FolderContextManager) GetStats

func (fcm *FolderContextManager) GetStats() map[string]interface{}

GetStats returns statistics about the manager.

func (*FolderContextManager) ResolveFolderPath

func (fcm *FolderContextManager) ResolveFolderPath(mention string) (string, bool)

ResolveFolderPath resolves a folder path from a mention.

func (*FolderContextManager) UpdateConfig

func (fcm *FolderContextManager) UpdateConfig(config *FolderContextConfig)

UpdateConfig updates the manager configuration.

type FolderContextResult

type FolderContextResult struct {
	Folder     *FolderInfo   `json:"folder"`
	Depth      int           `json:"depth"`
	TotalFiles int           `json:"total_files"`
	TotalSize  int64         `json:"total_size"`
	GatherTime time.Duration `json:"gather_time"`
	Truncated  bool          `json:"truncated"` // True if limits were hit
}

FolderContextResult represents the result of folder context gathering.

func (*FolderContextResult) ToMarkdown

func (r *FolderContextResult) ToMarkdown() string

ToMarkdown generates a markdown representation of the folder context result.

type FolderInfo

type FolderInfo struct {
	Path       string            `json:"path"`
	Name       string            `json:"name"`
	FileCount  int               `json:"file_count"`
	DirCount   int               `json:"dir_count"`
	TotalSize  int64             `json:"total_size"`
	Files      []*FileSummary    `json:"files,omitempty"`
	Subdirs    []string          `json:"subdirs,omitempty"`
	Extensions map[string]int    `json:"extensions"`
	ModTime    time.Time         `json:"mod_time"`
	HasReadme  bool              `json:"has_readme"`
	ReadmePath string            `json:"readme_path,omitempty"`
	Metadata   map[string]string `json:"metadata,omitempty"`
}

FolderInfo represents information about a folder.

type GitBlameInfo

type GitBlameInfo struct {
	Path       string          `json:"path"`
	Lines      []*GitBlameLine `json:"lines"`
	Authors    map[string]int  `json:"authors"` // Author -> line count
	Commits    map[string]int  `json:"commits"` // Commit -> line count
	TotalLines int             `json:"total_lines"`
}

GitBlameInfo represents blame information for a file.

type GitBlameLine

type GitBlameLine struct {
	LineNumber int       `json:"line_number"`
	Commit     string    `json:"commit"`
	Author     string    `json:"author"`
	Date       time.Time `json:"date"`
	Content    string    `json:"content"`
}

GitBlameLine represents a single line from git blame.

type GitBranchInfo

type GitBranchInfo struct {
	Name       string         `json:"name"`
	IsCurrent  bool           `json:"is_current"`
	IsRemote   bool           `json:"is_remote"`
	Upstream   string         `json:"upstream,omitempty"`
	Ahead      int            `json:"ahead"`
	Behind     int            `json:"behind"`
	LastCommit *GitCommitInfo `json:"last_commit,omitempty"`
}

GitBranchInfo represents information about a git branch.

type GitCommitInfo

type GitCommitInfo struct {
	Hash        string    `json:"hash"`
	ShortHash   string    `json:"short_hash"`
	Author      string    `json:"author"`
	AuthorEmail string    `json:"author_email"`
	Date        time.Time `json:"date"`
	Subject     string    `json:"subject"`
	Body        string    `json:"body,omitempty"`
	Parents     []string  `json:"parents,omitempty"`
}

GitCommitInfo represents information about a git commit.

type GitContextConfig

type GitContextConfig struct {
	MaxDiffSize   int64         `json:"max_diff_size"`   // Max diff size in bytes
	MaxCommits    int           `json:"max_commits"`     // Max commits in log
	MaxBlameLines int           `json:"max_blame_lines"` // Max lines in blame
	IncludeDiff   bool          `json:"include_diff"`    // Include full diff content
	IncludeBody   bool          `json:"include_body"`    // Include commit body
	ContextLines  int           `json:"context_lines"`   // Context lines in diff
	CacheTTL      time.Duration `json:"cache_ttl"`       // Cache TTL
}

GitContextConfig holds configuration for git context retrieval.

func DefaultGitContextConfig

func DefaultGitContextConfig() *GitContextConfig

DefaultGitContextConfig returns default configuration.

type GitContextManager

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

GitContextManager provides git-related context capabilities.

func NewGitContextManager

func NewGitContextManager(config *GitContextConfig, repoPath string, logger *slog.Logger) *GitContextManager

NewGitContextManager creates a new git context manager.

func (*GitContextManager) ClearCache

func (g *GitContextManager) ClearCache()

ClearCache clears all caches.

func (*GitContextManager) GetBlame

func (g *GitContextManager) GetBlame(ctx context.Context, filePath string) (*GitContextResult, error)

GetBlame returns blame info for a file.

func (*GitContextManager) GetBranch

func (g *GitContextManager) GetBranch(ctx context.Context, branchName string) (*GitContextResult, error)

GetBranch returns current branch info.

func (*GitContextManager) GetCommit

func (g *GitContextManager) GetCommit(ctx context.Context, ref string) (*GitContextResult, error)

GetCommit returns context for a specific commit.

func (*GitContextManager) GetConflictFiles

func (g *GitContextManager) GetConflictFiles(ctx context.Context) ([]string, error)

GetConflictFiles returns files with merge conflicts.

func (*GitContextManager) GetDiff

func (g *GitContextManager) GetDiff(ctx context.Context, paths ...string) (*GitContextResult, error)

GetDiff returns the unstaged diff context.

func (*GitContextManager) GetLog

func (g *GitContextManager) GetLog(ctx context.Context, limit int) (*GitContextResult, error)

GetLog returns recent commit log.

func (*GitContextManager) GetStaged

func (g *GitContextManager) GetStaged(ctx context.Context) (*GitContextResult, error)

GetStaged returns the staged diff context.

func (*GitContextManager) GetStats

func (g *GitContextManager) GetStats() map[string]interface{}

GetStats returns cache statistics.

func (*GitContextManager) GetStatus

func (g *GitContextManager) GetStatus(ctx context.Context) (*GitContextResult, error)

GetStatus returns the working tree status.

func (*GitContextManager) UpdateConfig

func (g *GitContextManager) UpdateConfig(config *GitContextConfig)

UpdateConfig updates the configuration.

type GitContextResult

type GitContextResult struct {
	Type      GitContextType `json:"type"`
	QueryTime time.Duration  `json:"query_time"`

	// One of these will be populated based on type
	Commit   *GitCommitInfo   `json:"commit,omitempty"`
	Diff     *GitDiffInfo     `json:"diff,omitempty"`
	Branch   *GitBranchInfo   `json:"branch,omitempty"`
	Branches []*GitBranchInfo `json:"branches,omitempty"`
	Log      []*GitCommitInfo `json:"log,omitempty"`
	Blame    *GitBlameInfo    `json:"blame,omitempty"`
	Status   *GitStatusInfo   `json:"status,omitempty"`

	// Markdown representation
	Markdown string `json:"markdown,omitempty"`
	TokenEst int    `json:"token_est"`
}

GitContextResult contains the result of a git context query.

type GitContextType

type GitContextType string

GitContextType defines the type of git context to retrieve.

const (
	GitContextDiff     GitContextType = "diff"     // Unstaged changes
	GitContextStaged   GitContextType = "staged"   // Staged changes
	GitContextCommit   GitContextType = "commit"   // Specific commit
	GitContextBranch   GitContextType = "branch"   // Branch info
	GitContextLog      GitContextType = "log"      // Recent commits
	GitContextBlame    GitContextType = "blame"    // Blame for file
	GitContextStatus   GitContextType = "status"   // Working tree status
	GitContextConflict GitContextType = "conflict" // Merge conflicts
)

type GitDiffFile

type GitDiffFile struct {
	Path        string `json:"path"`
	OldPath     string `json:"old_path,omitempty"` // For renames
	Status      string `json:"status"`             // A(dded), M(odified), D(eleted), R(enamed)
	Additions   int    `json:"additions"`
	Deletions   int    `json:"deletions"`
	DiffContent string `json:"diff_content,omitempty"`
}

GitDiffFile represents a single file in a diff.

type GitDiffInfo

type GitDiffInfo struct {
	FromRef     string         `json:"from_ref,omitempty"`
	ToRef       string         `json:"to_ref,omitempty"`
	Files       []*GitDiffFile `json:"files"`
	TotalAdd    int            `json:"total_add"`
	TotalDel    int            `json:"total_del"`
	DiffContent string         `json:"diff_content,omitempty"`
	TokenEst    int            `json:"token_est"`
	Authors     map[string]int `json:"authors,omitempty"`
	Commits     map[string]int `json:"commits,omitempty"`
}

GitDiffInfo represents a diff between commits or working tree.

type GitStatusInfo

type GitStatusInfo struct {
	Staged    []*GitDiffFile `json:"staged"`
	Unstaged  []*GitDiffFile `json:"unstaged"`
	Untracked []string       `json:"untracked"`
	Conflicts []string       `json:"conflicts"`
	IsClean   bool           `json:"is_clean"`
	Branch    string         `json:"branch"`
}

GitStatusInfo represents the working tree status.

type Import

type Import struct {
	Path  string `json:"path"`
	Alias string `json:"alias,omitempty"`
	Line  int    `json:"line"`
}

Import represents an import statement.

type IncrementalRefreshConfig

type IncrementalRefreshConfig struct {
	HashAlgorithm   string           `json:"hash_algorithm"`   // "sha256", "modtime", "size"
	MaxCacheAge     time.Duration    `json:"max_cache_age"`    // Max age before full refresh
	IncludeHidden   bool             `json:"include_hidden"`   // Include hidden files
	FollowSymlinks  bool             `json:"follow_symlinks"`  // Follow symbolic links
	MaxFileSize     int64            `json:"max_file_size"`    // Max file size in bytes
	ExcludePatterns []string         `json:"exclude_patterns"` // Files to exclude
	TokenEstimator  func(string) int `json:"-"`                // Token estimation function
}

IncrementalRefreshConfig holds configuration for incremental refresh.

func DefaultIncrementalRefreshConfig

func DefaultIncrementalRefreshConfig() *IncrementalRefreshConfig

DefaultIncrementalRefreshConfig returns default configuration.

type IncrementalRefresher

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

IncrementalRefresher manages incremental context refreshes.

func NewIncrementalRefresher

func NewIncrementalRefresher(config *IncrementalRefreshConfig, logger *slog.Logger, cacheDir string) *IncrementalRefresher

NewIncrementalRefresher creates a new incremental refresher.

func (*IncrementalRefresher) ClearSnapshots

func (ir *IncrementalRefresher) ClearSnapshots()

ClearSnapshots clears all cached snapshots.

func (*IncrementalRefresher) ForceFullRefresh

func (ir *IncrementalRefresher) ForceFullRefresh()

ForceFullRefresh forces a full refresh on the next Refresh call.

func (*IncrementalRefresher) GetAllSnapshots

func (ir *IncrementalRefresher) GetAllSnapshots() map[string]*FileSnapshot

GetAllSnapshots returns all current snapshots.

func (*IncrementalRefresher) GetChangedFiles

func (ir *IncrementalRefresher) GetChangedFiles(files []string) ([]string, error)

GetChangedFiles returns a list of files that would change.

func (*IncrementalRefresher) GetConfig

GetConfig returns the current configuration.

func (*IncrementalRefresher) GetSnapshot

func (ir *IncrementalRefresher) GetSnapshot(file string) *FileSnapshot

GetSnapshot returns the current snapshot for a file.

func (*IncrementalRefresher) Refresh

func (ir *IncrementalRefresher) Refresh(ctx context.Context, files []string) (*RefreshResult, error)

Refresh performs an incremental refresh of the given files.

func (*IncrementalRefresher) UpdateConfig

func (ir *IncrementalRefresher) UpdateConfig(config *IncrementalRefreshConfig)

UpdateConfig updates the refresher configuration.

type MentionConfig

type MentionConfig struct {
	MaxResults      int           `json:"max_results"`       // Max results per query
	MinScore        float64       `json:"min_score"`         // Minimum fuzzy match score (0-1)
	FuzzyThreshold  float64       `json:"fuzzy_threshold"`   // Threshold for fuzzy matching
	IncludeHidden   bool          `json:"include_hidden"`    // Include hidden files
	CacheTTL        time.Duration `json:"cache_ttl"`         // Cache time-to-live
	PreferRecent    bool          `json:"prefer_recent"`     // Prefer recently accessed files
	PreferOpenFiles bool          `json:"prefer_open_files"` // Prefer currently open files
}

MentionConfig holds configuration for mention matching.

func DefaultMentionConfig

func DefaultMentionConfig() *MentionConfig

DefaultMentionConfig returns default configuration.

type MentionMatch

type MentionMatch struct {
	Path          string    `json:"path"`
	Name          string    `json:"name"`
	Type          string    `json:"type"` // "file", "folder", "symbol"
	Score         float64   `json:"score"`
	MatchType     string    `json:"match_type"`               // "exact", "prefix", "fuzzy", "basename"
	MatchedRanges []int     `json:"matched_ranges,omitempty"` // [start, end] pairs
	LastAccessed  time.Time `json:"last_accessed,omitempty"`
	IsOpen        bool      `json:"is_open,omitempty"`
}

MentionMatch represents a matched mention.

type MentionMatcher

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

MentionMatcher handles fuzzy matching for @ mentions.

func NewMentionMatcher

func NewMentionMatcher(config *MentionConfig, logger *slog.Logger) *MentionMatcher

NewMentionMatcher creates a new mention matcher.

func (*MentionMatcher) ClearCache

func (mm *MentionMatcher) ClearCache()

ClearCache clears the query cache.

func (*MentionMatcher) GetStats

func (mm *MentionMatcher) GetStats() map[string]interface{}

GetStats returns statistics about the matcher.

func (*MentionMatcher) GetSuggestions

func (mm *MentionMatcher) GetSuggestions(prefix string, limit int) []string

GetSuggestions returns quick suggestions for a prefix.

func (*MentionMatcher) IndexFiles

func (mm *MentionMatcher) IndexFiles(files []string)

IndexFiles indexes files for matching.

func (*MentionMatcher) Match

func (mm *MentionMatcher) Match(ctx context.Context, query string) (*MentionResult, error)

Match finds files matching the query.

func (*MentionMatcher) MatchByType

func (mm *MentionMatcher) MatchByType(ctx context.Context, query string, mentionType string) (*MentionResult, error)

MatchByType finds matches filtered by type.

func (*MentionMatcher) ResolveMention

func (mm *MentionMatcher) ResolveMention(mention string) (string, bool)

ResolveMention resolves a mention string to a file path.

func (*MentionMatcher) SetOpenFiles

func (mm *MentionMatcher) SetOpenFiles(files []string)

SetOpenFiles sets the currently open files.

func (*MentionMatcher) SetRecentFiles

func (mm *MentionMatcher) SetRecentFiles(files []string)

SetRecentFiles sets the recently accessed files.

func (*MentionMatcher) UpdateConfig

func (mm *MentionMatcher) UpdateConfig(config *MentionConfig)

UpdateConfig updates the matcher configuration.

type MentionResult

type MentionResult struct {
	Query    string          `json:"query"`
	Matches  []*MentionMatch `json:"matches"`
	Total    int             `json:"total"`
	Duration time.Duration   `json:"duration"`
}

MentionResult contains the result of a mention query.

func (*MentionResult) ToMarkdown

func (r *MentionResult) ToMarkdown() string

ToMarkdown generates a markdown representation of the mention result.

type PackageMap

type PackageMap struct {
	Name      string              `json:"name"`
	Path      string              `json:"path"`
	Files     map[string]*FileMap `json:"files"`
	Exports   []Symbol            `json:"exports"` // Package-level exports
	Timestamp time.Time           `json:"timestamp"`
}

PackageMap represents the symbols in a package/directory.

type PrioritizationResult

type PrioritizationResult struct {
	Files              []*FilePriority `json:"files"`
	TotalTokens        int             `json:"total_tokens"`
	FilesIncluded      int             `json:"files_included"`
	FilesSkipped       int             `json:"files_skipped"`
	FocusFile          string          `json:"focus_file"`
	PrioritizationTime time.Duration   `json:"prioritization_time"`
}

PrioritizationResult contains the result of file prioritization.

func (*PrioritizationResult) ToMarkdown

func (r *PrioritizationResult) ToMarkdown() string

ToMarkdown generates a markdown representation of prioritization result.

type RefreshResult

type RefreshResult struct {
	Changes          []*FileChange `json:"changes"`
	FilesAdded       int           `json:"files_added"`
	FilesModified    int           `json:"files_modified"`
	FilesDeleted     int           `json:"files_deleted"`
	FilesUnchanged   int           `json:"files_unchanged"`
	TotalTokenDiff   int           `json:"total_token_diff"`
	RefreshTime      time.Duration `json:"refresh_time"`
	FullRefresh      bool          `json:"full_refresh"`
	PreviousSnapshot string        `json:"previous_snapshot"`
	NewSnapshot      string        `json:"new_snapshot"`
}

RefreshResult contains the result of an incremental refresh.

func (*RefreshResult) ToMarkdown

func (r *RefreshResult) ToMarkdown() string

ToMarkdown generates a markdown representation of the refresh result.

type RelatedFile

type RelatedFile struct {
	Path          string              `json:"path"`
	Score         float64             `json:"score"`
	Reasons       []RelatedFileReason `json:"reasons"`
	ReasonDetails []string            `json:"reason_details,omitempty"`
	TokenEstimate int                 `json:"token_estimate"`
	IsTest        bool                `json:"is_test"`
	Distance      int                 `json:"distance"` // Dependency distance (1=direct, 2=transitive)
}

RelatedFile represents a file related to a focus file.

type RelatedFileReason

type RelatedFileReason string

RelatedFileReason describes why a file is related.

const (
	RelatedReasonDirectImport RelatedFileReason = "direct_import"
	RelatedReasonTransitive   RelatedFileReason = "transitive_dependency"
	RelatedReasonReverseDep   RelatedFileReason = "reverse_dependency"
	RelatedReasonSamePackage  RelatedFileReason = "same_package"
	RelatedReasonTestForFile  RelatedFileReason = "test_for_file"
	RelatedReasonTestedbyFile RelatedFileReason = "tested_by_file"
	RelatedReasonSharedImport RelatedFileReason = "shared_import"
	RelatedReasonSimilarName  RelatedFileReason = "similar_name"
)

type RelatedFilesConfig

type RelatedFilesConfig struct {
	MaxResults      int     `json:"max_results"`
	MaxDepth        int     `json:"max_depth"`
	MinScore        float64 `json:"min_score"`
	IncludeTests    bool    `json:"include_tests"`
	IncludeExternal bool    `json:"include_external"`
	ScoreThreshold  float64 `json:"score_threshold"`
}

RelatedFilesConfig holds configuration for related file suggestions.

func DefaultRelatedFilesConfig

func DefaultRelatedFilesConfig() *RelatedFilesConfig

DefaultRelatedFilesConfig returns default configuration.

type RelatedFilesResult

type RelatedFilesResult struct {
	FocusFile    string         `json:"focus_file"`
	RelatedFiles []*RelatedFile `json:"related_files"`
	TotalFound   int            `json:"total_found"`
	QueryTime    time.Duration  `json:"query_time"`
	MaxDepth     int            `json:"max_depth"`
}

RelatedFilesResult contains the result of a related files query.

func (*RelatedFilesResult) ToMarkdown

func (r *RelatedFilesResult) ToMarkdown() string

ToMarkdown generates a markdown representation of the result.

type RelatedFilesSuggester

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

RelatedFilesSuggester suggests related files based on dependency analysis.

func NewRelatedFilesSuggester

func NewRelatedFilesSuggester(
	config *RelatedFilesConfig,
	depAnalyzer *DependencyAnalyzer,
	logger *slog.Logger,
) *RelatedFilesSuggester

NewRelatedFilesSuggester creates a new related files suggester.

func (*RelatedFilesSuggester) ClearCache

func (rfs *RelatedFilesSuggester) ClearCache()

ClearCache clears the suggestion cache.

func (*RelatedFilesSuggester) GetConfig

func (rfs *RelatedFilesSuggester) GetConfig() *RelatedFilesConfig

GetConfig returns the current configuration.

func (*RelatedFilesSuggester) SuggestRelatedFiles

func (rfs *RelatedFilesSuggester) SuggestRelatedFiles(ctx context.Context, focusFile string) (*RelatedFilesResult, error)

SuggestRelatedFiles returns files related to the given focus file.

func (*RelatedFilesSuggester) UpdateConfig

func (rfs *RelatedFilesSuggester) UpdateConfig(config *RelatedFilesConfig)

UpdateConfig updates the suggester configuration.

type RepoMap

type RepoMap struct {
	RootPath     string                 `json:"root_path"`
	Packages     map[string]*PackageMap `json:"packages"`
	TotalFiles   int                    `json:"total_files"`
	TotalSymbols int                    `json:"total_symbols"`
	Timestamp    time.Time              `json:"timestamp"`
	Duration     time.Duration          `json:"duration"`
	// contains filtered or unexported fields
}

RepoMap represents the complete map of a repository.

func (*RepoMap) GetFile

func (rm *RepoMap) GetFile(path string) *FileMap

GetFile returns a file map by path.

func (*RepoMap) GetPackage

func (rm *RepoMap) GetPackage(path string) *PackageMap

GetPackage returns a package by path.

func (*RepoMap) LookupSymbol

func (rm *RepoMap) LookupSymbol(name string) []*Symbol

LookupSymbol finds symbols by name.

func (*RepoMap) ToCompactString

func (rm *RepoMap) ToCompactString() string

ToCompactString generates a compact string representation (Aider-style).

func (*RepoMap) ToMarkdown

func (rm *RepoMap) ToMarkdown() string

ToMarkdown generates a markdown representation of the repo map.

type RepoMapConfig

type RepoMapConfig struct {
	// Enabled languages
	GoEnabled         bool
	TypeScriptEnabled bool
	PythonEnabled     bool
	RustEnabled       bool

	// Extraction options
	IncludePrivate  bool     // Include private functions/methods
	IncludeImports  bool     // Include import statements
	IncludeComments bool     // Include doc comments
	MaxFileSize     int64    // Max file size to process (bytes)
	MaxFiles        int      // Max files to process
	ExcludePatterns []string // Glob patterns to exclude

	// Output options
	CompactMode     bool // Use compact output format
	MaxSignatureLen int  // Max signature length (truncate if longer)
	IncludeLineNums bool // Include line numbers in output
}

RepoMapConfig holds configuration for the repo map generator.

func DefaultRepoMapConfig

func DefaultRepoMapConfig() RepoMapConfig

DefaultRepoMapConfig returns the default configuration.

type RepoMapGenerator

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

RepoMapGenerator generates repository maps using AST parsing.

func NewRepoMapGenerator

func NewRepoMapGenerator(config RepoMapConfig, logger *slog.Logger) *RepoMapGenerator

NewRepoMapGenerator creates a new repo map generator.

func (*RepoMapGenerator) Generate

func (g *RepoMapGenerator) Generate(ctx context.Context, rootPath string) (*RepoMap, error)

Generate generates a complete repository map.

type Symbol

type Symbol struct {
	Name       string           `json:"name"`
	Kind       SymbolKind       `json:"kind"`
	Visibility SymbolVisibility `json:"visibility"`
	Signature  string           `json:"signature"`
	DocComment string           `json:"doc_comment,omitempty"`
	File       string           `json:"file"`
	Line       int              `json:"line"`
	EndLine    int              `json:"end_line,omitempty"`
	Receiver   string           `json:"receiver,omitempty"` // For methods
	Parent     string           `json:"parent,omitempty"`   // Parent type for nested symbols
	Children   []Symbol         `json:"children,omitempty"` // Nested symbols
	Exported   bool             `json:"exported"`
}

Symbol represents a code symbol (function, type, etc.).

type SymbolKind

type SymbolKind string

SymbolKind represents the kind of a code symbol.

const (
	SymbolFunction  SymbolKind = "function"
	SymbolMethod    SymbolKind = "method"
	SymbolStruct    SymbolKind = "struct"
	SymbolInterface SymbolKind = "interface"
	SymbolType      SymbolKind = "type"
	SymbolConst     SymbolKind = "const"
	SymbolVar       SymbolKind = "var"
	SymbolField     SymbolKind = "field"
	SymbolImport    SymbolKind = "import"
)

type SymbolVisibility

type SymbolVisibility string

SymbolVisibility represents the visibility of a symbol.

const (
	VisibilityPublic    SymbolVisibility = "public"
	VisibilityPrivate   SymbolVisibility = "private"
	VisibilityProtected SymbolVisibility = "protected"
	VisibilityInternal  SymbolVisibility = "internal"
)

type TestCoverageConfig

type TestCoverageConfig struct {
	TestFileSuffix    string        `json:"test_file_suffix"`   // e.g., "_test.go", ".test.ts"
	IncludeCoverage   bool          `json:"include_coverage"`   // Include coverage metrics
	MaxTestFiles      int           `json:"max_test_files"`     // Max test files to include
	MaxTestSize       int           `json:"max_test_size"`      // Max size per test file in bytes
	PrioritizeRelated bool          `json:"prioritize_related"` // Prioritize tests for source files
	TestRunTimeout    time.Duration `json:"test_run_timeout"`   // Timeout for test runs
}

TestCoverageConfig holds configuration for test coverage context.

func DefaultTestCoverageConfig

func DefaultTestCoverageConfig() *TestCoverageConfig

DefaultTestCoverageConfig returns default configuration.

type TestCoverageManager

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

TestCoverageManager manages test coverage context.

func NewTestCoverageManager

func NewTestCoverageManager(config *TestCoverageConfig, logger *slog.Logger) *TestCoverageManager

NewTestCoverageManager creates a new test coverage manager.

func (*TestCoverageManager) ClearCache

func (tcm *TestCoverageManager) ClearCache()

ClearCache clears the test and coverage cache.

func (*TestCoverageManager) FindTestForSource

func (tcm *TestCoverageManager) FindTestForSource(sourceFile string) (*TestCoverageResult, error)

FindTestForSource finds test files for a source file.

func (*TestCoverageManager) GetSourceFromTest

func (tcm *TestCoverageManager) GetSourceFromTest(testFile string) string

GetSourceFromTest returns the source file for a test file.

func (*TestCoverageManager) GetTestContext

func (tcm *TestCoverageManager) GetTestContext(ctx context.Context, sourceFiles []string) ([]*TestCoverageResult, error)

GetTestContext returns test context for multiple source files.

func (*TestCoverageManager) GetTestStats

func (tcm *TestCoverageManager) GetTestStats() map[string]interface{}

GetTestStats returns statistics about cached tests.

func (*TestCoverageManager) ShouldIncludeTest

func (tcm *TestCoverageManager) ShouldIncludeTest(testFile string, sourceFiles []string) bool

ShouldIncludeTest determines if a test file should be included in context.

func (*TestCoverageManager) UpdateCoverage

func (tcm *TestCoverageManager) UpdateCoverage(sourceFile string, coverage float64)

UpdateCoverage updates the coverage cache for a source file.

type TestCoverageResult

type TestCoverageResult struct {
	SourceFile      string          `json:"source_file"`
	TestFiles       []*TestFileInfo `json:"test_files"`
	TotalTests      int             `json:"total_tests"`
	TotalBenchmarks int             `json:"total_benchmarks"`
	CoveragePct     float64         `json:"coverage_pct"`
	HasTests        bool            `json:"has_tests"`
	AnalysisTime    time.Duration   `json:"analysis_time"`
}

TestCoverageResult represents the result of test coverage analysis.

func (*TestCoverageResult) ToMarkdown

func (r *TestCoverageResult) ToMarkdown() string

ToMarkdown generates a markdown representation of the test coverage result.

type TestFileInfo

type TestFileInfo struct {
	Path           string            `json:"path"`
	TestFunctions  []string          `json:"test_functions"`
	Benchmarks     []string          `json:"benchmarks"`
	SourceFile     string            `json:"source_file,omitempty"`
	CoveragePct    float64           `json:"coverage_pct,omitempty"`
	LastRun        time.Time         `json:"last_run,omitempty"`
	LastResult     string            `json:"last_result,omitempty"` // "pass", "fail", "skip"
	RelatedSources []string          `json:"related_sources,omitempty"`
	Metadata       map[string]string `json:"metadata,omitempty"`
}

TestFileInfo represents information about a test file.

Jump to

Keyboard shortcuts

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