Help us shape the future of Go! Take the 2026 Go Developer Survey

context

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2025 License: AGPL-3.0 Imports: 17 Imported by: 0

README

Context Management System

This package provides intelligent context management for Matey's AI interactions.

Components

manager.go
  • Token-aware context window management
  • File context tracking (reads, edits, mentions)
  • Intelligent truncation strategies
  • Integration with existing AI providers
  • Context persistence to Kubernetes
search.go
  • Ripgrep-inspired file discovery
  • Gitignore-aware filtering
  • Fuzzy filename matching
  • Directory structure analysis
  • Optimization for large codebases
mentions.go
  • Rich @-mention system like Cline:
    • @/path/file.ext - file content inclusion
    • @/path/folder/ - directory listing with file contents
    • @problems - Kubernetes events and pod diagnostics
    • @logs - recent pod logs
    • @git-changes - Git working directory status
  • Mention parsing and validation
  • Context-aware content inclusion
tracker.go
  • File context tracking across AI interactions
  • Cross-file reference detection
  • Context relevance scoring
  • Automatic context cleanup

Features

  • Smart Discovery: Intelligent file and content discovery
  • Context Awareness: Tracks what files and content the AI has seen
  • Mention System: Rich @-mention syntax for easy content inclusion
  • Token Management: Respects AI model context limits
  • Kubernetes Integration: Persists context state in cluster

Usage

This package enables:

  • AI assistants to maintain awareness of file changes
  • Smart content truncation to fit within token limits
  • Easy file and content referencing via mentions
  • Persistent context across chat sessions

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ContextConfig

type ContextConfig struct {
	MaxTokens          int                     `json:"max_tokens"`
	TruncationStrategy TruncationStrategy      `json:"truncation_strategy"`
	TypePriorities     map[ContextType]float64 `json:"type_priorities"`
	RetentionDays      int                     `json:"retention_days"`
	TokenEstimator     func(string) int        `json:"-"`
	PersistToK8s       bool                    `json:"persist_to_k8s"`
	Namespace          string                  `json:"namespace"`
}

ContextConfig configures the context manager behavior

type ContextItem

