Documentation
¶
Index ¶
- Constants
- Variables
- func CallsCacheKey(root string, ranked []RankedFile, cfg CallsConfig) string
- func CheckGopls() error
- func CheckLspq() error
- func CtagsAvailable() bool
- func DetectImplementations(files []*FileSymbols)
- func EncodeJSON(a *CommitAnalysis, pretty bool) ([]byte, error)
- func ExpandCallers(ctx context.Context, root string, ranked []RankedFile, cfg CallsConfig, ...) (SymbolCallers, CallsStats)
- func FormatLines(files []RankedFile, maxTokens int, root string) string
- func FormatMap(files []RankedFile, maxTokens int, verbose, detail bool) string
- func FormatMapCompact(files []RankedFile, maxTokens int) string
- func FormatMapWithCallers(files []RankedFile, maxTokens int, verbose, detail bool, callers SymbolCallers, ...) string
- func FormatXML(files []RankedFile, maxTokens int) string
- func LanguageFor(ext string) string
- func ParseFindQuery(q string) (name, kind, file string)
- func PersistInventory(inv *Inventory, cacheDir string) error
- func QueryInventory(cacheDir string, filter string) (string, error)
- func SaveCallsCache(cacheDir, hash string, callers SymbolCallers) error
- func TreeSitterAvailable() bool
- type AnalyzeOptions
- type BlocklistConfig
- type CallsConfig
- type CallsStats
- type CommitAnalysis
- type CommitCounts
- type CommitGroup
- type CommitRefs
- type Config
- type DepBump
- type FileInfo
- type FileMetrics
- type FileSymbols
- type Finding
- type Inventory
- type Location
- type Map
- func (m *Map) Build(ctx context.Context) error
- func (m *Map) BuiltAt() time.Time
- func (m *Map) Config() Config
- func (m *Map) Dirty()
- func (m *Map) FindSymbol(name, kind, file string) []SymbolMatch
- func (m *Map) LoadCache(cacheDir string) bool
- func (m *Map) LoadCacheIncremental(ctx context.Context, cacheDir string) (bool, []string)
- func (m *Map) Ranked() []RankedFile
- func (m *Map) SaveCache(cacheDir string) error
- func (m *Map) SetCacheDir(dir string)
- func (m *Map) Stale() bool
- func (m *Map) String() string
- func (m *Map) StringCompact() string
- func (m *Map) StringDetail() string
- func (m *Map) StringLines() string
- func (m *Map) StringVerbose() string
- func (m *Map) StringXML() string
- type RankedFile
- type RefsQuerier
- type RemoteInfo
- type SecretsSummary
- type Symbol
- type SymbolCallers
- type SymbolMatch
Constants ¶
const DefaultConfidenceCutoff = 0.75
DefaultConfidenceCutoff is the clustering confidence threshold used when callers leave AnalyzeOptions.ConfidenceCutoff at zero.
Variables ¶
var ErrNotCodeProject = errors.New("no source files found")
ErrNotCodeProject is returned by Build when the target directory contains no recognisable source files. Callers should treat this as a normal condition, not an error — the project is simply not a code project.
Functions ¶
func CallsCacheKey ¶ added in v0.7.0
func CallsCacheKey(root string, ranked []RankedFile, cfg CallsConfig) string
CallsCacheKey computes the FNV hash key for a --calls cache entry. Components: absolute repo root + sorted (path, mtime) pairs + flag combo string.
func CheckGopls ¶ added in v0.7.0
func CheckGopls() error
CheckGopls verifies that gopls is on PATH.
func CheckLspq ¶ added in v0.7.0
func CheckLspq() error
CheckLspq verifies that the lspq binary is on PATH, returning a descriptive error if it is not. Used only when --calls-use-binary is set.
func CtagsAvailable ¶
func CtagsAvailable() bool
CtagsAvailable reports whether ctags with JSON output support is on PATH.
func DetectImplementations ¶
func DetectImplementations(files []*FileSymbols)
DetectImplementations scans parsed files and populates Symbol.Implements on struct types whose exported method sets satisfy an interface declared in the same project.
Matching is by exported method name only — a struct implements an interface if its methods are a superset of the interface's method names. This is a proxy for Go's structural typing; it is tight enough for LLM signal but not a full type checker (signature compatibility is not verified, and embedded interfaces are treated as opaque method names).
func EncodeJSON ¶
func EncodeJSON(a *CommitAnalysis, pretty bool) ([]byte, error)
EncodeJSON serializes a CommitAnalysis for stdout. Compact by default; set pretty=true for human inspection.
func ExpandCallers ¶ added in v0.7.0
func ExpandCallers( ctx context.Context, root string, ranked []RankedFile, cfg CallsConfig, q RefsQuerier, progress func(done, total int), ) (SymbolCallers, CallsStats)
ExpandCallers queries a RefsQuerier for each exported symbol in files that meet the threshold, returning a SymbolCallers map and run statistics.
progress is called with (done, total) as each symbol completes; pass nil to disable.
func FormatLines ¶
func FormatLines(files []RankedFile, maxTokens int, root string) string
FormatLines formats ranked files showing actual source code lines. root is the project root for resolving file paths.
func FormatMap ¶
func FormatMap(files []RankedFile, maxTokens int, verbose, detail bool) string
FormatMap formats ranked files into a token-budgeted text representation. maxTokens controls the output size (estimated as len(text)/4). Returns empty string if no files have symbols. When verbose is true, shows all symbols without summarization. When detail is true, shows signatures for funcs/methods and fields for structs.
func FormatMapCompact ¶ added in v0.7.0
func FormatMapCompact(files []RankedFile, maxTokens int) string
FormatMapCompact formats ranked files into the lean orientation mode: path + exported symbol names only, NO signatures, NO godoc, NO struct fields. Budget is applied using compactCost so more files fit vs. the enriched default. Returns empty string if no files have symbols.
func FormatMapWithCallers ¶ added in v0.7.0
func FormatMapWithCallers(files []RankedFile, maxTokens int, verbose, detail bool, callers SymbolCallers, limit int) string
FormatMapWithCallers formats the ranked files like FormatMap but injects caller information from the callers map into the output.
func FormatXML ¶
func FormatXML(files []RankedFile, maxTokens int) string
FormatXML formats ranked files as a structured XML document. maxTokens controls the output size (estimated as len(text)/4). Returns empty string if no files have symbols.
func LanguageFor ¶
LanguageFor returns the language ID for a file extension, or "" if unsupported.
func ParseFindQuery ¶ added in v0.6.0
ParseFindQuery splits a positional query of the form
[kind:][file:<path>:]<name>
into (name, kind, file). Qualifier prefixes may appear in either order; the final token is always the name. Empty input returns all empties.
func PersistInventory ¶
PersistInventory writes the inventory to disk using atomic write (temp + rename).
func SaveCallsCache ¶ added in v0.7.0
func SaveCallsCache(cacheDir, hash string, callers SymbolCallers) error
SaveCallsCache writes a SymbolCallers map to disk atomically.
func TreeSitterAvailable ¶
func TreeSitterAvailable() bool
TreeSitterAvailable reports whether tree-sitter parsing is available.
Types ¶
type AnalyzeOptions ¶
type AnalyzeOptions struct {
Root string // repo root (usually ".")
Tag bool // --tag: activate release gate (go.mod bump before commit)
ConfidenceCutoff float64 // default 0.75
Tmpdir string // override temp directory (tests)
}
AnalyzeOptions configures a commit-analyze run.
type BlocklistConfig ¶ added in v0.6.0
type BlocklistConfig struct {
// MethodBlocklist lists symbol-name patterns to drop at parse time.
// Each entry is either:
// - a regex wrapped in forward slashes, e.g. "/^pb_/"
// - a glob matched with path.Match, e.g. "Test*" or "*Mock"
MethodBlocklist []string `yaml:"method_blocklist"`
// contains filtered or unexported fields
}
BlocklistConfig holds loaded-from-disk repomap settings that filter parsed symbols. Start minimal — more fields land in follow-up versions. Safe for concurrent reads after Load returns.
func LoadBlocklistConfig ¶ added in v0.6.0
func LoadBlocklistConfig(root string) (*BlocklistConfig, error)
LoadBlocklistConfig reads <root>/.repomap.yaml. Returns zero-value config when the file is absent. Returns a wrapped error only when the file exists but is malformed or has invalid patterns.
func (*BlocklistConfig) ShouldSkipSymbol ¶ added in v0.6.0
func (c *BlocklistConfig) ShouldSkipSymbol(name string) bool
ShouldSkipSymbol reports whether a symbol name matches any blocklist pattern. A nil receiver or empty blocklist returns false.
type CallsConfig ¶ added in v0.7.0
type CallsConfig struct {
// Threshold: only expand symbols in files with ImportedBy >= Threshold.
Threshold int
// Limit: max callers shown per symbol.
Limit int
// IncludeTests: when false, filter out callers whose file path contains _test.go.
IncludeTests bool
}
CallsConfig controls --calls mode behaviour.
func DefaultCallsConfig ¶ added in v0.7.0
func DefaultCallsConfig() CallsConfig
DefaultCallsConfig returns the default --calls settings.
type CallsStats ¶ added in v0.7.0
CallsStats holds counters from a call-expansion run.
type CommitAnalysis ¶
type CommitAnalysis struct {
Version int `json:"version"`
Tmpdir string `json:"tmpdir"`
EarlyExit bool `json:"early_exit"`
EarlyReason string `json:"early_reason,omitempty"`
Complexity string `json:"complexity"` // simple | medium | complex
Counts CommitCounts `json:"counts"`
HistoryStyle string `json:"history_style"` // conventional | mixed | freeform
LatestTag string `json:"latest_tag,omitempty"` // most recent semver tag; empty if none
RecentSubjects []string `json:"recent_subjects,omitempty"` // top-5 commit subjects from HEAD (style sample)
Remote RemoteInfo `json:"remote"` // origin URL + visibility class; drives finding default_action
Secrets SecretsSummary `json:"secrets"`
Artifacts []string `json:"artifacts"` // paths recommended for .gitignore
ConfigFiles []string `json:"config_files"` // .md/.yaml/.toml/.json/.env*/.cfg/.ini/.conf in changeset
DepBumps []DepBump `json:"dep_bumps"`
Groups []CommitGroup `json:"groups"`
PlanHash string `json:"plan_hash"`
Refs CommitRefs `json:"refs"`
Diagnostics []string `json:"diagnostics,omitempty"` // non-fatal warnings
}
CommitAnalysis is the JSON document `repomap commit analyze` writes to stdout. Designed to stay under ~5KB for typical changesets — large blobs (full diffs, untracked content, plan text, full findings) are written to disk and referenced by Refs paths so the agent can read them on demand.
func AnalyzeCommit ¶
func AnalyzeCommit(ctx context.Context, opts AnalyzeOptions) (*CommitAnalysis, error)
AnalyzeCommit is the public entrypoint called by the CLI. Collects git state, parses all dirty files, runs grouping + messages + secrets, writes side files, returns the CommitAnalysis ready for JSON emit.
type CommitCounts ¶
type CommitCounts struct {
Total int `json:"total"`
Staged int `json:"staged"`
Unstaged int `json:"unstaged"`
Untracked int `json:"untracked"`
}
CommitCounts gives a per-status file tally.
type CommitGroup ¶
type CommitGroup struct {
ID string `json:"id"`
Type string `json:"type"` // feat | fix | docs | chore | test | refactor | deps
Scope string `json:"scope"` // empty for top-level changes
SuggestedMsg string `json:"suggested_msg"`
Files []string `json:"files"`
Rationale string `json:"rationale"` // why these files cluster
Confidence float64 `json:"confidence"` // 0.0–1.0
DiffOffsets map[string][2]int `json:"diff_offsets,omitempty"` // file -> [byte_start, byte_end] in refs.diffs
}
CommitGroup is one proposed commit. The agent ratifies (confidence >= 0.75) or inspects refs.diffs at DiffOffsets to refine grouping/messaging.
type CommitRefs ¶
type CommitRefs struct {
Plan string `json:"plan"` // commit-execute.sh format, ready to pipe
Diffs string `json:"diffs"` // full unified diff
Untracked string `json:"untracked"` // full content of untracked config/md files
History string `json:"history"` // full git log sample
Findings string `json:"findings"` // FLAG/REVIEW/CLEAR JSON array
}
CommitRefs points at on-disk side files for content too large to inline.
type Config ¶
type Config struct {
MaxTokens int // token budget for output (default: 1024)
MaxTokensNoCtx int // budget when no files in conversation (default: 2048)
}
Config holds repomap configuration.
type DepBump ¶
type DepBump struct {
File string `json:"file"` // go.mod, package.json, plugin.json, etc.
Manager string `json:"manager,omitempty"` // go | npm | cargo | dc-plugin
Changes []string `json:"changes"` // human-readable: "name v1 -> v2"
}
DepBump captures a recognized dependency version change in package manifests.
type FileMetrics ¶
type FileSymbols ¶
type FileSymbols struct {
Path string // relative path from project root
Language string // language ID
Package string // Go package name (empty for non-Go)
ImportPath string // Go import path from module (empty for non-Go)
Symbols []Symbol
Imports []string // import paths (Go) or module names (other)
ParseMethod string // "ast", "treesitter", "ctags", or "regex" — signals symbol fidelity
}
FileSymbols holds all symbols extracted from a single source file.
func ParseGenericFile ¶
func ParseGenericFile(path, root, language string) (*FileSymbols, error)
ParseGenericFile extracts symbols from a non-Go source file using regex patterns. path is absolute, root is the project root for relative path calculation.
func ParseGoFile ¶
func ParseGoFile(path, root string) (*FileSymbols, error)
ParseGoFile extracts exported symbols from a Go source file. path is absolute, root is the project root for relative path calculation.
func ParseWithCtags ¶
ParseWithCtags runs ctags once over all files and returns FileSymbols for each non-Go file in the list. Files must be absolute paths; root is used only for computing relative paths in output.
type Finding ¶
type Finding struct {
Class string `json:"class"` // FLAG | REVIEW | CLEAR
Kind string `json:"kind"` // secret | pii | dev_history | path | email | etc.
File string `json:"file"`
Line int `json:"line,omitempty"`
Snippet string `json:"snippet,omitempty"`
Detail string `json:"detail,omitempty"`
DefaultAction string `json:"default_action"` // fix | safe | review
}
Finding is one secret/PII/dev-history hit emitted by commit_secrets.go. DefaultAction is the deterministic adjudication the agent should follow unless it has a reason to override — it collapses the per-finding LLM loop that previously re-examined every REVIEW hit.
type Inventory ¶
type Inventory struct {
Files []FileMetrics `json:"files"`
Scanned string `json:"scanned"`
RootPath string `json:"root_path"`
Truncated bool `json:"truncated,omitzero"` // true when file cap was reached
}
func LoadInventory ¶
LoadInventory reads a previously persisted inventory from disk. Returns nil if the file is missing or corrupt.
type Location ¶ added in v0.7.0
type Location struct {
File string `json:"file"`
Line int `json:"line"`
Column int `json:"column"`
}
Location is a source position returned by a refs query.
type Map ¶
type Map struct {
// contains filtered or unexported fields
}
Map holds the built repository map state.
func (*Map) Build ¶
Build performs a full scan → parse → rank pipeline. When cacheDir is set, first tries an incremental rebuild via git diff against the cached HEAD SHA. Falls through to full rebuild on any eligibility failure — correctness over speed. Safe for concurrent use.
func (*Map) BuiltAt ¶
BuiltAt returns the time of the last successful build, or zero time if never built.
func (*Map) Dirty ¶
func (m *Map) Dirty()
Dirty marks the map as needing a rebuild by zeroing builtAt, bypassing the stale debounce. Use after code-changing tool calls.
func (*Map) FindSymbol ¶ added in v0.6.0
func (m *Map) FindSymbol(name, kind, file string) []SymbolMatch
FindSymbol searches the ranked symbol set for matches.
name: required (empty → empty result). Matched in priority order:
exact (100) > case-insensitive exact (75) > prefix (50) > contains (25).
kind: optional filter; "" matches any. Matched case-insensitively against Symbol.Kind.
file: optional substring filter against RankedFile.Path; "" matches any.
Results are sorted by Score desc, then the owning RankedFile.Score desc (tiebreaker), then File asc (stable tiebreaker). Safe for concurrent use.
func (*Map) LoadCache ¶
LoadCache loads a previously saved map from disk. Returns false if the cache is missing, corrupt, or for a different version.
func (*Map) LoadCacheIncremental ¶ added in v0.6.0
LoadCacheIncremental attempts a fast-path rebuild. Returns (true, changedRel) when the cache is valid for incremental use and the caller should merge `changedRel` (relative paths of added+modified files; deletions handled via side channel). Returns (false, nil) for any of:
- cache missing / corrupt / wrong version / wrong root
- cache was written for a non-git root (GitRoot=false)
- `git rev-parse HEAD` fails or returns empty
- diff between LastSHA and HEAD fails (e.g., SHA pruned by rebase)
- change set exceeds incrementalThreshold of total files
On (true, changedRel) the Map has been hydrated with the cached state and its mtimes map is populated. Deleted paths have already been removed from m.ranked. The caller is expected to re-parse changedRel, splice the results back in, re-rank, re-budget, and SaveCache.
func (*Map) Ranked ¶ added in v0.5.0
func (m *Map) Ranked() []RankedFile
Ranked returns the ranked file list built by Build. Returns nil if Build has not been called.
func (*Map) SetCacheDir ¶
SetCacheDir enables disk caching. Build() will save to this directory.
func (*Map) Stale ¶
Stale reports whether any tracked file has been modified since the last build. Uses file mtimes for fast checking. Also stale if Build has never been called. Debounced: returns false if last build was <30s ago.
func (*Map) String ¶
String returns the current formatted map output. Returns empty string if Build has not been called or produced no symbols.
func (*Map) StringCompact ¶ added in v0.7.0
StringCompact returns the lean orientation output: path + exported symbol names only. No signatures, no godoc, no struct fields. Budget is applied using compactCost so more files fit vs. the enriched default (m.String()). Returns empty string if Build has not been called or produced no symbols.
func (*Map) StringDetail ¶
StringDetail returns the full detailed map output with signatures and struct fields.
func (*Map) StringLines ¶
StringLines returns the source-line format showing actual code definitions.
func (*Map) StringVerbose ¶
StringVerbose returns the full verbose map output (all symbols, no summarization).
type RankedFile ¶
type RankedFile struct {
*FileSymbols
Score int // higher = more important
Tag string // e.g. "entry", ""
DetailLevel int // set by BudgetFiles: -1=omit, 0=header, 1=summary, 2=symbols, 3=symbols+fields
ImportedBy int // number of files that import this file's package
DependsOn int // number of internal imports (fan-out coupling proxy)
Untested bool // true if package lacks test coverage
Boundaries []string `json:"boundaries,omitempty"` // semantic boundary labels, e.g. ["HTTP", "Postgres"]
}
RankedFile is a FileSymbols with an importance score.
func BudgetFiles ¶
func BudgetFiles(ranked []RankedFile, maxTokens int) []RankedFile
BudgetFiles assigns a DetailLevel to each RankedFile within the given token budget. When maxTokens is 0, all files get DetailLevel 2 (unlimited mode for verbose/detail).
Detail levels:
-1: omitted (budget overflow, counted in footer) 0: header only — path + optional (package name) 1: summary — path + "5 types, 3 funcs" 2: full symbol groups 3: symbols + struct/interface field expansion
func BudgetFilesCompact ¶ added in v0.7.0
func BudgetFilesCompact(ranked []RankedFile, maxTokens int) []RankedFile
BudgetFilesCompact assigns DetailLevel to each RankedFile using compactCost estimates, matching the lean orientation renderer (path + exported symbol names only). When maxTokens is 0, all files get DetailLevel 2 (unlimited mode).
This is separate from BudgetFiles (which uses enrichedCost) so compact-mode callers get accurate budgeting without rewriting the enriched budget loop.
func RankFiles ¶
func RankFiles(files []*FileSymbols) []RankedFile
RankFiles scores and sorts files by importance. Returns files sorted by score descending, then by path ascending for ties.
type RefsQuerier ¶ added in v0.7.0
type RefsQuerier interface {
Refs(ctx context.Context, file string, line int, symbol string) ([]Location, error)
}
RefsQuerier abstracts the refs backend so tests can inject a fake and callers can choose between in-process gopls and exec-based lspq.
func DefaultQuerier ¶ added in v0.7.0
func DefaultQuerier() RefsQuerier
DefaultQuerier returns the lspq exec-based querier (legacy fallback).
func NewInProcessQuerier ¶ added in v0.7.0
func NewInProcessQuerier(mgr *lsp.Manager) RefsQuerier
NewInProcessQuerier returns a RefsQuerier that uses an already-running LSP Manager. The caller owns the Manager lifecycle (Shutdown).
type RemoteInfo ¶
type RemoteInfo struct {
OriginURL string `json:"origin_url,omitempty"`
Visibility string `json:"visibility"` // public | private | none | unknown
}
RemoteInfo records the origin remote and its visibility class. Used to pick the strictness of default_action on REVIEW findings: a personal repo with no remote gets lenient defaults; github.com/* public repos get strict defaults.
type SecretsSummary ¶
type SecretsSummary struct {
Clean bool `json:"clean"` // no FLAG findings (deterministic)
GitleaksFindings int `json:"gitleaks_findings"` // total flagged by gitleaks
ReviewCount int `json:"review_count"` // findings originally classed REVIEW (pre-adjudication)
FlagCount int `json:"flag_count"` // deterministic findings (auto-fixable)
FixCount int `json:"fix_count"` // findings with default_action=fix (auto-handled)
SafeCount int `json:"safe_count"` // findings with default_action=safe (auto-cleared)
AmbiguousCount int `json:"ambiguous_count"` // findings with default_action=review (need LLM judgment)
}
SecretsSummary is a compact gate for Phase 1 in the agent: if Clean is true and AmbiguousCount is zero, the agent can skip LLM review entirely — default_action handles every finding deterministically.
type Symbol ¶
type Symbol struct {
Name string // e.g. "Agent", "New", "Run"
Kind string // "function", "method", "struct", "interface", "constant", "variable", "type", "class", "enum"
Signature string // e.g. "(ctx, provider, opts) *Agent" — params + return, no func keyword
Receiver string // e.g. "*Agent" — methods only, empty for functions
Exported bool // true if the symbol is exported (uppercase first letter)
Line int // 1-based source line number (0 = unknown)
EndLine int // 1-based end line number (0 = unknown, same as Line when unavailable)
ParamCount int // parameter count (funcs/methods); method count (interfaces); 0 otherwise
ResultCount int // return value count (funcs/methods only); 0 otherwise
Implements []string // interface names this type implements (structs only; Go-module-local)
Doc string `json:"doc,omitempty"` // first-sentence of the Go doc comment (empty if none)
}
Symbol represents a single extracted symbol from a source file.
type SymbolCallers ¶ added in v0.7.0
SymbolCallers maps "file:symbol" -> caller locations.
func LoadCallsCache ¶ added in v0.7.0
func LoadCallsCache(cacheDir, hash string) SymbolCallers
LoadCallsCache loads a cached SymbolCallers map from disk. Returns nil if the cache is missing, corrupt, or version-mismatched.
type SymbolMatch ¶ added in v0.6.0
type SymbolMatch struct {
File string // path relative to root
Symbol Symbol // the matching symbol
Score float64 // relevance score: 100=exact, 75=exact-CI, 50=prefix, 25=contains
DetailLevel int // copied from the owning RankedFile (for budget-aware callers)
}
SymbolMatch is a single hit from FindSymbol. Results are sorted by Score descending; use the File+Symbol.Line pair for a stable identifier.
Source Files
¶
- boundary.go
- budget.go
- cache.go
- calls.go
- calls_cache.go
- calls_render.go
- categorize.go
- commit_analyze.go
- commit_gitstate.go
- commit_grouping.go
- commit_messages.go
- commit_secrets.go
- commit_types.go
- config.go
- depgraph.go
- filter.go
- find.go
- git.go
- go_signature.go
- incremental.go
- interface_detect.go
- inventory.go
- inventory_persist.go
- inventory_scan.go
- inventory_types.go
- ioutil.go
- language.go
- parse_dispatch.go
- parser_cfamily.go
- parser_ctags.go
- parser_generic.go
- parser_go.go
- parser_treesitter.go
- parser_ts_cfamily.go
- parser_ts_java.go
- parser_ts_php.go
- parser_ts_php_doc.go
- parser_ts_php_signatures.go
- parser_ts_python.go
- parser_ts_rust.go
- parser_ts_typescript.go
- parser_ts_web.go
- parser_web.go
- ranker.go
- render.go
- render_lines.go
- render_xml.go
- repomap.go
- scanner.go
- summarize.go
- types.go