context

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
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

View Source
const StatsCacheDirName = "stats-cache"

Variables

View Source
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.

View Source
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.

View Source
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

func ExpandBraces(pattern string) []string

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

func ExtractCommitFromPath(filePath string) string

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

func FindRulesetFile(projectPath, rulesetName string) (string, error)

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 FormatBytes

func FormatBytes(bytes int) string

FormatBytes formats byte count for display

func FormatTokenCount

func FormatTokenCount(tokens int) string

FormatTokenCount formats a token count for display

func GetCacheFilePathForRepo

func GetCacheFilePathForRepo(repoURL string) (string, error)

GetCacheFilePathForRepo returns the path to the cache file for a given repository. Deprecated: Use getCacheFilePathForWorktree instead. Kept for backwards compatibility.

func GetExtsFromLanguage

func GetExtsFromLanguage(extName string) []string

GetExtsFromLanguage returns the file extensions for a file type. For files without extensions (basenames like "Makefile"), returns the basename pattern.

func GetGitInfo

func GetGitInfo() (branch string, hasChanges bool, err error)

GetGitInfo returns information about the current git state

func IsBinaryFile

func IsBinaryFile(path string) bool

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

func TruncatePath(path string, maxLen int) string

TruncatePath shortens a path for display

Types

type AttributionResult

type AttributionResult map[int][]string

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

type ExclusionResult map[int][]string

ExclusionResult maps a line number to the list of files it excluded.

type FileInfo

type FileInfo struct {
	Path   string
	Tokens int
	Size   int64
}

FileInfo represents information about a file

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 NewManager

func NewManager(workDir string) *Manager

NewManager creates a new context manager

func (*Manager) AppendRule

func (m *Manager) AppendRule(rulePath, contextType string) error

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

func (m *Manager) EditRulesCmd() (*exec.Cmd, error)

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

func (m *Manager) EnsureAndGetRulesPath() (string, error)

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

func (m *Manager) FixContext() error

FixContext removes invalid files and duplicates from the context (deprecated - no longer applicable with dynamic resolution)

func (*Manager) GenerateCachedContext

func (m *Manager) GenerateCachedContext() error

GenerateCachedContext generates .grove/cached-context with only the cold context files.

func (*Manager) GenerateContext

func (m *Manager) GenerateContext(useXMLFormat bool) error

GenerateContext creates the context file from the files list

func (*Manager) GenerateContextFromRulesFile

func (m *Manager) GenerateContextFromRulesFile(rulesFilePath string, useXMLFormat bool) error

GenerateContextFromRulesFile generates context from an explicit rules file path.

func (*Manager) GetAllowedRoots

func (m *Manager) GetAllowedRoots() ([]string, error)

GetAllowedRoots returns the list of sandboxed root directories for scanning.

func (*Manager) GetDefaultRuleName

func (m *Manager) GetDefaultRuleName() string

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

func (m *Manager) GetExpireTime() (time.Duration, error)

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) GetStats

func (m *Manager) GetStats(contextType string, files []string, topN int) (*ContextStats, error)

GetStats analyzes the context and returns comprehensive statistics

func (*Manager) GetWorkDir

func (m *Manager) GetWorkDir() string

GetWorkDir returns the current working directory

func (*Manager) IsPathAllowed

func (m *Manager) IsPathAllowed(path string) (bool, string)

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) ListFiles

func (m *Manager) ListFiles() ([]string, error)

ListFiles returns the list of files in the context

func (*Manager) ListGitRules

func (m *Manager) ListGitRules() ([]GitRule, error)

ListGitRules parses the active rules file and returns a slice of all Git-based rules.

func (*Manager) ListPlanRules

func (m *Manager) ListPlanRules() ([]PlanRule, error)

ListPlanRules discovers and returns all rules files from grove-flow plans across all workspaces.

func (*Manager) LoadDefaultRulesContent

func (m *Manager) LoadDefaultRulesContent() (content []byte, rulesPath string)

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

func (m *Manager) LoadRulesContent() (content []byte, path string, err error)

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

func (m *Manager) ParseGitRule(rule string) (isGitURL bool, repoURL, version, ruleset string)

ParseGitRule checks if a rule is a Git URL and extracts the URL, optional version, and optional ruleset

func (*Manager) ReadFilesList

func (m *Manager) ReadFilesList(filename string) ([]string, error)

ReadFilesList reads the list of files from a file

func (*Manager) RemoveRule

func (m *Manager) RemoveRule(rulePath string) error

RemoveRule removes a specific rule from the rules file

func (*Manager) RemoveRuleForPath

func (m *Manager) RemoveRuleForPath(path string) error

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

func (m *Manager) ResolveColdContextFiles() ([]string, error)

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

func (m *Manager) ResolveFilesFromPatterns(patterns []string) ([]string, error)

ResolveFilesFromPatterns exposes the internal file resolution logic for external use. It resolves files from a given set of patterns.

func (*Manager) ResolveFilesFromRules

func (m *Manager) ResolveFilesFromRules() ([]string, error)

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

func (m *Manager) ResolveLineForRulePreview(line string) (string, error)

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

func (m *Manager) SetActiveRules(sourcePath string) error

SetActiveRules copies a rules file to the active rules location

func (*Manager) ShouldDisableCache

func (m *Manager) ShouldDisableCache() (bool, error)

ShouldDisableCache checks if the @disable-cache directive is present in the rules file.

func (*Manager) ShouldDisableExpiration

func (m *Manager) ShouldDisableExpiration() (bool, error)

ShouldDisableExpiration checks if the @no-expire directive is present in the rules file.

func (*Manager) ShouldFreezeCache

func (m *Manager) ShouldFreezeCache() (bool, error)

ShouldFreezeCache checks if the @freeze-cache directive is present in the rules file.

func (*Manager) ShowContext

func (m *Manager) ShowContext() error

ShowContext outputs the context file content

func (*Manager) ToggleViewDirective

func (m *Manager) ToggleViewDirective(path string) error

ToggleViewDirective adds or removes a `@view:` directive from the rules file.

func (*Manager) UpdateFromCmd

func (m *Manager) UpdateFromCmd(command string) error

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

func (m *Manager) UpdateFromRules() error

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

func (m *Manager) WriteFilesList(filename string, files []string) error

WriteFilesList writes a list of files to a file

func (*Manager) WriteRulesTo

func (m *Manager) WriteRulesTo(destPath string) error

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

type SkippedRule struct {
	LineNum int
	Rule    string
	Reason  string
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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