type ContextItem struct {
	ID          string                 `json:"id"`
	Type        ContextType            `json:"type"`
	FilePath    string                 `json:"file_path,omitempty"`
	Content     string                 `json:"content"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	TokenCount  int                    `json:"token_count"`
	Timestamp   time.Time              `json:"timestamp"`
	AccessCount int                    `json:"access_count"`
	LastAccess  time.Time              `json:"last_access"`
	Priority    float64                `json:"priority"`
	Hash        string                 `json:"hash"`
}

ContextItem represents a single piece of context information

type ContextManager

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

ContextManager manages the context window and provides intelligent truncation

func NewContextManager

func NewContextManager(config ContextConfig, aiProvider ai.Provider) *ContextManager

NewContextManager creates a new context manager with the given configuration

func (*ContextManager) AddContext

func (cm *ContextManager) AddContext(contextType ContextType, filePath, content string, metadata map[string]interface{}) error

AddContext adds a new context item to the manager

func (*ContextManager) CleanupExpired

func (cm *ContextManager) CleanupExpired() error

CleanupExpired removes context items older than the retention period

func (*ContextManager) GetContext

func (cm *ContextManager) GetContext(id string) (*ContextItem, error)

GetContext retrieves a context item by ID and updates access statistics

func (*ContextManager) GetContextByFile

func (cm *ContextManager) GetContextByFile(filePath string) ([]*ContextItem, error)

GetContextByFile retrieves all context items for a specific file

func (*ContextManager) GetCurrentWindow

func (cm *ContextManager) GetCurrentWindow() *ContextWindow

GetCurrentWindow returns the current context window

func (*ContextManager) GetStats

func (cm *ContextManager) GetStats() map[string]interface{}

GetStats returns statistics about the context manager

func (*ContextManager) LoadFromK8s

func (cm *ContextManager) LoadFromK8s(ctx context.Context) error

LoadFromK8s loads context from Kubernetes ConfigMaps and Secrets

func (*ContextManager) RemoveContext

func (cm *ContextManager) RemoveContext(id string) error

RemoveContext removes a context item by ID

func (*ContextManager) RemoveContextByFile

func (cm *ContextManager) RemoveContextByFile(filePath string) error

RemoveContextByFile removes all context items for a specific file

func (*ContextManager) SaveToK8s

func (cm *ContextManager) SaveToK8s(ctx context.Context) error

SaveToK8s saves context to Kubernetes ConfigMaps and Secrets

func (*ContextManager) UpdateFilePath

func (cm *ContextManager) UpdateFilePath(oldPath, newPath string) error

UpdateFilePath updates the file path for all context items (for file renames)

func (*ContextManager) UpdateMaxTokens

func (cm *ContextManager) UpdateMaxTokens(maxTokens int)

UpdateMaxTokens dynamically updates the maximum token limit

type ContextType

type ContextType string

ContextType represents different types of context content

const (
	ContextTypeFile       ContextType = "file"
	ContextTypeEdit       ContextType = "edit"
	ContextTypeMention    ContextType = "mention"
	ContextTypeLog        ContextType = "log"
	ContextTypeDiagnostic ContextType = "diagnostic"
	ContextTypeGit        ContextType = "git"
	ContextTypeDefinition ContextType = "definition"
)

type ContextWindow

type ContextWindow struct {
	Items       []ContextItem `json:"items"`
	TotalTokens int           `json:"total_tokens"`
	MaxTokens   int           `json:"max_tokens"`
	Truncated   bool          `json:"truncated"`
	Strategy    string        `json:"strategy"`
}

ContextWindow represents the current context state

type FileDiscovery

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

FileDiscovery provides high-performance file discovery with git integration

func NewFileDiscovery

func NewFileDiscovery(workDir string) (*FileDiscovery, error)

NewFileDiscovery creates a new file discovery instance

func (*FileDiscovery) FindRecentFiles

func (fd *FileDiscovery) FindRecentFiles(since time.Time, maxResults int) ([]SearchResult, error)

FindRecentFiles finds recently modified files

func (*FileDiscovery) GetDirectoryStructure

func (fd *FileDiscovery) GetDirectoryStructure(rootPath string, maxDepth int) (map[string]interface{}, error)

GetDirectoryStructure returns a tree-like structure of the directory

func (*FileDiscovery) GetGitBranch

func (fd *FileDiscovery) GetGitBranch() string

GetGitBranch returns the current git branch

func (*FileDiscovery) GetRecentCommits

func (fd *FileDiscovery) GetRecentCommits(limit int) ([]map[string]interface{}, error)

GetRecentCommits returns recent commits for context

func (*FileDiscovery) GetRepoRoot

func (fd *FileDiscovery) GetRepoRoot() string

GetRepoRoot finds the git repository root

func (*FileDiscovery) Search

func (fd *FileDiscovery) Search(ctx context.Context, options SearchOptions) ([]SearchResult, error)

Search performs file discovery with the given options

func (*FileDiscovery) SearchByExtension

func (fd *FileDiscovery) SearchByExtension(extensions []string, maxResults int) ([]SearchResult, error)

SearchByExtension finds files with specific extensions

func (*FileDiscovery) SearchFiles

func (fd *FileDiscovery) SearchFiles(pattern string, maxResults int) ([]SearchResult, error)

SearchFiles is a convenience method for finding files by pattern

type Mention

type Mention struct {
	Type       MentionType            `json:"type"`
	Raw        string                 `json:"raw"`
	Path       string                 `json:"path,omitempty"`
	Content    string                 `json:"content"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
	Lines      []int                  `json:"lines,omitempty"`
	TokenCount int                    `json:"token_count"`
	Error      string                 `json:"error,omitempty"`
}

Mention represents a parsed mention from user input

