Documentation
¶
Index ¶
- Constants
- Variables
- func ExpandBraces(pattern string) []string
- func ExtractCommitFromPath(filePath string) string
- func FindRulesetFile(projectPath, rulesetName string) (string, error)
- func FormatBytes(bytes int) string
- func FormatTokenCount(tokens int) string
- func GetCacheFilePathForRepo(repoURL string) (string, error)
- func GetExtsFromLanguage(extName string) []string
- func GetGitInfo() (branch string, hasChanges bool, err error)
- func IsBinaryFile(path string) bool
- func MatchesGitRule(rule GitRule, ...) bool
- func TruncatePath(path string, maxLen int) string
- type AttributionResult
- type CachedFileStats
- type ConceptManifest
- type ContextConfig
- type ContextStats
- type DiffResult
- type ExclusionResult
- type FileInfo
- type FileStats
- type FilteredFileInfo
- type FilteredResult
- type GitOptions
- type GitRule
- type ImportInfo
- type LanguageStats
- type LineType
- type Manager
- func (m *Manager) AppendRule(rulePath, contextType string) error
- func (m *Manager) ClassifyAllProjectFiles(showGitIgnored bool) (map[string]NodeStatus, error)
- func (m *Manager) ClearSkippedRules()
- func (m *Manager) DiffContext(rulesetName string) (*DiffResult, error)
- func (m *Manager) EditRulesCmd() (*exec.Cmd, error)
- func (m *Manager) EnsureAndGetRulesPath() (string, error)
- func (m *Manager) FixContext() error
- func (m *Manager) GenerateCachedContext() error
- func (m *Manager) GenerateContext(useXMLFormat bool) error
- func (m *Manager) GenerateContextFromRulesFile(rulesFilePath string, useXMLFormat bool) error
- func (m *Manager) GetAllowedRoots() ([]string, error)
- func (m *Manager) GetDefaultRuleName() string
- func (m *Manager) GetExpireTime() (time.Duration, error)
- func (m *Manager) GetRuleStatus(rulePath string) RuleStatus
- func (m *Manager) GetSkippedRules() []SkippedRule
- func (m *Manager) GetStats(contextType string, files []string, topN int) (*ContextStats, error)
- func (m *Manager) GetWorkDir() string
- func (m *Manager) IsPathAllowed(path string) (bool, string)
- func (m *Manager) ListFiles() ([]string, error)
- func (m *Manager) ListGitRules() ([]GitRule, error)
- func (m *Manager) ListPlanRules() ([]PlanRule, error)
- func (m *Manager) LoadDefaultRulesContent() (content []byte, rulesPath string)
- func (m *Manager) LoadRulesContent() (content []byte, path string, err error)
- func (m *Manager) ParseGitRule(rule string) (isGitURL bool, repoURL, version, ruleset string)
- func (m *Manager) ReadFilesList(filename string) ([]string, error)
- func (m *Manager) RemoveRule(rulePath string) error
- func (m *Manager) RemoveRuleForPath(path string) error
- func (m *Manager) ResolveColdContextFiles() ([]string, error)
- func (m *Manager) ResolveFilesFromCustomRulesFile(rulesFilePath string) (hotFiles []string, coldFiles []string, err error)
- func (m *Manager) ResolveFilesFromPatterns(patterns []string) ([]string, error)
- func (m *Manager) ResolveFilesFromRules() ([]string, error)
- func (m *Manager) ResolveFilesWithAttribution(rulesContent string) (AttributionResult, []RuleInfo, ExclusionResult, FilteredResult, error)
- func (m *Manager) ResolveLineForRulePreview(line string) (string, error)
- func (m *Manager) SetActiveRules(sourcePath string) error
- func (m *Manager) ShouldDisableCache() (bool, error)
- func (m *Manager) ShouldDisableExpiration() (bool, error)
- func (m *Manager) ShouldFreezeCache() (bool, error)
- func (m *Manager) ShowContext() error
- func (m *Manager) ToggleViewDirective(path string) error
- func (m *Manager) UpdateFromCmd(command string) error
- func (m *Manager) UpdateFromGit(opts GitOptions) error
- func (m *Manager) UpdateFromRules() error
- func (m *Manager) ValidateContext(files []string) (*ValidationResult, error)
- func (m *Manager) WriteFilesList(filename string, files []string) error
- func (m *Manager) WriteRulesTo(destPath string) error
- type NodeStatus
- type ParsedLine
- type PlanRule
- type RepoCache
- type RuleInfo
- type RuleStatus
- type SkippedRule
- type StatsProvider
- type TokenDistribution
- type ValidationResult
Constants ¶
const ( GroveDir = ".grove" ContextFile = ".grove/context" FilesListFile = ".grove/context-files" RulesFile = ".grovectx" ActiveRulesFile = ".grove/rules" CachedContextFilesListFile = ".grove/cached-context-files" CachedContextFile = ".grove/cached-context" RulesDir = ".cx" RulesWorkDir = ".cx.work" RulesExt = ".rules" )
Constants for context file paths
const StatsCacheDirName = "stats-cache"
Variables ¶
var BinaryExtensions = map[string]bool{ ".exe": true, ".dll": true, ".so": true, ".dylib": true, ".a": true, ".o": true, ".obj": true, ".lib": true, ".bin": true, ".dat": true, ".db": true, ".sqlite": true, ".sqlite3": true, ".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".bmp": true, ".ico": true, ".tiff": true, ".webp": true, ".mp3": true, ".mp4": true, ".avi": true, ".mov": true, ".wmv": true, ".flv": true, ".webm": true, ".m4a": true, ".flac": true, ".wav": true, ".zip": true, ".tar": true, ".gz": true, ".bz2": true, ".xz": true, ".7z": true, ".rar": true, ".deb": true, ".rpm": true, ".dmg": true, ".pkg": true, ".msi": true, ".pdf": true, ".doc": true, ".docx": true, ".xls": true, ".xlsx": true, ".ppt": true, ".pptx": true, ".odt": true, ".ods": true, ".odp": true, ".pyc": true, ".pyo": true, ".class": true, ".jar": true, ".war": true, ".woff": true, ".woff2": true, ".ttf": true, ".otf": true, ".eot": true, ".wasm": true, ".node": true, }
BinaryExtensions contains a map of common binary file extensions for fast checking.
var IsZombieWorktree = workspace.IsZombieWorktree
IsZombieWorktree checks if the given path is inside a deleted git worktree. This is a re-export of workspace.IsZombieWorktree from grove-core for convenience.
A worktree is considered "zombie" if it's inside a .grove-worktrees directory but the .git file (which links to the main repo) is missing.
This is used to prevent recreating .grove/rules files in deleted worktrees, which would cause "zombie" directories to reappear after cleanup.
var IsZombieWorktreeCwd = workspace.IsZombieWorktreeCwd
IsZombieWorktreeCwd checks if the current working directory is inside a zombie worktree. This is a re-export of workspace.IsZombieWorktreeCwd from grove-core for convenience.
Functions ¶
func ExpandBraces ¶
ExpandBraces recursively expands shell-style brace patterns. Example: "path/{a,b}/{c,d}" -> ["path/a/c", "path/a/d", "path/b/c", "path/b/d"]
func ExtractCommitFromPath ¶
ExtractCommitFromPath extracts the commit hash from a worktree path. Returns the commit hash if the path is inside a .grove-worktrees directory, empty string otherwise.
func FindRulesetFile ¶
FindRulesetFile searches for a ruleset file by name in both .cx.work/ and .cx/ directories. It returns the absolute path to the file if found, or an error if not found. This function checks .cx.work/ first for local overrides, then .cx/ as a fallback.
func FormatTokenCount ¶
FormatTokenCount formats a token count for display
func GetCacheFilePathForRepo ¶
GetCacheFilePathForRepo returns the path to the cache file for a given repository. Deprecated: Use getCacheFilePathForWorktree instead. Kept for backwards compatibility.
func GetExtsFromLanguage ¶
GetExtsFromLanguage returns the file extensions for a file type. For files without extensions (basenames like "Makefile"), returns the basename pattern.
func GetGitInfo ¶
GetGitInfo returns information about the current git state
func IsBinaryFile ¶
IsBinaryFile checks if a file is binary based on extension or content.
func MatchesGitRule ¶
func MatchesGitRule(rule GitRule, projectRepoURL, projectVersion, projectHeadCommit, projectPath string) bool
MatchesGitRule checks if a project matches a Git rule by comparing repo URL and version. It handles exact version matches, partial commit hash matches, and branch-to-commit resolution. Parameters:
- rule: the Git rule to match against
- projectRepoURL: the project's repository URL (e.g., "https://github.com/owner/repo")
- projectVersion: the project's current branch or version string
- projectHeadCommit: the project's current HEAD commit hash
- projectPath: the project's filesystem path (used for git ref resolution)
func TruncatePath ¶
TruncatePath shortens a path for display
Types ¶
type AttributionResult ¶
AttributionResult maps a line number to the list of files it includes.
type CachedFileStats ¶
type CachedFileStats struct {
Path string `json:"path"`
Size int64 `json:"size"`
Tokens int `json:"tokens"`
}
CachedFileStats holds statistics for a single file in the cache.
type ConceptManifest ¶
type ConceptManifest struct {
ID string `yaml:"id"`
Title string `yaml:"title"`
Description string `yaml:"description"`
Status string `yaml:"status"`
RelatedConcepts []string `yaml:"related_concepts"`
RelatedPlans []string `yaml:"related_plans"`
RelatedNotes []string `yaml:"related_notes"`
}
ConceptManifest represents the structure of a concept-manifest.yml file
type ContextConfig ¶
type ContextConfig struct {
// IncludedWorkspaces is a strict allowlist: if set, only these workspaces are scanned for context.
IncludedWorkspaces []string `yaml:"included_workspaces,omitempty"`
// ExcludedWorkspaces is a denylist: these workspaces are excluded from context scanning.
// Ignored if IncludedWorkspaces is set.
ExcludedWorkspaces []string `yaml:"excluded_workspaces,omitempty"`
// AllowedPaths is a list of additional paths that can be included in context,
// regardless of workspace boundaries. Paths can be absolute or use ~/ for home directory.
AllowedPaths []string `yaml:"allowed_paths,omitempty"`
}
ContextConfig defines configuration specific to grove-context. This is intended to be nested under the "context" key in grove.yml Extensions.
type ContextStats ¶
type ContextStats struct {
ContextType string `json:"context_type"`
TotalFiles int `json:"total_files"`
TotalTokens int `json:"total_tokens"`
TotalSize int64 `json:"total_size"`
Languages map[string]*LanguageStats `json:"languages"`
LargestFiles []FileStats `json:"largest_files"`
AllFiles []FileStats `json:"all_files"`
Distribution []TokenDistribution `json:"distribution"`
AvgTokens int `json:"avg_tokens"`
MedianTokens int `json:"median_tokens"`
}
ContextStats contains comprehensive statistics about the context
func (*ContextStats) Print ¶
func (s *ContextStats) Print(title string)
Print displays context statistics by printing the lipgloss-styled string output.
func (*ContextStats) String ¶
func (s *ContextStats) String(title string) string
String displays context statistics in a formatted, lipgloss-styled string
type DiffResult ¶
type DiffResult struct {
Added []FileInfo
Removed []FileInfo
CurrentFiles map[string]FileInfo
CompareFiles map[string]FileInfo
CurrentTotalTokens int
CompareTotalTokens int
CurrentTotalSize int64
CompareTotalSize int64
}
DiffResult contains the results of a context diff operation
func (*DiffResult) Print ¶
func (d *DiffResult) Print(compareName string)
PrintDiff displays the diff result in a formatted way
type ExclusionResult ¶
ExclusionResult maps a line number to the list of files it excluded.
type FileStats ¶
type FileStats struct {
Path string `json:"path"`
Tokens int `json:"tokens"`
Size int64 `json:"size"`
Percentage float64 `json:"percentage"`
}
FileStats contains statistics for a single file
type FilteredFileInfo ¶
type FilteredFileInfo struct {
File string `json:"file"`
WinningLineNum int `json:"winningLineNum"`
}
FilteredFileInfo tracks a file that was filtered and where it ended up
type FilteredResult ¶
type FilteredResult map[int][]FilteredFileInfo
FilteredResult maps a line number to files that matched the base pattern but were filtered by directive.
type GitOptions ¶
type GitOptions struct {
Since string // Include files changed since date/commit
Branch string // Include files changed in branch (e.g., main..HEAD)
Staged bool // Include only staged files
Commits int // Include files from last N commits
}
GitOptions contains options for git-based context generation
type GitRule ¶
type GitRule struct {
RepoURL string
Version string
Ruleset string
ContextType RuleStatus
IsExclude bool
}
GitRule represents a parsed Git alias rule from the rules file.
type ImportInfo ¶
type ImportInfo struct {
OriginalLine string `json:"originalLine,omitempty"` // The full original line text
ImportIdentifier string // e.g., "project:ruleset"
LineNum int // The line number where this import appears
Directive string `json:"directive,omitempty"` // e.g., "find" or "grep"
DirectiveQuery string `json:"directiveQuery,omitempty"` // the search query
}
ImportInfo holds information about a ruleset import with its line number.
type LanguageStats ¶
type LanguageStats struct {
Name string `json:"name"`
FileCount int `json:"file_count"`
TotalTokens int `json:"total_tokens"`
Percentage float64 `json:"percentage"`
Patterns []string `json:"-"` // Glob patterns for exclusion, e.g., "**/*.go"
}
LanguageStats contains statistics for a programming language
type LineType ¶
type LineType int
LineType represents the type of a rules file line
const ( LineTypeUnknown LineType = iota LineTypeComment LineTypeSeparator LineTypeExclude LineTypeGitURL LineTypeGitURLRuleset LineTypeRulesetImport LineTypeAliasPattern LineTypeViewDirective LineTypeCmdDirective LineTypeFindDirective LineTypeGrepDirective LineTypeOtherDirective LineTypePattern LineTypeEmpty )
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager handles context operations
func (*Manager) AppendRule ¶
AppendRule adds a rule to the active rules file in the specified context contextType can be "hot", "cold", or "exclude".
func (*Manager) ClassifyAllProjectFiles ¶
func (m *Manager) ClassifyAllProjectFiles(showGitIgnored bool) (map[string]NodeStatus, error)
ClassifyAllProjectFiles is the unified, deterministic classification engine that resolves and classifies all files based on context rules. It returns a map of file paths to their NodeStatus. This method ensures consistency across all views (tree, stats, list).
func (*Manager) ClearSkippedRules ¶
func (m *Manager) ClearSkippedRules()
ClearSkippedRules clears the list of skipped rules
func (*Manager) DiffContext ¶
func (m *Manager) DiffContext(rulesetName string) (*DiffResult, error)
DiffContext compares the current context with a named rule set or another context
func (*Manager) EditRulesCmd ¶
EditRulesCmd prepares an *exec.Cmd to open the active rules file in an editor. It handles finding/creating the rules file, determining the editor, and setting the working directory to the git root for a consistent editing experience.
func (*Manager) EnsureAndGetRulesPath ¶
EnsureAndGetRulesPath finds the active rules file, creates it with boilerplate if it doesn't exist, and returns its absolute path. This is useful for integrations that need to open the file directly.
func (*Manager) FixContext ¶
FixContext removes invalid files and duplicates from the context (deprecated - no longer applicable with dynamic resolution)
func (*Manager) GenerateCachedContext ¶
GenerateCachedContext generates .grove/cached-context with only the cold context files.
func (*Manager) GenerateContext ¶
GenerateContext creates the context file from the files list
func (*Manager) GenerateContextFromRulesFile ¶
GenerateContextFromRulesFile generates context from an explicit rules file path.
func (*Manager) GetAllowedRoots ¶
GetAllowedRoots returns the list of sandboxed root directories for scanning.
func (*Manager) GetDefaultRuleName ¶
GetDefaultRuleName returns the name of the default rule set from grove.yml. For example, if default_rules_path is ".cx/dev-no-tests.rules", it returns "dev-no-tests". Returns empty string if no default is configured.
func (*Manager) GetExpireTime ¶
GetExpireTime returns the custom expiration duration if @expire-time directive is present. Returns 0 if no custom expiration time is set.
func (*Manager) GetRuleStatus ¶
func (m *Manager) GetRuleStatus(rulePath string) RuleStatus
GetRuleStatus checks the current status of a rule in the rules file
func (*Manager) GetSkippedRules ¶
func (m *Manager) GetSkippedRules() []SkippedRule
GetSkippedRules returns the list of rules that were skipped during the last parsing operation
func (*Manager) GetWorkDir ¶
GetWorkDir returns the current working directory
func (*Manager) IsPathAllowed ¶
IsPathAllowed checks if a given path is within one of the allowed workspace roots. It returns true if allowed, or false and a reason string if not.
func (*Manager) ListGitRules ¶
ListGitRules parses the active rules file and returns a slice of all Git-based rules.
func (*Manager) ListPlanRules ¶
ListPlanRules discovers and returns all rules files from grove-flow plans across all workspaces.
func (*Manager) LoadDefaultRulesContent ¶
LoadDefaultRulesContent loads only the default rules from grove.yml, ignoring any local rules files. It returns the default rules content and the path where rules should be written.
func (*Manager) LoadRulesContent ¶
LoadRulesContent finds and reads the active rules file, falling back to grove.yml defaults. It returns the content of the rules, the path of the file read (if any), and an error.
func (*Manager) ParseGitRule ¶
ParseGitRule checks if a rule is a Git URL and extracts the URL, optional version, and optional ruleset
func (*Manager) ReadFilesList ¶
ReadFilesList reads the list of files from a file
func (*Manager) RemoveRule ¶
RemoveRule removes a specific rule from the rules file
func (*Manager) RemoveRuleForPath ¶
RemoveRuleForPath removes any rule that corresponds to the given repository path. Unlike RemoveRule which requires an exact match, this function will find and remove rules in various formats (path, !path, path/**, !path/**) that match the repository.
func (*Manager) ResolveColdContextFiles ¶
ResolveColdContextFiles resolves the list of files from the "cold" section of a rules file.
func (*Manager) ResolveFilesFromCustomRulesFile ¶
func (m *Manager) ResolveFilesFromCustomRulesFile(rulesFilePath string) (hotFiles []string, coldFiles []string, err error)
ResolveFilesFromCustomRulesFile resolves both hot and cold files from a custom rules file path.
func (*Manager) ResolveFilesFromPatterns ¶
ResolveFilesFromPatterns exposes the internal file resolution logic for external use. It resolves files from a given set of patterns.
func (*Manager) ResolveFilesFromRules ¶
ResolveFilesFromRules dynamically resolves the list of files from the active rules file
func (*Manager) ResolveFilesWithAttribution ¶
func (m *Manager) ResolveFilesWithAttribution(rulesContent string) (AttributionResult, []RuleInfo, ExclusionResult, FilteredResult, error)
ResolveFilesWithAttribution walks the filesystem once and attributes each included file to the rule that was responsible for its inclusion. It also tracks exclusions and filtered matches.
func (*Manager) ResolveLineForRulePreview ¶
ResolveLineForRulePreview resolves a single rule line, handling aliases. It is intended for use by tools like the Neovim plugin's rule previewer.
func (*Manager) SetActiveRules ¶
SetActiveRules copies a rules file to the active rules location
func (*Manager) ShouldDisableCache ¶
ShouldDisableCache checks if the @disable-cache directive is present in the rules file.
func (*Manager) ShouldDisableExpiration ¶
ShouldDisableExpiration checks if the @no-expire directive is present in the rules file.
func (*Manager) ShouldFreezeCache ¶
ShouldFreezeCache checks if the @freeze-cache directive is present in the rules file.
func (*Manager) ShowContext ¶
ShowContext outputs the context file content
func (*Manager) ToggleViewDirective ¶
ToggleViewDirective adds or removes a `@view:` directive from the rules file.
func (*Manager) UpdateFromCmd ¶
UpdateFromCmd updates the context rules file from the output of a shell command
func (*Manager) UpdateFromGit ¶
func (m *Manager) UpdateFromGit(opts GitOptions) error
UpdateFromGit updates the context files list based on git history
func (*Manager) UpdateFromRules ¶
UpdateFromRules updates the files list based on rules file patterns (deprecated - kept for compatibility)
func (*Manager) ValidateContext ¶
func (m *Manager) ValidateContext(files []string) (*ValidationResult, error)
ValidateContext checks the integrity of all files in the context
func (*Manager) WriteFilesList ¶
WriteFilesList writes a list of files to a file
func (*Manager) WriteRulesTo ¶
WriteRulesTo writes the current active rules to a specified file path
type NodeStatus ¶
type NodeStatus int
NodeStatus represents the classification of a file in the context
const ( StatusIncludedHot NodeStatus = iota // In hot context StatusIncludedCold // In cold context StatusExcludedByRule // Matched an include rule, but then an exclude rule StatusOmittedNoMatch // Not matched by any include rule StatusIgnoredByGit // Ignored by .gitignore (not used in final result) StatusDirectory // A directory containing other nodes )
type ParsedLine ¶
type ParsedLine struct {
Type LineType
Content string
Parts map[string]string // For storing parsed components
}
ParsedLine represents a parsed line from a rules file
func ParseRulesLine ¶
func ParseRulesLine(line string) ParsedLine
ParseRulesLine parses a single line from a rules file and returns its type and parsed components
type PlanRule ¶
type PlanRule struct {
Name string // e.g., "01-chat.md.rules"
Path string // Absolute path to the file
PlanName string
WorkspaceName string
}
PlanRule holds information about a rules file discovered within a grove-flow plan.
type RepoCache ¶
type RepoCache struct {
WorktreePath string `json:"worktreePath"`
CreatedAt time.Time `json:"createdAt"`
Files map[string]CachedFileStats `json:"files"` // Use map for faster lookups
}
RepoCache is the structure of the cache file stored in the stats cache directory. It is now keyed by the worktree path, which implicitly includes the commit hash.
type RuleInfo ¶
type RuleInfo struct {
Pattern string
IsExclude bool
LineNum int // The line number in its original source file
EffectiveLineNum int // The line number in the root file that caused this rule to be included
Directive string `json:"directive,omitempty"` // e.g., "find" or "grep"
DirectiveQuery string `json:"directiveQuery,omitempty"` // the search query
}
RuleInfo holds a parsed rule with its line number and origin.
type RuleStatus ¶
type RuleStatus int
RuleStatus represents the current state of a rule
const ( RuleNotFound RuleStatus = iota // Rule doesn't exist RuleHot // Rule exists in hot context RuleCold // Rule exists in cold context RuleExcluded // Rule exists as exclusion // StateSourceKey is the key used in grove-core state to store the path to the active rule set. StateSourceKey = "context.active_rules_source" )
type SkippedRule ¶
SkippedRule represents a rule that was skipped during parsing along with the reason why
type StatsProvider ¶
type StatsProvider struct {
// contains filtered or unexported fields
}
StatsProvider provides file statistics, using a cache for managed repositories.
func GetStatsProvider ¶
func GetStatsProvider() *StatsProvider
GetStatsProvider returns a singleton instance of the StatsProvider.
func (*StatsProvider) GetFileStats ¶
func (sp *StatsProvider) GetFileStats(filePath string) (FileInfo, error)
GetFileStats returns statistics for a file, utilizing the worktree cache if applicable.
type TokenDistribution ¶
type TokenDistribution struct {
RangeLabel string `json:"range_label"`
FileCount int `json:"file_count"`
Percentage float64 `json:"percentage"`
}
TokenDistribution represents a range of token counts
type ValidationResult ¶
type ValidationResult struct {
TotalFiles int
AccessibleFiles int
MissingFiles []string
Duplicates map[string]int
PermissionIssues []string
}
ValidationResult contains the results of context validation
func (*ValidationResult) Print ¶
func (r *ValidationResult) Print()
PrintValidationResults displays validation results in a formatted way