Documentation
¶
Overview ¶
Package code provides shared implementations for Code service RPCs.
Plugins call into this library instead of reimplementing common logic. Language-specific behavior (e.g. which fixers to run) stays in the plugin.
Package code provides shared, language-agnostic primitives for code operations.
Graph types (CodeNode, CodeGraph, Edge) are the universal representation of a codebase's structure. Language-specific parsers (parse_go.go, etc.) populate these types; Mind and plugins both consume them.
Package code provides the DefaultCodeServer: a complete, language-agnostic implementation of the unified Code.Execute RPC. Plugins embed it and override only language-specific operations (LSP, Fix, dependency management).
Index ¶
- func ComputeFileHashes(vfs VFS, dir string, extensions map[string]bool) map[string]string
- func DedentLines(lines []string) []string
- func FormatTimeline(timelines []*FileTimeline) string
- func FormatTimelineStats(s TimelineStats) string
- func Levenshtein(a, b string) int
- func OperationName(req *codev0.CodeRequest) string
- type ASTSymbolProvider
- type AgeBucket
- type ByteLRU
- type CachedVFS
- func (c *CachedVFS) Close() error
- func (c *CachedVFS) Invalidate() error
- func (c *CachedVFS) MkdirAll(path string, perm os.FileMode) error
- func (c *CachedVFS) ReadDir(path string) ([]os.DirEntry, error)
- func (c *CachedVFS) ReadFile(path string) ([]byte, error)
- func (c *CachedVFS) Remove(path string) error
- func (c *CachedVFS) Rename(oldpath, newpath string) error
- func (c *CachedVFS) Stat(path string) (os.FileInfo, error)
- func (c *CachedVFS) WalkDir(root string, fn fs.WalkDirFunc) error
- func (c *CachedVFS) WriteFile(path string, data []byte, perm os.FileMode) error
- type CodeExecutor
- type CodeGraph
- func (g *CodeGraph) AddEdge(e Edge)
- func (g *CodeGraph) AddNode(n *CodeNode)
- func (g *CodeGraph) Files() []string
- func (g *CodeGraph) FindDefinitions(name string) []*CodeNode
- func (g *CodeGraph) FindDefinitionsByKind(name string, kind NodeKind) []*CodeNode
- func (g *CodeGraph) FindUsages(name string) []*CodeNode
- func (g *CodeGraph) FunctionNodes() []*CodeNode
- func (g *CodeGraph) GetCallees(nodeID string) []string
- func (g *CodeGraph) GetCallers(nodeID string) []string
- func (g *CodeGraph) GetCallersOfAny(nodeIDs []string) []string
- func (g *CodeGraph) GetNeighborhood(nodeID string) *Neighborhood
- func (g *CodeGraph) GetNodesForFile(file string) []string
- func (g *CodeGraph) GetSameFile(nodeID string) []string
- func (g *CodeGraph) NameIndexSize() int
- func (g *CodeGraph) RebuildIndexes()
- func (g *CodeGraph) RemoveNode(nodeID string)
- func (g *CodeGraph) RemoveNodesForFile(file string) []string
- func (g *CodeGraph) ResolveIDs(ids []string) []*CodeNode
- func (g *CodeGraph) SearchSymbols(query string) []*CodeNode
- func (g *CodeGraph) Stats() GraphStats
- func (g *CodeGraph) SummaryableNodes() []*CodeNode
- type CodeMap
- type CodeMapStats
- type CodeNode
- type CodebaseContext
- type DefaultCodeServer
- func (s *DefaultCodeServer) Close() error
- func (s *DefaultCodeServer) Execute(ctx context.Context, req *codev0.CodeRequest) (*codev0.CodeResponse, error)
- func (s *DefaultCodeServer) FileOps() FileOperation
- func (s *DefaultCodeServer) GetSourceDir() string
- func (s *DefaultCodeServer) GetVFS() VFS
- func (s *DefaultCodeServer) Override(op string, handler OperationHandler)
- func (s *DefaultCodeServer) SetWriteListener(l WriteListener)
- type DepEdge
- type DepGraph
- type DiffKind
- type DiffLine
- type Edge
- type EdgeKind
- type EditResult
- type FileChange
- type FileDiff
- type FileMap
- type FileOperation
- type FileTimeline
- type GitBlameLine
- type GitCommitInfo
- type GitDiffFileInfo
- type GoCodeServer
- func (s *GoCodeServer) GetProjectInfo(ctx context.Context, req *codev0.GetProjectInfoRequest) (*codev0.GetProjectInfoResponse, error)
- func (s *GoCodeServer) ListDependencies(ctx context.Context, req *codev0.ListDependenciesRequest) (*codev0.ListDependenciesResponse, error)
- func (s *GoCodeServer) ListSymbols(ctx context.Context, req *codev0.ListSymbolsRequest) (*codev0.ListSymbolsResponse, error)
- func (s *GoCodeServer) VFS() VFS
- type GoServerOption
- type GraphStats
- type HotspotFile
- type Hunk
- type LocalVFS
- func (LocalVFS) MkdirAll(path string, perm os.FileMode) error
- func (LocalVFS) ReadDir(path string) ([]os.DirEntry, error)
- func (LocalVFS) ReadFile(path string) ([]byte, error)
- func (LocalVFS) Remove(path string) error
- func (LocalVFS) Rename(oldpath, newpath string) error
- func (LocalVFS) Stat(path string) (os.FileInfo, error)
- func (LocalVFS) WalkDir(root string, fn fs.WalkDirFunc) error
- func (LocalVFS) WriteFile(path string, data []byte, perm os.FileMode) error
- type MemoryVFS
- func (m *MemoryVFS) MkdirAll(path string, _ os.FileMode) error
- func (m *MemoryVFS) ReadDir(path string) ([]os.DirEntry, error)
- func (m *MemoryVFS) ReadFile(path string) ([]byte, error)
- func (m *MemoryVFS) Remove(path string) error
- func (m *MemoryVFS) Rename(oldpath, newpath string) error
- func (m *MemoryVFS) Stat(path string) (os.FileInfo, error)
- func (m *MemoryVFS) WalkDir(root string, fn fs.WalkDirFunc) error
- func (m *MemoryVFS) WriteFile(path string, data []byte, _ os.FileMode) error
- type NativeGit
- func (g *NativeGit) DiffStat(ctx context.Context, baseRef, headRef string) ([]*GitDiffFileInfo, error)
- func (g *NativeGit) HEAD() (string, error)
- func (g *NativeGit) ListBranches() ([]string, error)
- func (g *NativeGit) Log(ctx context.Context, maxCount int, ref, path, since string) ([]*GitCommitInfo, error)
- func (g *NativeGit) Show(ctx context.Context, ref, path string) (string, bool, error)
- type NativeJJ
- func (j *NativeJJ) Blame(ctx context.Context, path string, startLine, endLine int32) ([]*GitBlameLine, error)
- func (j *NativeJJ) Diff(ctx context.Context, baseRef, headRef, path string, contextLines int, ...) (string, []*GitDiffFileInfo, error)
- func (j *NativeJJ) Log(ctx context.Context, maxCount int, ref, path, since string) ([]*GitCommitInfo, error)
- func (j *NativeJJ) Show(ctx context.Context, ref, path string) (string, bool, error)
- type Neighborhood
- type NodeKind
- type OperationHandler
- type OverlayVFS
- func (o *OverlayVFS) Base() VFS
- func (o *OverlayVFS) BaseSnapshot(path string) ([]byte, bool)
- func (o *OverlayVFS) Commit() error
- func (o *OverlayVFS) DeletedFiles() []string
- func (o *OverlayVFS) Diff() []FileChange
- func (o *OverlayVFS) Dirty() bool
- func (o *OverlayVFS) MkdirAll(path string, perm os.FileMode) error
- func (o *OverlayVFS) ModifiedFiles() []string
- func (o *OverlayVFS) ReadDir(path string) ([]os.DirEntry, error)
- func (o *OverlayVFS) ReadFile(path string) ([]byte, error)
- func (o *OverlayVFS) Remove(path string) error
- func (o *OverlayVFS) Rename(oldpath, newpath string) error
- func (o *OverlayVFS) Rollback()
- func (o *OverlayVFS) Stat(path string) (os.FileInfo, error)
- func (o *OverlayVFS) WalkDir(root string, fn fs.WalkDirFunc) error
- func (o *OverlayVFS) WriteFile(path string, data []byte, perm os.FileMode) error
- type PackageInput
- type PackageNode
- type PythonASTSymbolProvider
- type PythonCodeServer
- func (s *PythonCodeServer) GetProjectInfo(ctx context.Context, req *codev0.GetProjectInfoRequest) (*codev0.GetProjectInfoResponse, error)
- func (s *PythonCodeServer) ListDependencies(ctx context.Context, req *codev0.ListDependenciesRequest) (*codev0.ListDependenciesResponse, error)
- func (s *PythonCodeServer) ListSymbols(ctx context.Context, req *codev0.ListSymbolsRequest) (*codev0.ListSymbolsResponse, error)
- type PythonServerOption
- type RelevanceScorer
- type ScoredFile
- type ScorerOption
- type SearchMatch
- type SearchOpts
- type SearchResult
- func Search(ctx context.Context, root string, opts SearchOpts) (*SearchResult, error)
- func SearchTrigram(_ context.Context, vfs VFS, idx *TrigramIndex, root string, opts SearchOpts) (*SearchResult, error)
- func SearchVFS(_ context.Context, vfs VFS, root string, opts SearchOpts) (*SearchResult, error)
- type ServerOption
- type SymbolEntry
- type SymbolInput
- type SymbolProvider
- type TSASTSymbolProvider
- type TimelineChunk
- type TimelineStats
- type TrigramIndex
- type VCSProvider
- type VFS
- type VFSProvider
- type WriteListener
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ComputeFileHashes ¶
ComputeFileHashes walks a directory and hashes source files. If extensions is nil, all files are included. Otherwise only matching extensions. Files larger than maxHashFileSize are skipped. Shared by DefaultCodeServer and language-specific servers.
func DedentLines ¶
DedentLines strips the minimum common leading whitespace from all non-empty lines.
func FormatTimeline ¶
func FormatTimeline(timelines []*FileTimeline) string
FormatTimeline produces a compact text representation of file timelines, suitable for LLM context or developer review.
func FormatTimelineStats ¶
func FormatTimelineStats(s TimelineStats) string
FormatTimelineStats produces a readable summary.
func Levenshtein ¶
Levenshtein computes the edit distance between two strings.
func OperationName ¶
func OperationName(req *codev0.CodeRequest) string
OperationName returns the oneof field name for dispatch/override keys. This is the SINGLE source of truth for operation name mapping. If you add a new operation to the proto, add it here AND in dispatch(). The test TestOperationName_MatchesDispatch verifies they stay in sync.
Types ¶
type ASTSymbolProvider ¶
type ASTSymbolProvider struct {
// contains filtered or unexported fields
}
ASTSymbolProvider uses ParseGoTreeVFS to extract symbols from Go AST. Zero external dependencies, millisecond performance, works anywhere Go is installed. Tradeoff: no cross-module type resolution.
func NewASTSymbolProvider ¶
func NewASTSymbolProvider(dir string) *ASTSymbolProvider
NewASTSymbolProvider creates a provider that lazily parses the Go source tree. Uses LocalVFS by default; callers can override vfs for non-local filesystems.
func NewASTSymbolProviderVFS ¶
func NewASTSymbolProviderVFS(dir string, vfs VFS) *ASTSymbolProvider
NewASTSymbolProviderVFS creates a provider backed by the given VFS.
func (*ASTSymbolProvider) Graph ¶
func (p *ASTSymbolProvider) Graph() (*CodeGraph, error)
Graph returns the underlying CodeGraph for callers that need it.
func (*ASTSymbolProvider) ListSymbols ¶
ListSymbols returns proto Symbol messages for a specific file or all files (if file is empty).
type ByteLRU ¶
type ByteLRU struct {
// MaxEntrySize is the maximum size of a single entry (default 1MB).
// Files larger than this are not cached.
MaxEntrySize int64
// contains filtered or unexported fields
}
ByteLRU is a byte-slice LRU cache with a configurable memory budget. Thread-safe. Used by CachedVFS to cache file contents in RAM.
func NewByteLRU ¶
NewByteLRU creates a new LRU cache with the given capacity in bytes.
func (*ByteLRU) Get ¶
Get returns the cached data for key, or nil if not present. Moves the entry to the front (most recently used).
func (*ByteLRU) Invalidate ¶
Invalidate removes a key from the cache.
type CachedVFS ¶
type CachedVFS struct {
// contains filtered or unexported fields
}
CachedVFS wraps a base VFS (typically LocalVFS) with an in-memory file tree cache. Metadata operations (Stat, ReadDir, WalkDir) are served from cache. Reads/writes pass through to the base and update the cache.
On startup, the entire source directory is walked to build the cache. A fsnotify watcher keeps the cache fresh on file changes.
func NewCachedVFS ¶
NewCachedVFS creates a CachedVFS rooted at dir, backed by base. It walks dir to populate the cache and starts a background fsnotify watcher.
func (*CachedVFS) Invalidate ¶
Invalidate forces a full re-scan of the tree. Use sparingly.
type CodeExecutor ¶
type CodeExecutor interface {
Execute(context.Context, *codev0.CodeRequest) (*codev0.CodeResponse, error)
}
CodeExecutor is the interface every code server (Default, Go, …) satisfies.
type CodeGraph ¶
type CodeGraph struct {
Nodes map[string]*CodeNode // node ID → node
Edges []Edge // all directed edges
// contains filtered or unexported fields
}
CodeGraph holds the full structural representation of a codebase.
func ParseGoTree ¶
ParseGoTree parses a Go source tree and builds a CodeGraph using the local filesystem. For VFS-backed parsing, use ParseGoTreeVFS.
func ParseGoTreeVFS ¶
ParseGoTreeVFS parses a Go source tree through a VFS and builds a CodeGraph. It extracts functions, methods, types, file nodes, imports, and call edges.
func (*CodeGraph) AddNode ¶
AddNode inserts or replaces a node and updates the file and name indexes.
func (*CodeGraph) FindDefinitions ¶
FindDefinitions returns all nodes whose name matches (case-insensitive). O(1) lookup via the nameIdx — no linear scan of all nodes.
func (*CodeGraph) FindDefinitionsByKind ¶
FindDefinitionsByKind returns nodes matching both name and kind.
func (*CodeGraph) FindUsages ¶
FindUsages returns all callers of any node matching the given name. "Where is X used?" — finds definitions of X, then returns their callers.
func (*CodeGraph) FunctionNodes ¶
FunctionNodes returns all nodes of kind Function or Method.
func (*CodeGraph) GetCallees ¶
GetCallees returns IDs of nodes that the given node calls.
func (*CodeGraph) GetCallers ¶
GetCallers returns IDs of nodes that call the given node.
func (*CodeGraph) GetCallersOfAny ¶
GetCallersOfAny returns the union of callers for a set of node IDs. Deduplicates and excludes IDs in the input set.
func (*CodeGraph) GetNeighborhood ¶
func (g *CodeGraph) GetNeighborhood(nodeID string) *Neighborhood
GetNeighborhood returns the structural neighborhood of a node.
func (*CodeGraph) GetNodesForFile ¶
GetNodesForFile returns all node IDs belonging to a specific file.
func (*CodeGraph) GetSameFile ¶
GetSameFile returns IDs of all nodes in the same file as the given node.
func (*CodeGraph) NameIndexSize ¶
NameIndexSize returns the number of unique names in the symbol index.
func (*CodeGraph) RebuildIndexes ¶
func (g *CodeGraph) RebuildIndexes()
RebuildIndexes recomputes all indexes from raw Nodes and Edges. Call after deserializing from storage.
func (*CodeGraph) RemoveNode ¶
RemoveNode deletes a node and all its edges.
func (*CodeGraph) RemoveNodesForFile ¶
RemoveNodesForFile removes all nodes associated with a file. Returns the removed IDs.
func (*CodeGraph) ResolveIDs ¶
ResolveIDs maps node IDs to CodeNode pointers, skipping unknowns.
func (*CodeGraph) SearchSymbols ¶
SearchSymbols returns all nodes whose name contains the query (case-insensitive). Uses the nameIdx for prefix filtering — much faster than scanning all nodes when the index has many entries.
func (*CodeGraph) SummaryableNodes ¶
SummaryableNodes returns all nodes worth generating summaries for (functions, methods, types, files — everything except packages).
type CodeMap ¶
CodeMap is a structured representation of all symbols in a codebase, organized by file and hierarchy. This is used by Mind to give the LLM a compressed overview of the project's code structure.
func BuildCodeMap ¶
func BuildCodeMap(language string, symbols []SymbolInput) *CodeMap
BuildCodeMap groups symbols by file and sorts them by line number.
func (*CodeMap) Format ¶
Format produces a compact text representation suitable for LLM system prompts. It uses ~1 line per symbol to stay within context budgets.
func (*CodeMap) Stats ¶
func (cm *CodeMap) Stats() CodeMapStats
Stats returns summary statistics about the code map.
type CodeMapStats ¶
type CodeNode ¶
type CodeNode struct {
ID string // unique: "pkg/api/router.go::SetupRoutes"
Kind NodeKind // function, method, type, file, package
Name string // short name: "SetupRoutes"
File string // relative path: "pkg/api/router.go"
Line int // starting line number
EndLine int // ending line number (0 if unknown)
Signature string // from AST/LSP: "func SetupRoutes(r chi.Router)"
Doc string // documentation comment, if any
Body string // source text of the node (for summary generation)
// Relationship IDs.
Children []string // functions/types contained in this file/package
Calls []string // outgoing: functions this node calls
CalledBy []string // incoming: functions that call this node
Imports []string // package paths imported by this file
}
CodeNode represents a single element in the code graph.
func (*CodeNode) QualifiedName ¶
QualifiedName returns "File::Name" for display.
type CodebaseContext ¶
type CodebaseContext struct {
Module string
Language string
Packages []*codev0.PackageInfo
CodeMap *CodeMap
DepGraph *DepGraph
Graph *CodeGraph
Timelines []*FileTimeline
Stats TimelineStats
}
CodebaseContext holds all analysis layers assembled from a single code server. It is the unified input for LLM prompts, relevance scoring, and edit planning.
func BuildCodebaseContext ¶
func BuildCodebaseContext(ctx context.Context, server CodeExecutor) (*CodebaseContext, error)
BuildCodebaseContext runs the full analysis pipeline through a CodeExecutor (typically GoCodeServer) and returns a populated CodebaseContext.
func (*CodebaseContext) FilePaths ¶
func (cc *CodebaseContext) FilePaths() []string
FilePaths returns all source file paths known to this context.
func (*CodebaseContext) Format ¶
func (cc *CodebaseContext) Format(budget int) string
Format produces a token-budgeted text representation for LLM system prompts. Budget is in bytes; 0 means unlimited. Sections are included in priority order: header > code map > dep graph > timeline > call graph.
type DefaultCodeServer ¶
type DefaultCodeServer struct {
codev0.UnimplementedCodeServer
SourceDir string
FS VFS
// contains filtered or unexported fields
}
DefaultCodeServer implements every Code.Execute operation with sensible, language-agnostic defaults. Plugins embed this and call Override to replace handlers for operations they specialize (e.g. Fix, ListSymbols, deps).
func NewDefaultCodeServer ¶
func NewDefaultCodeServer(sourceDir string, opts ...ServerOption) *DefaultCodeServer
NewDefaultCodeServer creates a server rooted at sourceDir. By default it uses LocalVFS (direct os.* calls).
func (*DefaultCodeServer) Close ¶
func (s *DefaultCodeServer) Close() error
Close releases resources held by the server (e.g. CachedVFS watcher, git repo).
func (*DefaultCodeServer) Execute ¶
func (s *DefaultCodeServer) Execute(ctx context.Context, req *codev0.CodeRequest) (*codev0.CodeResponse, error)
Execute dispatches the incoming CodeRequest to the appropriate handler.
func (*DefaultCodeServer) FileOps ¶
func (s *DefaultCodeServer) FileOps() FileOperation
FileOps returns a FileOperation view over this server's VFS and root. Use it when only file operations (read, write, list, delete, move, copy, search, replace) are needed, so Search and ReplaceInFile always run on the virtual layer (e.g. overlay) instead of disk.
func (*DefaultCodeServer) GetSourceDir ¶
func (s *DefaultCodeServer) GetSourceDir() string
GetSourceDir returns the root directory for this server (implements VFSProvider).
func (*DefaultCodeServer) GetVFS ¶
func (s *DefaultCodeServer) GetVFS() VFS
GetVFS returns the VFS backend used by this server (implements VFSProvider).
func (*DefaultCodeServer) Override ¶
func (s *DefaultCodeServer) Override(op string, handler OperationHandler)
Override registers a custom handler for an operation name. Names match the oneof field names: "read_file", "write_file", "fix", etc.
func (*DefaultCodeServer) SetWriteListener ¶
func (s *DefaultCodeServer) SetWriteListener(l WriteListener)
SetWriteListener installs a post-mutation hook. It is called after every successful WriteFile, CreateFile, DeleteFile, and MoveFile dispatched through Execute. Language plugins wire their LSP's textDocument/didChange through this so the LSP's in-memory view stays in sync with disk without waiting for the filesystem watcher.
Safe to call after construction; nil clears the listener. The listener is invoked synchronously after the mutation commits; if you need async fire-and-forget, do the dispatch inside your own listener.
type DepGraph ¶
type DepGraph struct {
Module string
Packages []PackageNode
}
DepGraph represents the package dependency graph of a project. Nodes are packages; edges are import relationships.
func BuildDepGraph ¶
func BuildDepGraph(module string, packages []PackageInput) *DepGraph
BuildDepGraph creates a DepGraph from raw package data.
func (*DepGraph) ConnectedComponents ¶
ConnectedComponents returns groups of packages that are connected via internal imports (undirected). Packages in different components have no import relationship and can be worked on independently.
func (*DepGraph) InternalEdges ¶
InternalEdges returns only edges between packages within the same module.
type DiffKind ¶
type DiffKind int
DiffKind describes whether a line was added, removed, or unchanged.
type DiffLine ¶
type DiffLine struct {
Kind DiffKind
Content string
OldLine int // 0 if the line doesn't exist in the old file
NewLine int // 0 if the line doesn't exist in the new file
}
DiffLine is a single line within a hunk.
type Edge ¶
type Edge struct {
From string // source node ID
To string // target node ID
Kind EdgeKind // relationship type
}
Edge represents a directed relationship between two nodes.
type EditResult ¶
type EditResult struct {
Content string // the file after replacement
Strategy string // which strategy matched
OK bool
}
EditResult holds the outcome of a smart edit attempt.
func SmartEdit ¶
func SmartEdit(content, find, replace string) EditResult
SmartEdit tries all matching strategies to apply a FIND/REPLACE on content. Strategies are tried in order of decreasing precision:
- Exact substring match
- Trailing whitespace normalized
- Fully trimmed (all leading+trailing whitespace per line)
- Indentation-shifted (same content, different indent level)
- Anchor-based (first+last unique lines locate the region)
- Fuzzy scored (Levenshtein per line)
- Fuzzy block (60% line match threshold)
type FileChange ¶
type FileChange struct {
Path string
Type string // "create", "modify", "delete"
Content []byte // nil for deletes
}
FileChange records a single file mutation in the overlay.
type FileDiff ¶
FileDiff represents the structured diff of a single file.
func ParseUnifiedDiff ¶
ParseUnifiedDiff parses the output of `git diff` (unified format) into structured FileDiff objects with line numbers on every line.
type FileMap ¶
type FileMap struct {
Path string
Symbols []SymbolEntry
}
FileMap represents the symbols in a single file.
type FileOperation ¶
type FileOperation interface {
ReadFile(ctx context.Context, path string) ([]byte, error)
WriteFile(ctx context.Context, path string, data []byte) error
ListFiles(ctx context.Context, path string, recursive bool, extensions []string) ([]string, error)
DeleteFile(ctx context.Context, path string) error
MoveFile(ctx context.Context, oldPath, newPath string) error
CopyFile(ctx context.Context, srcPath, destPath string) error
Search(ctx context.Context, opts SearchOpts) (*SearchResult, error)
ReplaceInFile(ctx context.Context, path, find, replace string) (changed bool, err error)
}
FileOperation provides VFS-only operations. All paths are relative to the root passed at construction. Search and ReplaceInFile run on the VFS (no ripgrep on disk), so overlay/virtual state is consistent.
func NewFileOps ¶
func NewFileOps(vfs VFS, root string) FileOperation
NewFileOps returns a FileOperation that uses vfs with all paths under root. Paths passed to its methods must be relative to root (e.g. "foo/bar.go").
type FileTimeline ¶
type FileTimeline struct {
Path string
Chunks []TimelineChunk
}
FileTimeline is the temporal breakdown of a single source file.
func BuildFileTimeline ¶
func BuildFileTimeline(path string, blameLines []*codev0.GitBlameLine, refDate time.Time) *FileTimeline
BuildFileTimeline groups blame lines into consecutive chunks by commit hash, classifies each by age relative to refDate, and extracts a summary.
func BuildProjectTimeline ¶
func BuildProjectTimeline(ctx context.Context, vfs VFS, rootDir string, extensions []string, refDate time.Time) ([]*FileTimeline, error)
BuildProjectTimeline blames every source file and returns timelines sorted by path. It uses the VFS to discover files, skipping test files, vendor, and generated directories, then runs git blame directly via exec.Command.
func (*FileTimeline) Lines ¶
func (ft *FileTimeline) Lines() int
Lines returns total line count (EndLine of last chunk).
func (*FileTimeline) Newest ¶
func (ft *FileTimeline) Newest() time.Time
Newest returns the most recent chunk date, or zero time if empty.
func (*FileTimeline) Oldest ¶
func (ft *FileTimeline) Oldest() time.Time
Oldest returns the earliest chunk date, or zero time if empty.
type GitBlameLine ¶
GitBlameLine holds blame information for a single line.
type GitCommitInfo ¶
type GitCommitInfo struct {
Hash string
ShortHash string
Author string
Date string
Message string
FilesChanged int32
}
GitCommitInfo holds parsed commit data (used by both native and exec paths).
type GitDiffFileInfo ¶
GitDiffFileInfo holds per-file diff statistics.
type GoCodeServer ¶
type GoCodeServer struct {
*DefaultCodeServer
// contains filtered or unexported fields
}
GoCodeServer extends DefaultCodeServer with Go-specific operations: ListSymbols (via pluggable SymbolProvider), GetProjectInfo (go list), and ListDependencies (go list -m). It provides the same data as the go-generic agent but without requiring Docker or gopls.
func NewGoCodeServer ¶
func NewGoCodeServer(dir string, serverOpts []ServerOption, goOpts ...GoServerOption) *GoCodeServer
NewGoCodeServer creates a Go-aware code server. By default it uses ASTSymbolProvider (ParseGoTree) for symbols. Pass WithSymbolProvider() to use LSP or any other implementation. ServerOptions are forwarded to the embedded DefaultCodeServer (e.g. WithVFS).
func (*GoCodeServer) GetProjectInfo ¶
func (s *GoCodeServer) GetProjectInfo(ctx context.Context, req *codev0.GetProjectInfoRequest) (*codev0.GetProjectInfoResponse, error)
GetProjectInfo implements the standalone gRPC RPC (not through Execute).
func (*GoCodeServer) ListDependencies ¶
func (s *GoCodeServer) ListDependencies(ctx context.Context, req *codev0.ListDependenciesRequest) (*codev0.ListDependenciesResponse, error)
ListDependencies implements the standalone gRPC RPC.
func (*GoCodeServer) ListSymbols ¶
func (s *GoCodeServer) ListSymbols(ctx context.Context, req *codev0.ListSymbolsRequest) (*codev0.ListSymbolsResponse, error)
ListSymbols implements the standalone gRPC RPC (not through Execute).
func (*GoCodeServer) VFS ¶
func (s *GoCodeServer) VFS() VFS
VFS returns the underlying VFS of the code server.
type GoServerOption ¶
type GoServerOption func(*GoCodeServer)
GoServerOption configures a GoCodeServer.
func WithSymbolProvider ¶
func WithSymbolProvider(sp SymbolProvider) GoServerOption
WithSymbolProvider overrides the default AST-based symbol provider. Use this to plug in an LSP-backed provider when gopls is available.
type GraphStats ¶
type GraphStats struct {
TotalNodes int
TotalEdges int
Functions int
Methods int
Types int
Files int
Packages int
}
GraphStats holds aggregate counts for a code graph.
func (GraphStats) String ¶
func (s GraphStats) String() string
type HotspotFile ¶
HotspotFile tracks files with many distinct commit chunks.
type Hunk ¶
type Hunk struct {
OldStart int // 1-based starting line in the old version
OldCount int
NewStart int // 1-based starting line in the new version
NewCount int
Header string // optional hunk header (function name, etc.)
Lines []DiffLine
}
Hunk is a contiguous block of changes within a file diff.
type LocalVFS ¶
type LocalVFS struct{}
LocalVFS delegates every call to the os/filepath standard library. This is the default for DefaultCodeServer -- zero behavior change from the original direct-os implementation.
type MemoryVFS ¶
type MemoryVFS struct {
// contains filtered or unexported fields
}
MemoryVFS is a pure in-memory filesystem. All paths are absolute. Safe for concurrent use.
func NewMemoryVFS ¶
func NewMemoryVFS() *MemoryVFS
NewMemoryVFS creates an empty in-memory filesystem.
func NewMemoryVFSFrom ¶
NewMemoryVFSFrom creates a MemoryVFS pre-populated with the given files. Keys are absolute paths, values are file contents.
type NativeGit ¶
type NativeGit struct {
// contains filtered or unexported fields
}
NativeGit wraps a go-git Repository for in-process git operations. Eliminates fork/exec overhead for common operations (log, show, diff). Falls back to exec for operations go-git doesn't support well (blame with line ranges).
func OpenNativeGit ¶
OpenNativeGit opens a git repository at dir. Returns nil (not error) if dir is not a git repo — callers should fall back to exec-based git.
func (*NativeGit) DiffStat ¶
func (g *NativeGit) DiffStat(ctx context.Context, baseRef, headRef string) ([]*GitDiffFileInfo, error)
DiffStat returns file-level diff statistics between two refs. For full unified diff output, fall back to exec (go-git's patch is verbose).
func (*NativeGit) ListBranches ¶
ListBranches returns all local branch names.
type NativeJJ ¶
type NativeJJ struct {
// contains filtered or unexported fields
}
NativeJJ implements VCSProvider for Jujutsu (jj) repositories. All operations go through the jj CLI — there is no Go library for jj.
func OpenNativeJJ ¶
OpenNativeJJ returns a NativeJJ if dir contains a .jj directory and jj is installed. Returns nil if jj is not available or dir is not a jj repo.
type Neighborhood ¶
type Neighborhood struct {
Node *CodeNode
Callers []*CodeNode
Callees []*CodeNode
SameFile []*CodeNode
}
Neighborhood captures the structural context around a node.
type OperationHandler ¶
type OperationHandler func(ctx context.Context, req *codev0.CodeRequest) (*codev0.CodeResponse, error)
OperationHandler processes a single code operation within Execute.
type OverlayVFS ¶
type OverlayVFS struct {
// contains filtered or unexported fields
}
OverlayVFS layers in-memory writes/deletes on top of a base VFS. Reads check the overlay first, then fall through to the base. Writes never touch the base until Commit() is called.
func NewOverlayVFS ¶
func NewOverlayVFS(base VFS) *OverlayVFS
NewOverlayVFS wraps an existing VFS with an in-memory overlay.
func (*OverlayVFS) BaseSnapshot ¶
func (o *OverlayVFS) BaseSnapshot(path string) ([]byte, bool)
BaseSnapshot returns the base content captured when the overlay first touched a file. Returns nil, false if no snapshot exists.
func (*OverlayVFS) Commit ¶
func (o *OverlayVFS) Commit() error
Commit flushes all overlay writes to the base VFS and applies deletes.
func (*OverlayVFS) DeletedFiles ¶
func (o *OverlayVFS) DeletedFiles() []string
DeletedFiles returns the set of file paths that have pending deletes.
func (*OverlayVFS) Diff ¶
func (o *OverlayVFS) Diff() []FileChange
Diff returns a list of all file changes in the overlay.
func (*OverlayVFS) Dirty ¶
func (o *OverlayVFS) Dirty() bool
Dirty returns true if the overlay has any pending changes.
func (*OverlayVFS) ModifiedFiles ¶
func (o *OverlayVFS) ModifiedFiles() []string
ModifiedFiles returns the set of file paths that have pending writes.
func (*OverlayVFS) Remove ¶
func (o *OverlayVFS) Remove(path string) error
func (*OverlayVFS) Rename ¶
func (o *OverlayVFS) Rename(oldpath, newpath string) error
func (*OverlayVFS) Rollback ¶
func (o *OverlayVFS) Rollback()
Rollback discards all overlay changes.
func (*OverlayVFS) WalkDir ¶
func (o *OverlayVFS) WalkDir(root string, fn fs.WalkDirFunc) error
type PackageInput ¶
BuildDepGraph constructs a dependency graph from package info.
type PackageNode ¶
PackageNode represents one package in the dependency graph.
type PythonASTSymbolProvider ¶
type PythonASTSymbolProvider struct {
// contains filtered or unexported fields
}
PythonASTSymbolProvider extracts symbols from Python files using Python's ast module via a subprocess.
func NewPythonASTSymbolProvider ¶
func NewPythonASTSymbolProvider(sourceDir string) *PythonASTSymbolProvider
NewPythonASTSymbolProvider creates a provider that parses Python files.
func (*PythonASTSymbolProvider) Close ¶
func (p *PythonASTSymbolProvider) Close()
Close removes the temporary script file.
func (*PythonASTSymbolProvider) ListSymbols ¶
func (p *PythonASTSymbolProvider) ListSymbols(ctx context.Context, file string) ([]*codev0.Symbol, error)
ListSymbols extracts symbols from a file or the entire source directory.
type PythonCodeServer ¶
type PythonCodeServer struct {
*DefaultCodeServer
// contains filtered or unexported fields
}
PythonCodeServer extends DefaultCodeServer with Python-specific operations: GetProjectInfo (pyproject.toml + uv), ListDependencies (uv pip list), and ListSymbols (via pluggable SymbolProvider — AST or LSP).
func NewPythonCodeServer ¶
func NewPythonCodeServer(dir string, serverOpts []ServerOption, pyOpts ...PythonServerOption) *PythonCodeServer
NewPythonCodeServer creates a Python-aware code server.
func (*PythonCodeServer) GetProjectInfo ¶
func (s *PythonCodeServer) GetProjectInfo(ctx context.Context, req *codev0.GetProjectInfoRequest) (*codev0.GetProjectInfoResponse, error)
func (*PythonCodeServer) ListDependencies ¶
func (s *PythonCodeServer) ListDependencies(ctx context.Context, req *codev0.ListDependenciesRequest) (*codev0.ListDependenciesResponse, error)
func (*PythonCodeServer) ListSymbols ¶
func (s *PythonCodeServer) ListSymbols(ctx context.Context, req *codev0.ListSymbolsRequest) (*codev0.ListSymbolsResponse, error)
type PythonServerOption ¶
type PythonServerOption func(*PythonCodeServer)
PythonServerOption configures a PythonCodeServer.
func WithPythonSymbolProvider ¶
func WithPythonSymbolProvider(sp SymbolProvider) PythonServerOption
WithPythonSymbolProvider overrides the default symbol provider.
type RelevanceScorer ¶
type RelevanceScorer struct {
// contains filtered or unexported fields
}
RelevanceScorer ranks files by structural relevance to a text query. All signals are computed from data already available in CodebaseContext -- no embeddings or LLM calls required.
func NewRelevanceScorer ¶
func NewRelevanceScorer(cc *CodebaseContext, vfs VFS, rootDir string, opts ...ScorerOption) *RelevanceScorer
NewRelevanceScorer creates a scorer from a CodebaseContext and its backing server. vfs and rootDir are used for the search signal; pass a DefaultCodeServer's FS and SourceDir.
func (*RelevanceScorer) ScoreFiles ¶
func (r *RelevanceScorer) ScoreFiles(ctx context.Context, query string, files []string) []ScoredFile
ScoreFiles ranks the provided files by relevance to the query. Returns results sorted by descending score.
func (*RelevanceScorer) TopK ¶
func (r *RelevanceScorer) TopK(ctx context.Context, query string, files []string, k int) []ScoredFile
TopK returns the top K files from ScoreFiles.
type ScoredFile ¶
type ScoredFile struct {
Path string
Score float64
SearchHits int
SymbolHits int
Callers int
RecentLines int
Importers int
}
ScoredFile is a file path annotated with a composite relevance score.
type ScorerOption ¶
type ScorerOption func(*RelevanceScorer)
ScorerOption configures a RelevanceScorer.
func WithWeights ¶
func WithWeights(search, symbol, callGraph, recency, centrality float64) ScorerOption
WithWeights sets custom signal weights. Default: 0.35, 0.25, 0.15, 0.15, 0.10.
type SearchMatch ¶
SearchMatch is one search result.
type SearchOpts ¶
type SearchOpts struct {
Pattern string
Literal bool
CaseInsensitive bool
Path string // subdirectory (relative to root)
Extensions []string // e.g. [".go", ".py"]
Exclude []string // glob patterns
MaxResults int // 0 = 100
ContextLines int
}
SearchOpts configures a text search.
type SearchResult ¶
type SearchResult struct {
Matches []SearchMatch
Truncated bool
}
SearchResult holds all matches.
func Search ¶
func Search(ctx context.Context, root string, opts SearchOpts) (*SearchResult, error)
Search runs ripgrep on a local directory.
func SearchTrigram ¶
func SearchTrigram(_ context.Context, vfs VFS, idx *TrigramIndex, root string, opts SearchOpts) (*SearchResult, error)
SearchTrigram performs trigram-accelerated search. The index narrows candidates to files containing the query's trigrams, then regex matches only those files. Falls back to SearchVFS if trigrams can't be extracted (e.g., pure wildcard pattern).
func SearchVFS ¶
func SearchVFS(_ context.Context, vfs VFS, root string, opts SearchOpts) (*SearchResult, error)
SearchVFS performs regex-based text search over a VFS. Used when the filesystem is non-local (MemoryVFS, OverlayVFS) and ripgrep can't run.
type ServerOption ¶
type ServerOption func(*DefaultCodeServer)
ServerOption configures a DefaultCodeServer.
func WithCachedFS ¶
func WithCachedFS() ServerOption
WithCachedFS enables in-memory file tree caching backed by fsnotify. Metadata operations (Stat, ReadDir, WalkDir) are served from cache. File reads/writes pass through to disk. Cache is kept fresh via fsnotify.
func WithContentCache ¶
func WithContentCache(budgetBytes int64) ServerOption
WithContentCache enables in-memory file content caching on top of CachedVFS. File reads are served from RAM with LRU eviction. Invalidated by fsnotify. Implies WithCachedFS. budgetBytes is the maximum memory for cached content (default 200MB if 0).
func WithTrigramIndex ¶
func WithTrigramIndex() ServerOption
WithTrigramIndex enables trigram-based search indexing for sub-linear text search. Implies WithContentCache (trigram index reads content from cache). Files are indexed at startup and updated incrementally via fsnotify.
func WithVFS ¶
func WithVFS(vfs VFS) ServerOption
WithVFS sets a custom VFS backend. Defaults to LocalVFS.
type SymbolEntry ¶
type SymbolEntry struct {
Name string
Kind string // "function", "struct", "method", "interface", "class", "constant", "variable"
Signature string
Line int
Parent string
Children []SymbolEntry
}
SymbolEntry is a flattened symbol record for the code map.
type SymbolInput ¶
type SymbolInput struct {
Name string
Kind string
Signature string
File string
Line int
Parent string
Children []SymbolInput
}
BuildCodeMap constructs a CodeMap from raw symbol data (as returned by ListSymbols). Each SymbolInput mirrors the proto Symbol message but in plain Go types.
type SymbolProvider ¶
type SymbolProvider interface {
ListSymbols(ctx context.Context, file string) ([]*codev0.Symbol, error)
}
SymbolProvider abstracts how symbols are resolved for a codebase. Default implementation: ASTSymbolProvider (Go AST via ParseGoTree). Override with LSPSymbolProvider (gopls) for full cross-module resolution.
type TSASTSymbolProvider ¶
type TSASTSymbolProvider struct {
// contains filtered or unexported fields
}
TSASTSymbolProvider extracts symbols from TypeScript/JavaScript files using the TypeScript compiler API via a Node.js subprocess.
func NewTSASTSymbolProvider ¶
func NewTSASTSymbolProvider(sourceDir string) *TSASTSymbolProvider
NewTSASTSymbolProvider creates a provider that parses TS/JS files.
func (*TSASTSymbolProvider) Close ¶
func (p *TSASTSymbolProvider) Close()
Close removes the temporary script file.
func (*TSASTSymbolProvider) ListSymbols ¶
func (p *TSASTSymbolProvider) ListSymbols(ctx context.Context, file string) ([]*codev0.Symbol, error)
ListSymbols extracts symbols from a file or the entire source directory.
func (*TSASTSymbolProvider) ListSymbolsByFile ¶
func (p *TSASTSymbolProvider) ListSymbolsByFile(ctx context.Context) (map[string][]*codev0.Symbol, error)
ListSymbolsByFile returns symbols grouped by relative file path.
type TimelineChunk ¶
type TimelineChunk struct {
StartLine int
EndLine int
Hash string
Author string
Date time.Time
Age AgeBucket
Summary string // first non-blank content line in the range
}
TimelineChunk groups consecutive lines from the same commit.
type TimelineStats ¶
type TimelineStats struct {
TotalLines int
TotalFiles int
TotalChunks int
LinesByAge map[AgeBucket]int // lines per bucket
NewestFile string // most recently modified file
NewestDate time.Time // date of most recent change
OldestFile string // oldest untouched file
OldestDate time.Time // date of oldest change
Hotspots []HotspotFile // files with most distinct chunks (frequently patched)
}
TimelineStats summarizes the temporal distribution of a project's code.
func ComputeTimelineStats ¶
func ComputeTimelineStats(timelines []*FileTimeline) TimelineStats
ComputeTimelineStats derives project-wide statistics from a set of timelines.
type TrigramIndex ¶
type TrigramIndex struct {
// contains filtered or unexported fields
}
TrigramIndex provides sub-linear text search by maintaining posting lists of trigrams (3-byte sequences) to file IDs. A search query extracts trigrams, intersects their posting lists, and only scans the resulting candidate files.
Typical speedup: 10-100x on large repos vs linear scan.
func NewTrigramIndex ¶
func NewTrigramIndex() *TrigramIndex
NewTrigramIndex creates an empty trigram index.
func (*TrigramIndex) AddFile ¶
func (idx *TrigramIndex) AddFile(path string, content []byte)
AddFile indexes the content of a file. If the file was previously indexed, it is removed first (full re-index of that file).
func (*TrigramIndex) Query ¶
func (idx *TrigramIndex) Query(pattern string) []string
Query returns candidate file paths that contain ALL trigrams from the pattern. For short patterns (<3 bytes), returns all indexed files (no filtering possible). The candidates are a superset of actual matches — callers must verify with regex.
func (*TrigramIndex) RemoveFile ¶
func (idx *TrigramIndex) RemoveFile(path string)
RemoveFile removes a file from the index.
func (*TrigramIndex) Size ¶
func (idx *TrigramIndex) Size() int
Size returns the number of indexed files.
type VCSProvider ¶
type VCSProvider interface {
// Log returns recent commits, optionally filtered by ref, path, and date.
Log(ctx context.Context, maxCount int, ref, path, since string) ([]*GitCommitInfo, error)
// Diff returns a diff between two refs (or working copy if refs are empty).
// Returns the full diff text and per-file statistics.
Diff(ctx context.Context, baseRef, headRef, path string, contextLines int, statOnly bool) (string, []*GitDiffFileInfo, error)
// Show returns the content of a file at a specific ref.
Show(ctx context.Context, ref, path string) (string, bool, error)
// Blame returns line-by-line authorship of a file.
Blame(ctx context.Context, path string, startLine, endLine int32) ([]*GitBlameLine, error)
}
VCSProvider abstracts version control operations. Both git and jj implement this interface, allowing the DefaultCodeServer to dispatch VCS operations without knowing which VCS is in use.
The response types (GitCommitInfo, GitDiffFileInfo, etc.) are VCS-agnostic despite their "Git" prefix — they map to the Code proto responses.
type VFS ¶
type VFS interface {
ReadFile(path string) ([]byte, error)
WriteFile(path string, data []byte, perm os.FileMode) error
Remove(path string) error
Rename(oldpath, newpath string) error
Stat(path string) (os.FileInfo, error)
MkdirAll(path string, perm os.FileMode) error
WalkDir(root string, fn fs.WalkDirFunc) error
ReadDir(path string) ([]os.DirEntry, error)
}
VFS abstracts filesystem operations so DefaultCodeServer can work with local disk, in-memory stores, overlay layers, or remote backends. All paths are absolute -- the server joins SourceDir + relative before calling.
type VFSProvider ¶
VFSProvider is implemented by servers that expose their underlying VFS and root directory for in-process use (e.g. relevance scoring, timeline building).
type WriteListener ¶
WriteListener is called after every successful file mutation so that language plugins can push the new content into their LSP's in-memory view via textDocument/didChange. Without this, gopls and pylsp only notice the edit when their filesystem watcher fires — latency that breaks the agent's "edit → query symbols → see own edit" inner loop.
The listener receives the mutation kind ("write", "create", "delete", "move"), the relative path (destination for moves), and the new file content if available. For deletes and moves the content argument is nil. For the move kind, prevPath is the source path; it is empty otherwise.
Errors returned by the listener are logged by the caller but do NOT fail the mutation — notification is best-effort. A failing LSP shouldn't break file I/O.
Source Files
¶
- codemap.go
- context.go
- depgraph.go
- diff.go
- edit.go
- fileops.go
- git_native.go
- go_server.go
- graph.go
- graph_symbol_index.go
- jj_native.go
- lru.go
- parse_go.go
- python_server.go
- python_symbol_provider.go
- relevance.go
- search.go
- server.go
- shell_exec.go
- symbol_provider.go
- timeline.go
- trigram.go
- ts_symbol_provider.go
- vcs.go
- vfs.go
- vfs_cached.go
- vfs_memory.go
- vfs_overlay.go