type MentionConfig

type MentionConfig struct {
	MaxFileSize    int64         `json:"max_file_size"`
	MaxDirFiles    int           `json:"max_dir_files"`
	MaxLogLines    int           `json:"max_log_lines"`
	DefaultLines   int           `json:"default_lines"`
	IncludeHidden  bool          `json:"include_hidden"`
	FollowSymlinks bool          `json:"follow_symlinks"`
	Timeout        time.Duration `json:"timeout"`
}

MentionConfig configures mention processing behavior

type MentionProcessor

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

MentionProcessor handles parsing and resolving mentions

func NewMentionProcessor

func NewMentionProcessor(workDir string, fileDiscovery *FileDiscovery, contextManager *ContextManager) *MentionProcessor

NewMentionProcessor creates a new mention processor

func (*MentionProcessor) ExpandText

func (mp *MentionProcessor) ExpandText(text string) (string, []Mention, error)

ExpandText replaces all mentions in text with their resolved content

func (*MentionProcessor) GetSupportedMentions

func (mp *MentionProcessor) GetSupportedMentions() map[string]string

GetSupportedMentions returns information about all supported mention types

func (*MentionProcessor) ParseMentions

func (mp *MentionProcessor) ParseMentions(text string) ([]Mention, error)

ParseMentions parses all mentions from a text string

func (*MentionProcessor) ProcessMention

func (mp *MentionProcessor) ProcessMention(mention Mention) (Mention, error)

ProcessMention processes a single mention and returns its content

type MentionType

type MentionType string

MentionType represents different types of mentions

const (
	MentionTypeFile       MentionType = "file"
	MentionTypeDirectory  MentionType = "directory"
	MentionTypeProblems   MentionType = "problems"
	MentionTypeLogs       MentionType = "logs"
	MentionTypeGitChanges MentionType = "git-changes"
	MentionTypeDefinition MentionType = "definition"
	MentionTypeMemory     MentionType = "memory"
	MentionTypeWorkflow   MentionType = "workflow"
)

type SearchOptions

type SearchOptions struct {
	// Base search directory
	Root string `json:"root"`

	// Pattern matching
	Pattern    string   `json:"pattern,omitempty"`
	Extensions []string `json:"extensions,omitempty"`
	Include    []string `json:"include,omitempty"` // Include patterns
	Exclude    []string `json:"exclude,omitempty"` // Exclude patterns

	// Search behavior
	MaxResults     int  `json:"max_results"`
	MaxDepth       int  `json:"max_depth"`
	FollowSymlinks bool `json:"follow_symlinks"`
	IncludeHidden  bool `json:"include_hidden"`

	// Git integration
	RespectGitignore bool `json:"respect_gitignore"`
	IncludeGitStatus bool `json:"include_git_status"`

	// Performance
	Concurrent bool          `json:"concurrent"`
	Timeout    time.Duration `json:"timeout"`
}

SearchOptions configures file discovery behavior

type SearchResult

type SearchResult struct {
	Path         string    `json:"path"`
	RelativePath string    `json:"relative_path"`
	Type         string    `json:"type"` // file, directory, symlink
	Size         int64     `json:"size"`
	ModTime      time.Time `json:"mod_time"`
	GitStatus    string    `json:"git_status,omitempty"`
	Score        int       `json:"score,omitempty"`   // For fuzzy matching
	Matches      []string  `json:"matches,omitempty"` // Matched portions
}

SearchResult represents a file discovery result

type TruncationStrategy

type TruncationStrategy string

TruncationStrategy defines how context should be truncated when limits are exceeded

const (
	TruncateOldest      TruncationStrategy = "oldest"
	TruncateLRU         TruncationStrategy = "lru"
	TruncateByType      TruncationStrategy = "by_type"
	TruncateByPriority  TruncationStrategy = "by_priority"
	TruncateIntelligent TruncationStrategy = "intelligent"
)

Jump to

Keyboard shortcuts

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