cass

package
v0.14.4 Latest Latest
Warning

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

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

Documentation

Overview

Package cass provides detection and health checking for the cass search tool. Cass is an external binary for semantic code search that may or may not be installed.

Package cass provides integration with the cass semantic code search tool.

Cass (https://github.com/cass-lang/cass) is an external binary that provides semantic code search capabilities. This package handles detection and health checking to determine if cass is available before attempting integration.

Detection Flow

The Detector performs a two-step detection process:

  1. Check if "cass" exists in PATH using exec.LookPath
  2. Run "cass health" with a configurable timeout (default 2s)

Health Status

Based on the exit code from "cass health":

Exit 0: StatusHealthy - ready to search
Exit 1: StatusNeedsIndex - needs indexing before use
Exit 3: StatusNeedsIndex - index missing or corrupt
Other:  StatusNotInstalled - treat as unavailable

Caching

Detection results are cached for 5 minutes by default (configurable). This avoids repeated subprocess calls during normal operation. The cache can be invalidated explicitly via Invalidate() or will automatically expire after the TTL.

Thread Safety

The Detector is safe for concurrent use. All exported methods use appropriate locking to prevent data races.

Example Usage

detector := cass.NewDetector()
if detector.Check() == cass.StatusHealthy {
    // Safe to use cass for searching
    results := runCassSearch(query)
}

Silent Failure

This package is designed for silent degradation. When cass is not available, it returns StatusNotInstalled without logging errors or warnings. The consuming code should simply disable cass-dependent features.

Index

Constants

View Source
const (
	// Base scores by match type
	ScoreIDMention      = 100 // Definitive evidence
	ScoreExactKeyword   = 50  // Strong thematic link
	ScorePartialKeyword = 30  // Probable relation

	// Multipliers
	MultiplierSameWorkspace = 2.0 // Critical for relevance

	// Time decay bonuses
	BonusRecent24h = 20  // Session within 24 hours of bead activity
	BonusRecent7d  = 10  // Session within 7 days
	PenaltyOld30d  = -10 // Session older than 30 days

	// Thresholds
	MinScoreThreshold    = 25 // Below this, don't show session
	MaxSessionsReturned  = 3  // Top N sessions per bead
	MaxKeywordsExtracted = 5  // Keywords from title
)

Scoring constants - all values are tunable based on real-world usage.

View Source
const DefaultCacheTTL = 5 * time.Minute

DefaultCacheTTL is the default duration to cache detection results.

View Source
const DefaultHealthTimeout = 2 * time.Second

DefaultHealthTimeout is the default timeout for health check commands.

View Source
const DefaultResultCacheSize = 100

DefaultResultCacheSize is the default maximum number of cache entries.

View Source
const DefaultResultCacheTTL = 10 * time.Minute

DefaultResultCacheTTL is the default time-to-live for cache entries.

View Source
const DefaultSearchLimit = 10

DefaultSearchLimit is the default max number of results.

View Source
const DefaultSearchTimeout = 5 * time.Second

DefaultSearchTimeout is the default timeout for search operations.

View Source
const MaxConcurrentSearches = 2

MaxConcurrentSearches limits concurrent cass processes.

View Source
const MaxOutputSize = 1024 * 1024

MaxOutputSize is the max bytes to read from cass output (1MB).

Variables

This section is empty.

Functions

func ExtractKeywords

func ExtractKeywords(text string) []string

ExtractKeywords extracts meaningful search keywords from text. It removes stop words, short words, and limits to MaxKeywordsExtracted.

func FindBeadIDMentions

func FindBeadIDMentions(text string) []string

FindBeadIDMentions finds all bead ID mentions in text.

func WorkspaceFromBeadsPath

func WorkspaceFromBeadsPath(beadsPath string) string

WorkspaceFromBeadsPath extracts the workspace directory from a beads.jsonl path.

Types

type Cache

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

Cache provides an LRU cache for cass correlation results. It is safe for concurrent use.

func NewCache

func NewCache() *Cache

NewCache creates a new Cache with default settings.

func NewCacheWithOptions

func NewCacheWithOptions(opts ...CacheOption) *Cache

NewCacheWithOptions creates a Cache with custom options.

func (*Cache) Clear

func (c *Cache) Clear()

Clear removes all entries from the cache.

func (*Cache) Get

func (c *Cache) Get(beadID string) *CorrelationHint

Get retrieves a cached hint by bead ID. Returns nil if not found or expired. This is an O(1) operation.

func (*Cache) Invalidate

func (c *Cache) Invalidate(beadID string)

Invalidate removes a specific entry from the cache.

func (*Cache) Len

func (c *Cache) Len() int

Len returns the number of entries (alias for Size for list.List compatibility).

func (*Cache) Set

func (c *Cache) Set(beadID string, hint *CorrelationHint)

Set stores a correlation hint in the cache. If the cache is full, it evicts expired entries first, then LRU. O(1) when no eviction needed; O(n) worst case when eviction scans for expired entries.

func (*Cache) Size

func (c *Cache) Size() int

Size returns the current number of cached entries.

func (*Cache) Stats

func (c *Cache) Stats() CacheStats

Stats returns current cache statistics.

type CacheEntry

type CacheEntry struct {
	Hint      *CorrelationHint
	Key       string
	CachedAt  time.Time
	ExpiresAt time.Time
}

CacheEntry wraps a cached hint with timing metadata.

type CacheOption

type CacheOption func(*Cache)

CacheOption configures a Cache.

func WithResultCacheSize

func WithResultCacheSize(size int) CacheOption

WithResultCacheSize sets the maximum cache size.

func WithResultCacheTTL

func WithResultCacheTTL(ttl time.Duration) CacheOption

WithResultCacheTTL sets the cache entry TTL.

type CacheStats

type CacheStats struct {
	Size      int           // Current number of entries
	MaxSize   int           // Maximum capacity
	Hits      int64         // Total cache hits
	Misses    int64         // Total cache misses
	Evictions int64         // Total evictions (TTL + LRU)
	TTL       time.Duration // Current TTL setting
}

CacheStats contains cache statistics for monitoring.

type CorrelationHint

type CorrelationHint struct {
	BeadID      string         // The bead this hint is for
	Results     []SearchResult // Correlated search results
	QueryUsed   string         // The query that produced these results
	ResultCount int            // Total results (may be > len(Results) if truncated)
}

CorrelationHint represents cached correlation data for a bead. This will be extended when the correlation engine is implemented.

type CorrelationResult

type CorrelationResult struct {
	BeadID        string              // Which bead this is for
	TopSessions   []ScoredResult      // Up to MaxSessionsReturned best matches
	TotalFound    int                 // Total results before filtering
	Strategy      CorrelationStrategy // Primary strategy that produced results
	Keywords      []string            // Keywords used (for display)
	ComputeTimeMs int                 // Time spent computing correlation
}

CorrelationResult contains the full correlation output for a bead.

type CorrelationStrategy

type CorrelationStrategy string

CorrelationStrategy identifies which strategy produced a correlation.

const (
	StrategyIDMention CorrelationStrategy = "id_mention"
	StrategyKeywords  CorrelationStrategy = "keywords"
	StrategyTimestamp CorrelationStrategy = "timestamp"
	StrategyCombined  CorrelationStrategy = "combined"
)

type Correlator

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

Correlator intelligently matches cass sessions to beads using multiple strategies.

func NewCorrelator

func NewCorrelator(searcher *Searcher, cache *Cache, workspace string) *Correlator

NewCorrelator creates a new Correlator with the given dependencies.

func NewCorrelatorWithOptions

func NewCorrelatorWithOptions(searcher *Searcher, cache *Cache, opts ...CorrelatorOption) *Correlator

NewCorrelatorWithOptions creates a Correlator with custom options.

func (*Correlator) Correlate

func (c *Correlator) Correlate(ctx context.Context, issue *model.Issue) CorrelationResult

Correlate finds sessions relevant to the given bead. It tries multiple strategies in order of confidence: 1. ID mention (highest confidence) 2. Keyword extraction (medium confidence) 3. Timestamp proximity (lower confidence)

func (*Correlator) GetCached

func (c *Correlator) GetCached(beadID string) *CorrelationHint

GetCached returns the cached correlation hint for a bead without triggering a new search. Returns nil if not cached or expired. This is useful for status bar indicators where we don't want to block on network/process calls.

type CorrelatorOption

type CorrelatorOption func(*Correlator)

CorrelatorOption configures a Correlator.

func WithWorkspace

func WithWorkspace(path string) CorrelatorOption

WithWorkspace sets the workspace path for filtering.

type Detector

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

Detector checks if cass is installed and operational. It caches results and is safe for concurrent use.

func NewDetector

func NewDetector() *Detector

NewDetector creates a new Detector with default settings.

func NewDetectorWithOptions

func NewDetectorWithOptions(opts ...Option) *Detector

NewDetectorWithOptions creates a new Detector with custom options.

func (*Detector) CacheValid

func (d *Detector) CacheValid() bool

CacheValid returns true if the cached result is still valid.

func (*Detector) Check

func (d *Detector) Check() Status

Check performs detection and returns the current status. Results are cached for cacheTTL duration. This method is safe for concurrent use.

func (*Detector) CheckedAt

func (d *Detector) CheckedAt() time.Time

CheckedAt returns when the last check was performed. Returns zero time if never checked.

func (*Detector) Invalidate

func (d *Detector) Invalidate()

Invalidate clears the cached status, forcing a fresh check on next Check() call.

func (*Detector) IsHealthy

func (d *Detector) IsHealthy() bool

IsHealthy returns true if cass is ready to use. This is a convenience method that checks the cached status.

func (*Detector) Status

func (d *Detector) Status() Status

Status returns the current cached status. If the cache is stale or unknown, returns StatusUnknown. Use Check() to perform an actual detection.

type Option

type Option func(*Detector)

Option configures a Detector.

func WithCacheTTL

func WithCacheTTL(ttl time.Duration) Option

WithCacheTTL sets the cache time-to-live.

func WithHealthTimeout

func WithHealthTimeout(timeout time.Duration) Option

WithHealthTimeout sets the health check timeout.

type ScoredResult

type ScoredResult struct {
	SearchResult
	FinalScore float64             // Combined score after all adjustments
	BaseScore  float64             // Score before multipliers
	Strategy   CorrelationStrategy // Which strategy matched
	Keywords   []string            // Keywords that matched (if strategy = keywords)
}

ScoredResult wraps a SearchResult with correlation scoring metadata.

type SearchMeta

type SearchMeta struct {
	ElapsedMs int    `json:"elapsed_ms"`
	Total     int    `json:"total"`
	Truncated bool   `json:"truncated"`
	Error     string `json:"error,omitempty"` // Non-empty if partial failure
}

SearchMeta contains metadata about the search operation.

type SearchOptions

type SearchOptions struct {
	Query     string        // Required: search query
	Limit     int           // Max results (default 10)
	Days      int           // Time filter (0 = no filter)
	Workspace string        // Filter by workspace path
	Fields    string        // "minimal", "summary", or field list
	Timeout   time.Duration // Override default timeout
}

SearchOptions configures a cass search operation.

type SearchResponse

type SearchResponse struct {
	Results []SearchResult `json:"results"`
	Meta    SearchMeta     `json:"meta"`
}

SearchResponse contains results and metadata from a cass search.

type SearchResult

type SearchResult struct {
	SourcePath string    `json:"source_path"` // Path to session file
	LineNumber int       `json:"line_number"` // Line in session
	Agent      string    `json:"agent"`       // "claude", "cursor", etc.
	Title      string    `json:"title"`       // Conversation title
	Score      float64   `json:"score"`       // Relevance score (0-1)
	Snippet    string    `json:"snippet"`     // Content preview
	Timestamp  time.Time `json:"timestamp"`   // When the message occurred
	MatchType  string    `json:"match_type"`  // "exact", "prefix", "fuzzy"
}

SearchResult represents a single search hit from cass.

type Searcher

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

Searcher executes cass searches with safety wrappers. It enforces timeouts, limits concurrent processes, and handles errors gracefully.

func NewSearcher

func NewSearcher(detector *Detector) *Searcher

NewSearcher creates a new Searcher that uses the provided detector.

func NewSearcherWithOptions

func NewSearcherWithOptions(detector *Detector, opts ...SearcherOption) *Searcher

NewSearcherWithOptions creates a Searcher with custom options.

func (*Searcher) Search

func (s *Searcher) Search(ctx context.Context, opts SearchOptions) SearchResponse

Search executes a cass search with the given options. It returns an empty response (not error) on any failure - errors are logged internally. This method is safe for concurrent use.

func (*Searcher) SearchInWorkspace

func (s *Searcher) SearchInWorkspace(ctx context.Context, query, workspace string) SearchResponse

SearchInWorkspace searches within a specific workspace directory.

func (*Searcher) SearchWithQuery

func (s *Searcher) SearchWithQuery(ctx context.Context, query string) SearchResponse

SearchWithQuery is a convenience method for simple searches.

type SearcherOption

type SearcherOption func(*Searcher)

SearcherOption configures a Searcher.

func WithSearchTimeout

func WithSearchTimeout(timeout time.Duration) SearcherOption

WithSearchTimeout sets the default search timeout.

type Status

type Status int

Status represents the availability state of cass.

const (
	// StatusUnknown indicates detection hasn't been performed yet.
	StatusUnknown Status = iota
	// StatusNotInstalled indicates cass binary is not found in PATH or is not executable.
	StatusNotInstalled
	// StatusNeedsIndex indicates cass is installed but needs indexing before use.
	StatusNeedsIndex
	// StatusHealthy indicates cass is installed, indexed, and ready for searches.
	StatusHealthy
)

func (Status) String

func (s Status) String() string

String returns a human-readable status description.

Jump to

Keyboard shortcuts

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