repomap

package module
v0.13.1 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 47 Imported by: 0

README

repomap

Turn a repository into a compact, deterministic code map for coding agents, scripts, and humans.

repomap --intent "fix token refresh race" -t 4096
## Repository Map (138 files, 807 symbols)

### Flow
entry: cmd/repomap/main.go
spine: repomap.go, types.go, ranker.go, budget.go, render.go

### Dependencies
repomap/cmd/repomap -> repomap/internal/cli
repomap/internal/cli -> repomap, repomap/internal/lsp

repomap.go [imported by 12]
  type Config{MaxTokens int, MaxTokensNoCtx int, Intent string, ConsumedPaths []string}
    // holds repomap configuration
  type Map
    // holds the built repository map state
  func New(root string, cfg Config) *Map
  func (*Map) Build(ctx context.Context) error

repomap is local static analysis: git ls-files, Go go/ast, tree-sitter, ctags/regex fallback, import graphs, BM25 intent ranking, and optional gopls caller expansion. It does not call an LLM.

Install

go install github.com/dotcommander/repomap/cmd/repomap@latest

Or build from a checkout:

git clone https://github.com/dotcommander/repomap
cd repomap
go build -o repomap ./cmd/repomap

Quick Start

repomap

Scans the current repository, ranks important files first, and renders exported symbols, signatures, first-sentence docs, and struct/interface fields within the default token budget.

repomap ./internal/cli -t 6000

Map a subtree with a larger budget.

repomap --intent "debug caller expansion timeouts"

Bias ranking toward files whose paths, packages, exported symbols, imports, and signatures match the task.

repomap --symbol-refs

Add a cheap cross-language lexical reference signal for non-Go symbols when imports are too weak and LSP caller data is unavailable.

repomap --intent "debug caller expansion timeouts" --consumed calls.go,internal/lsp/client.go

Downrank files you already read and uprank files that import them.

Workflow Examples

Orient a Coding Agent
repomap --intent "add structured json output" -t 4096

Use this as first context. It gives the agent entry points, central packages, public APIs, and the most task-relevant files without dumping source.

Ask What a File Can Affect
repomap impact ranker.go
ranker.go
  parsed: go_ast
  imports: path/filepath, slices, strings
  imported by: internal/cli/root.go, internal/cli/find.go, ...
  tests: ranker_test.go, ranker_callers_test.go, ranker_consumed_test.go
  exported: RankFiles, RankedFile
  score: 133 map[imports:120 symbols:3 transitive:10]

impact reports local facts only: imports, reverse imports, nearby tests, exported symbols, boundaries, parser backend, and score components.

Get Context for One Symbol
repomap context RankFiles
ranker.go:49  function  RankFiles(files []*FileSymbols) []RankedFile
also matched:
  repomap_test.go:200  function  TestRankFiles(t *testing.T)

source:
  49 | func RankFiles(files []*FileSymbols) []RankedFile {
  50 |     ranked := make([]RankedFile, len(files))
     ...
ranker.go
  parsed: go_ast
  imports: path/filepath, slices, strings
  tests: ranker_test.go, ranker_callers_test.go

context is a symbol-centered bundle: best match, bounded source span, ambiguity hints, and the owning file's impact facts. Use --json for structured output, or --calls to include exact Go callers through gopls.

Explain a Ranking Decision
repomap explain ranker.go
ranker.go
  score: 133
  detail: omitted (budget)
  components:
    imports: +120
    symbols: +3
    transitive: +10

Use explain when a match looks suspicious. Every score component is deterministic and auditable.

Feed a Tool Structured Data
repomap --json-structured -t 4096 > map.json
{
  "schema_version": 1,
  "files": [
    {
      "path": "ranker.go",
      "language": "go",
      "parse_method": "go_ast",
      "score": 133,
      "score_components": {
        "imports": 120,
        "symbols": 3,
        "transitive": 10
      },
      "detail_level": -1,
      "omitted_reason": "budget",
      "symbols": [
        {
          "name": "RankFiles",
          "kind": "function",
          "line": 48
        }
      ]
    }
  ]
}

Files excluded by the budget remain present with detail_level: -1 and omitted_reason.

Expand Callers with gopls
repomap --calls --calls-threshold 2 --calls-limit 8

--calls asks gopls for references to exported symbols in highly imported files, then boosts files with many caller sites. Caller data is cached under ~/.cache/repomap unless --no-cache is set.

Inspect Cache State
repomap cache status
repomap cache status --json

cache status reports whether the disk cache for the current root exists, is usable, and appears fresh. It checks the saved cache version, root, tracked file hashes/mtimes, and saved HEAD when present.

Seed a Deep Audit
repomap audit brief --json --limit 20
repomap audit hygiene --json
repomap audit risks --json --limit 20
repomap audit surface --json --limit 20
repomap audit effects --json --limit 20

audit brief builds the map once and emits risks, surface, effects, a grouped first-read queue, and a review_plan for workflow tools. The review_plan projects the first-read queue into per-lane review obligations — each lane lists the files to cover, the gates to discharge, suggested verify commands (Go-specific commands appear only when Go sources are detected), and why the lane matters — so deep-audit tools get coverage targets without inventing findings. Use the narrower commands when you only need one packet. audit hygiene reports tracked, untracked, and ignored source-file leads so release audits can catch local-only code. audit risks converts rank, boundary, and symbol-size facts into lane packets for tools such as repo-audit-deep. audit surface extracts commands, flags, env vars, config keys, JSON schema fields, routes, and output paths. audit effects extracts side-effect boundaries such as filesystem writes, subprocesses, HTTP, DB calls, serialization, secrets, crypto, time, and randomness. These are deterministic leads, not final findings.

Commands

repomap [directory]                 # default enriched map
repomap -t 4096                     # token budget
repomap -f compact                  # path + exported symbol names
repomap -f verbose                  # all symbols, no budget cap
repomap -f detail                   # all symbols with signatures and fields
repomap -f lines                    # declaration source lines
repomap -f xml                      # structured XML
repomap --json                      # JSON envelope with rendered lines
repomap --json --json-legacy        # legacy bare []string JSON
repomap --json-structured           # schema-versioned map data
repomap find RankFiles              # locate symbols
repomap context RankFiles           # source + impact context for one symbol
repomap impact ranker.go            # blast-radius facts for a file
repomap audit brief                 # single-pass audit packets + first-read queue
repomap audit hygiene               # tracked/untracked/ignored source leads
repomap audit risks                 # lane-oriented audit risk packets
repomap audit surface               # command/flag/config/schema/API/output surfaces
repomap audit effects               # side-effect and trust-boundary packets
repomap cache status                # inspect disk cache freshness
repomap explain ranker.go           # ranking and budget evidence
repomap init                        # scaffold .repomap.yaml and post-commit cache hook

LSP commands are also available when gopls is installed:

repomap symbols ranker.go
repomap def ranker.go 48 RankFiles
repomap refs ranker.go 48 RankFiles
repomap hover ranker.go 48 RankFiles

Output Formats

Format What it shows Budget enforced
default Exported symbols, signatures, docs, struct/interface fields yes
compact File paths and exported symbol names yes
verbose All symbols, no summarization no
detail All symbols plus signatures and fields no
lines Actual declaration lines yes
xml Structured XML yes
--json Rendered verbose lines in JSON no
--json-structured Files, symbols, ranks, parser data, budget data yes

Budgeting is all-or-lower-detail: repomap does not cut a file halfway through a symbol. A file renders at its assigned detail level, drops to a summary/header, or is marked omitted.

Ranking

repomap ranks files before budgeting. Main signals:

Signal Effect
Entry point (main.go, index.ts, app.py, etc.) strong boost
Exported symbols contracts and public API rise
Direct importers heavily depended-on files rise
Transitive fan-in deep core files rise
Boundary imports HTTP, database, shell, and similar edges rise
Deep paths mild penalty
Tests (_test.go) demoted by default; --include-tests ranks them at full weight
--intent task-relevant files rise
--symbol-refs non-Go symbols mentioned by many other files rise
--consumed read files fall; their importers rise
--calls files with many caller sites rise

Check exact evidence with:

repomap explain path/to/file.go --json

Languages

Supported file types:

Language Parser path
Go go/ast
PHP tree-sitter with signatures, visibility, constructor promotion, PHPDoc
Python, Rust, TypeScript, JavaScript, Java, C, C++, Ruby, HTML, CSS tree-sitter when available, ctags/regex fallback

Structured output includes parse_method: go_ast, tree_sitter, ctags, or regex.

Configuration

Create .repomap.yaml at the repo root:

method_blocklist:
  - "Test*"
  - "*Mock"
  - "/^pb_/"

include_paths:
  - "cmd/*"
  - "internal/*"
  - "pkg/*"

exclude_paths:
  - "internal/generated/*"
  - "vendor/*"

file_overrides:
  "cmd/*/main.go": "full"
  "internal/generated/**": "omit"
Field Purpose
method_blocklist Drop matching symbols at parse time. Supports globs and /regex/.
include_paths If set, only matching paths are scanned.
exclude_paths Always excluded; wins over includes.
file_overrides Force matched files to "full" or "omit" detail.

Scaffold a config and cache-warming hook:

repomap init
repomap init --no-hook
repomap init --force

Library Usage

package main

import (
	"context"
	"fmt"

	"github.com/dotcommander/repomap"
)

func main() {
	m := repomap.New(".", repomap.Config{
		MaxTokens: 4096,
		Intent:    "debug caller expansion",
	})
	if err := m.Build(context.Background()); err != nil {
		panic(err)
	}

	fmt.Print(m.String())
}

Useful methods:

m.String()              // enriched default
m.StringCompact()       // lean orientation
m.StringVerbose()       // all symbols
m.StringDetail()        // all signatures and fields
m.StringLines()         // declaration lines
m.StringXML()           // XML
m.StructuredOutput()    // structured Go value
m.StructuredJSON()      // indented JSON bytes
m.Impact("ranker.go")   // file blast-radius facts
m.Explain("ranker.go")  // rank and budget evidence
m.Stale()               // source changed since build

Design

repomap is intentionally boring:

  • local only
  • deterministic
  • small Go API
  • no LLM calls
  • no embeddings
  • no hidden network dependency
  • graceful parser fallback

Pipeline:

scan -> parse -> rank -> budget -> format

Docs live in docs/. Start with docs/02-quick-start.md, then docs/03-output-formats.md, docs/06-ranking.md, and docs/08-languages.md. For a task-by-task tour from cold start to commit, see docs/11-usage-examples.md.

Acknowledgments

The repository map concept was pioneered by aider.chat, which popularized compact codebase maps for LLM-assisted development.

License

MIT

Documentation

Overview

Package repomap: tiers are a pure projection over ScoreComponents. They add provenance labels to explain why a file scored as it did, but never mutate Score or ScoreComponents.

Index

Constants

View Source
const (
	WeightTestPair  = 1.0
	WeightSymbolDep = 0.8
	WeightCoChange  = 0.5
	WeightSibling   = 0.3
)

Edge weights used by commit_grouping.buildEdges. Grouped here so the full edge-weight vocabulary is visible in one place and the clustering contract (DefaultConfidenceCutoff) has something to derive from.

Cluster-forming edges (weight >= DefaultConfidenceCutoff):

  • WeightTestPair — a test and its implementation file
  • WeightSymbolDep — one file imports another (exact-syntax match; Go module path, PHP FQCN `use`, Python dotted package, Rust `use` path, TS relative `import`)

Refine-only edges (below the cutoff; tie-break within a cluster but never form one on their own):

  • WeightCoChange — historical co-commit frequency
  • WeightSibling — same directory + same inferred type
View Source
const (
	PrepStatusReady         = "ready"
	PrepStatusNeedsJudgment = "needs_judgment"
	PrepStatusAbort         = "abort"
)

Prep status values emitted in PrepPayload.Status.

View Source
const (
	VerdictSafe   = "safe"
	VerdictUnsafe = "unsafe"
)

Review verdict values emitted in ReviewDecision.Verdict.

View Source
const (
	ActionFix    = "fix"
	ActionSafe   = "safe"
	ActionReview = "review"
)

DefaultAction values emitted in Finding.DefaultAction.

View Source
const DefaultConfidenceCutoff = WeightSymbolDep - 0.05

DefaultConfidenceCutoff is the minimum per-edge weight required to form a cluster. Set slightly below WeightSymbolDep so that symbol-dep is the lowest cluster-forming edge type; co-change (0.5) and sibling (0.3) are below the cutoff by design — they refine an already-clustered group but never pull files together on their own.

Invariant enforced by Test_EdgeWeights_ClusteringContract: every cluster-forming weight (test-pair, symbol-dep) must exceed this cutoff; every refine-only weight (co-change, sibling) must be below it.

Variables

View Source
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 ApplyCallerBonus added in v0.11.1

func ApplyCallerBonus(ranked []RankedFile, callerCounts map[string]int)

ApplyCallerBonus boosts files proportional to their caller count. Only meaningful in --calls mode where caller data is available.

Score delta: min(uniqueCallerFiles*2, 30) — capped at +30 so caller-heavy files boost rank without dominating files with high import counts.

func ApplyConsumedBonus added in v0.11.1

func ApplyConsumedBonus(ranked []RankedFile, consumedPaths map[string]bool)

ApplyConsumedBonus adjusts scores for files the caller has already read.

Consumed files are downranked (score halved) since the caller already has their content. Files that import consumed files are upranked (+15 per consumed dependency, capped at +45) because they are likely next files the caller will need to understand.

Follows the same pattern as ApplyCallerBonus: mutates scores in-place, re-sorts by score descending / path ascending for ties, returns nothing. No-op when consumedPaths is empty.

func ApplyIntraPackageRefs added in v0.13.0

func ApplyIntraPackageRefs(root string, ranked []RankedFile)

ApplyIntraPackageRefs adds a cheap, AST/lexical intra-package usage signal by counting how many other files reference each exported symbol. Unlike ApplySymbolReferenceBonus it INCLUDES Go files, since intra-package coupling is the strongest within-package importance signal when the import graph is flat (every file in a Go package shares one import path).

It is lexical by design — no gopls — and capped the same way as the cross-language symbol-reference bonus.

func ApplyReviewDecisions added in v0.11.0

func ApplyReviewDecisions(ctx context.Context, repoRoot string, decisions []ReviewDecision, findings []Finding) error

ApplyReviewDecisions applies LLM-adjudicated verdicts to REVIEW findings. For verdict="unsafe": applies the decision's Replacement at the finding's file+line. For verdict="safe": no-op (finding is cleared without edit). Callers should validate decisions before applying them.

func ApplySymbolReferenceBonus added in v0.11.3

func ApplySymbolReferenceBonus(root string, ranked []RankedFile)

ApplySymbolReferenceBonus adds a cheap, approximate cross-language usage signal by counting how many other files mention each exported non-Go symbol.

It is lexical by design: useful when import graphs are weak and LSP callers are unavailable, but lower-fidelity than --calls and therefore capped.

func CallerCountsFromSymbolCallers added in v0.11.1

func CallerCountsFromSymbolCallers(callers SymbolCallers) map[string]int

CallerCountsFromSymbolCallers derives a per-file unique-caller-file count from the SymbolCallers map produced by ExpandCallers.

The key in SymbolCallers is "targetFile\x00symbol"; each value is a slice of Locations (one per call site). We count distinct caller files per target file across all its symbols.

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, content-sha256) pairs + flag combo string. The key changes whenever any scanned source file's CONTENT changes, even if its path, mtime, and the flag values are unchanged. Files that cannot be hashed (deleted, unreadable) are skipped, matching the prior behaviour for un-stattable files.

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 ConfidenceOrder added in v0.13.0

func ConfidenceOrder() []string

ConfidenceOrder returns tier labels in canonical render order (highest confidence first).

func ContainsLowConf added in v0.11.0

func ContainsLowConf(lowConf []PrepLowConf, groupID string) bool

ContainsLowConf reports whether lowConf already contains an entry for groupID. Prevents double-adding a group that was already flagged by the confidence pass.

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 DetectJustfileRelease added in v0.11.0

func DetectJustfileRelease(repoRoot string) bool

DetectJustfileRelease returns true when a Justfile with a `release` recipe exists.

func DetectSessionRepos added in v0.11.0

func DetectSessionRepos(repoRoot string) []string

DetectSessionRepos returns repos likely touched in this session. Checks known companion repos; always includes repoRoot itself.

func EncodeExecuteResult added in v0.10.0

func EncodeExecuteResult(r *ExecuteResult, pretty bool) ([]byte, error)

EncodeExecuteResult serializes an ExecuteResult for stdout.

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 ExecExitCode added in v0.10.0

func ExecExitCode(err error) int

ExecExitCode extracts the exit code from an execError, defaulting to 1. Uses errors.As so wrapped execError values (e.g. fmt.Errorf("...: %w", err)) still return the embedded code.

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, cfg *BlocklistConfig, explain bool) string

FormatMap formats ranked files into a token-budgeted text representation. maxTokens controls the output size (estimated as len(text)/4). cfg may be nil — nil means no file-level detail overrides. 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, cfg *BlocklistConfig, explain bool) 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. cfg may be nil — nil means no file-level detail overrides. 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, cfg *BlocklistConfig, explain bool) string

FormatMapWithCallers formats the ranked files like FormatMap but injects caller information from the callers map into the output. cfg may be nil — nil means no file-level detail overrides.

func FormatXML

func FormatXML(files []RankedFile, maxTokens int, cfg *BlocklistConfig) string

FormatXML formats ranked files as a structured XML document. maxTokens controls the output size (estimated as len(text)/4). cfg may be nil — nil means no file-level detail overrides. Returns empty string if no files have symbols.

func IsKitchenSink added in v0.11.0

func IsKitchenSink(g *CommitGroup) bool

IsKitchenSink returns true when a CommitGroup looks like an accidental fusion that should be forced to LLM judgment. Triggers:

  1. Group has more than 10 files.
  2. Group spans more than one distinct top-level plugin segment (e.g. plugins/dc/... and plugins/pi/... in the same group).
  3. Group contains a plugin.json path — signals a new plugin being added.

func LanguageFor

func LanguageFor(ext string) string

LanguageFor returns the language ID for a file extension, or "" if unsupported.

func LoadDiffSlice added in v0.11.0

func LoadDiffSlice(diffsPath string, g CommitGroup, maxChars int) string

LoadDiffSlice extracts the diff slice for a group's files, capped at maxChars.

func ModeHint added in v0.11.0

func ModeHint(p PrepPreflight) string

ModeHint derives FULL/LOCAL from preflight signals.

FULL  = remote present AND gh auth logged in → push + tag
LOCAL = anything else                        → no push, no tag

Permissive on auth string format: any "logged in" substring is truthy unless the line also says "not logged in" (gh's own negative phrasing).

func ParseFindQuery added in v0.6.0

func ParseFindQuery(q string) (name, kind, file string)

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 PersistPrepState added in v0.11.0

func PersistPrepState(state *PrepState) (string, error)

PersistPrepState writes state to tmpdir and returns the prep_token.

func Polish added in v0.11.0

func Polish(g CommitGroup) (subject string, confidence float64)

Polish generates a heuristic commit subject for a CommitGroup. Returns (subject, confidence) where confidence >= 0.6 is safe to use without LLM review. Below 0.6, callers should mark the group for LLM polish.

Algorithm: classify files by extension family and directory prefix, then combine with a diff-stat action verb to produce a templated subject. Specificity rules:

  • test files → type=test, confidence 0.7
  • single file, known family → confidence depends on scope clarity
  • mixed / unknown → chore fallback at 0.3

func PolishGroup added in v0.11.0

func PolishGroup(g *CommitGroup, threshold float64) bool

PolishGroup is a convenience wrapper that applies Polish and updates g.SuggestedMsg when the result meets the confidence threshold. Returns whether the message was updated.

func RenderPlan added in v0.11.0

func RenderPlan(groups []CommitGroup) string

RenderPlan emits commit-execute.sh's native format:

COMMIT
MSG: feat(scope): subject
FILES: path1
FILES: path2
COMMIT
...
END

Release gate (--tag + go.mod bump) is left to the agent to apply before invoking commit-execute.sh; the tool reports it via dep_bumps, not the plan.

func ReviewFindingCount added in v0.13.0

func ReviewFindingCount(findings []Finding) int

ReviewFindingCount returns the number of findings requiring judgment.

func SaveCallsCache added in v0.7.0

func SaveCallsCache(cacheDir, hash string, callers SymbolCallers) error

SaveCallsCache writes a SymbolCallers map to disk atomically.

func ScoreComponentTotal added in v0.11.3

func ScoreComponentTotal(f RankedFile) int

ScoreComponentTotal returns the sum of tracked score components.

func StashArtifacts added in v0.11.0

func StashArtifacts(repoRoot string, artifacts []string)

StashArtifacts adds artifact paths to .gitignore and unstages them. Best-effort: I/O failures are swallowed (artifacts are advisory).

func StashArtifactsContext added in v0.12.0

func StashArtifactsContext(ctx context.Context, repoRoot string, artifacts []string)

StashArtifactsContext is StashArtifacts with caller cancellation.

func TreeSitterAvailable

func TreeSitterAvailable() bool

TreeSitterAvailable reports whether tree-sitter parsing is available.

func ValidateConventionalMsg added in v0.10.0

func ValidateConventionalMsg(msg string) error

ValidateConventionalMsg returns an error if the first line of msg does not match conventionalSubjectRe. Only the first line is validated; a multi-line body is allowed.

func ValidateReviewDecisions added in v0.13.0

func ValidateReviewDecisions(findings []Finding, decisions []ReviewDecision) error

ValidateReviewDecisions verifies that all REVIEW findings have one explicit verdict before commit finish executes the prepared plan.

func ValidateTag added in v0.10.0

func ValidateTag(tag string) error

ValidateTag returns an error if tag does not match the semver format.

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 AuditBriefReport added in v0.13.0

type AuditBriefReport struct {
	SchemaVersion  int                `json:"schema_version"`
	Root           string             `json:"root"`
	Risks          AuditRiskReport    `json:"risks"`
	Surface        AuditSurfaceReport `json:"surface"`
	Effects        AuditEffectReport  `json:"effects"`
	FirstReadQueue []AuditReadGroup   `json:"first_read_queue"`
	ReviewPlan     []AuditReviewLane  `json:"review_plan"`
}

AuditBriefReport is the single-pass audit prepass packet used by workflow tools that need deterministic local context without rebuilding the map for every audit subcommand.

type AuditCounts added in v0.13.0

type AuditCounts struct {
	Tracked       int `json:"tracked"`
	TrackedSource int `json:"tracked_source"`
	Untracked     int `json:"untracked"`
	UntrackedCode int `json:"untracked_code"`
	Ignored       int `json:"ignored"`
	IgnoredSource int `json:"ignored_source"`
}

AuditCounts records the path counts behind an AuditHygieneReport.

type AuditEffect added in v0.13.0

type AuditEffect struct {
	Kind     string `json:"kind"`
	Op       string `json:"op"`
	Path     string `json:"path"`
	Line     int    `json:"line"`
	Lane     string `json:"lane"`
	Evidence string `json:"evidence"`
}

AuditEffect is one static side-effect lead.

type AuditEffectFile added in v0.13.0

type AuditEffectFile struct {
	Path    string        `json:"path"`
	Score   int           `json:"score"`
	Lanes   []string      `json:"lanes"`
	Effects []AuditEffect `json:"effects"`
}

AuditEffectFile groups side-effect leads by source file.

type AuditEffectKind added in v0.13.0

type AuditEffectKind struct {
	Name    string   `json:"name"`
	Reason  string   `json:"reason"`
	Lane    string   `json:"lane"`
	Files   []string `json:"files"`
	Command string   `json:"command,omitempty"`
}

AuditEffectKind groups files that share a side-effect kind.

type AuditEffectReport added in v0.13.0

type AuditEffectReport struct {
	SchemaVersion int               `json:"schema_version"`
	Root          string            `json:"root"`
	Files         []AuditEffectFile `json:"files"`
	Kinds         []AuditEffectKind `json:"kinds"`
}

AuditEffectReport captures files with side effects and trust boundaries.

type AuditFileRisk added in v0.13.0

type AuditFileRisk struct {
	Path       string   `json:"path"`
	Language   string   `json:"language,omitempty"`
	Package    string   `json:"package,omitempty"`
	Score      int      `json:"score"`
	AuditScore int      `json:"audit_score"`
	Lanes      []string `json:"lanes,omitempty"`
	Reasons    []string `json:"reasons,omitempty"`
	Boundaries []string `json:"boundaries,omitempty"`
	ImportedBy int      `json:"imported_by,omitempty"`
	DependsOn  int      `json:"depends_on,omitempty"`
	Symbols    []string `json:"symbols,omitempty"`
}

AuditFileRisk summarizes why one file deserves audit attention.

type AuditHygieneReport added in v0.13.0

type AuditHygieneReport struct {
	SchemaVersion int          `json:"schema_version"`
	Root          string       `json:"root"`
	GitAvailable  bool         `json:"git_available"`
	Counts        AuditCounts  `json:"counts"`
	IgnoredSource []string     `json:"ignored_source,omitempty"`
	UntrackedCode []string     `json:"untracked_code,omitempty"`
	Issues        []AuditIssue `json:"issues,omitempty"`
}

AuditHygieneReport captures git/source-discovery facts that are cheap to compute but easy for a model to miss, especially tracked-vs-worktree drift.

func AuditHygiene added in v0.13.0

func AuditHygiene(ctx context.Context, root string) (AuditHygieneReport, error)

AuditHygiene inspects tracked, untracked, and ignored source files. It uses git when available so ignored source files remain visible to release audits.

type AuditIssue added in v0.13.0

type AuditIssue struct {
	ID       string `json:"id"`
	Severity string `json:"severity"`
	Lane     string `json:"lane"`
	Path     string `json:"path,omitempty"`
	Evidence string `json:"evidence"`
}

AuditIssue is a deterministic lead for a human or LLM audit pass. Issues are evidence, not final findings; callers should promote them only after checking source, docs, runtime behavior, or command output.

type AuditLane added in v0.13.0

type AuditLane struct {
	Name    string   `json:"name"`
	Reason  string   `json:"reason"`
	Files   []string `json:"files"`
	Command string   `json:"command,omitempty"`
}

AuditLane groups the files that triggered one repo-audit lane.

type AuditReadGroup added in v0.13.0

type AuditReadGroup struct {
	Group   string   `json:"group"`
	Lane    string   `json:"lane"`
	Reasons []string `json:"reasons"`
	Files   []string `json:"files"`
}

AuditReadGroup is a compact first-read queue grouped by the kind of risk a local static packet found.

func BuildAuditReadQueue added in v0.13.0

func BuildAuditReadQueue(risks AuditRiskReport, surface AuditSurfaceReport, effects AuditEffectReport) []AuditReadGroup

BuildAuditReadQueue turns audit packets into a deterministic file-read order grouped by why the files matter.

type AuditReviewLane added in v0.13.0

type AuditReviewLane struct {
	Lane   string   `json:"lane"`
	Group  string   `json:"group"`
	Files  []string `json:"files"`
	Gates  []string `json:"gates"`
	Verify []string `json:"verify"`
	Why    []string `json:"why"`
}

AuditReviewLane is a deterministic per-lane review obligation derived from the first-read queue: which files to cover, what gates to discharge, and how to verify. It carries no findings — only obligations implied by the static packets.

func BuildAuditReviewPlan added in v0.13.0

func BuildAuditReviewPlan(queue []AuditReadGroup, goDetected bool) []AuditReviewLane

BuildAuditReviewPlan projects the first-read queue into per-lane review obligations: it merges read groups sharing a lane, attaches deterministic gates/verify from the static table, and suppresses Go-specific verify commands when the target has no Go sources. It invents no findings.

type AuditRiskReport added in v0.13.0

type AuditRiskReport struct {
	SchemaVersion int             `json:"schema_version"`
	Root          string          `json:"root"`
	Files         []AuditFileRisk `json:"files"`
	Lanes         []AuditLane     `json:"lanes"`
}

AuditRiskReport is a compact packet for selecting deep-audit lanes before spending model context on full source reads.

type AuditSurfaceFile added in v0.13.0

type AuditSurfaceFile struct {
	Path  string            `json:"path"`
	Score int               `json:"score"`
	Kinds []string          `json:"kinds"`
	Hits  []AuditSurfaceHit `json:"hits"`
}

AuditSurfaceFile groups user-facing contract hits by source file.

type AuditSurfaceHit added in v0.13.0

type AuditSurfaceHit struct {
	Kind     string `json:"kind"`
	Name     string `json:"name,omitempty"`
	Path     string `json:"path"`
	Line     int    `json:"line"`
	Lane     string `json:"lane"`
	Evidence string `json:"evidence"`
}

AuditSurfaceHit is one static surface lead.

type AuditSurfaceReport added in v0.13.0

type AuditSurfaceReport struct {
	SchemaVersion       int                `json:"schema_version"`
	Root                string             `json:"root"`
	Files               []AuditSurfaceFile `json:"files"`
	Commands            []AuditSurfaceHit  `json:"commands,omitempty"`
	Flags               []AuditSurfaceHit  `json:"flags,omitempty"`
	EnvVars             []AuditSurfaceHit  `json:"env_vars,omitempty"`
	ConfigKeys          []AuditSurfaceHit  `json:"config_keys,omitempty"`
	SchemaFields        []AuditSurfaceHit  `json:"schema_fields,omitempty"`
	Routes              []AuditSurfaceHit  `json:"routes,omitempty"`
	Outputs             []AuditSurfaceHit  `json:"outputs,omitempty"`
	DependencyManifests []AuditSurfaceHit  `json:"dependency_manifests,omitempty"`
}

AuditSurfaceReport captures deterministic user-facing contracts that are useful audit entrypoints before a model starts reading source broadly.

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"`

	// ExcludePaths lists path glob patterns (relative to project root) to drop
	// at scan time. Any file whose relative path matches is excluded.
	// Example: ["internal/gen/*", "vendor/*"]
	ExcludePaths []string `yaml:"exclude_paths"`

	// IncludePaths lists path glob patterns (relative to project root) to keep
	// at scan time. When non-empty, only matching files are included.
	// Example: ["cmd/*", "internal/cli/*"]
	IncludePaths []string `yaml:"include_paths"`

	// FileOverrides maps relative-path globs to forced detail levels.
	// Accepted values: "full" (DetailLevel 2) and "omit" (DetailLevel -1).
	// Example:
	//   file_overrides:
	//     "cmd/main.go": full
	//     "internal/gen/**": omit
	FileOverrides map[string]string `yaml:"file_overrides"`
	// contains filtered or unexported fields
}

BlocklistConfig holds loaded-from-disk repomap settings that filter parsed symbols and file paths. 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) MatchFileOverride added in v0.11.1

func (c *BlocklistConfig) MatchFileOverride(rel string) (level int, ok bool)

MatchFileOverride reports whether a relative file path matches any file_overrides rule. Returns the forced DetailLevel (2 or -1) and true on match; 0 and false otherwise. A nil receiver returns (0, false) — no overrides. Globs use path.Match semantics; patterns containing "**" match any path with the corresponding prefix (everything before the first "**").

func (*BlocklistConfig) ShouldExcludePath added in v0.11.1

func (c *BlocklistConfig) ShouldExcludePath(rel string) bool

ShouldExcludePath reports whether rel matches any ExcludePaths pattern. rel must be a slash-separated path relative to the project root. A nil receiver returns false (nothing excluded).

func (*BlocklistConfig) ShouldIncludePath added in v0.11.1

func (c *BlocklistConfig) ShouldIncludePath(rel string) bool

ShouldIncludePath reports whether rel passes the IncludePaths filter. When IncludePaths is empty, all paths are included (returns true). When non-empty, returns true only if rel matches at least one pattern. A nil receiver returns true (nothing excluded).

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 CacheStatus added in v0.12.0

type CacheStatus struct {
	CachePath    string     `json:"cache_path"`
	Exists       bool       `json:"exists"`
	Usable       bool       `json:"usable"`
	Stale        bool       `json:"stale"`
	Reason       string     `json:"reason,omitempty"`
	Root         string     `json:"root,omitempty"`
	BuiltAt      *time.Time `json:"built_at,omitempty"`
	TrackedFiles int        `json:"tracked_files,omitempty"`
	SavedHead    string     `json:"saved_head,omitempty"`
	CurrentHead  string     `json:"current_head,omitempty"`
	GitRoot      bool       `json:"git_root,omitempty"`
	Version      int        `json:"version,omitempty"`
}

CacheStatus describes the usability and freshness of one disk cache entry.

func InspectCache added in v0.12.0

func InspectCache(ctx context.Context, root, cacheDir string) CacheStatus

InspectCache reports whether the cache for root is present, loadable, and fresh.

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.

type CallsStats added in v0.7.0

type CallsStats struct {
	OK      int
	Timeout int
	Error   int
}

CallsStats holds counters from a call-expansion run.

type Candidate added in v0.11.0

type Candidate struct {
	File        string `json:"file"`
	Line        int    `json:"line"`
	Kind        string `json:"kind"`                  // go_lint | go_vet | go_complexity | ts_lint | py_lint
	Hint        string `json:"hint"`                  // human-readable finding
	Replacement string `json:"replacement,omitempty"` // "" means no auto-fix available
}

Candidate is one code-quality finding from the simplify detector. Replacement is empty when the detector does not provide an auto-fix (the current shell script never does — it only reports).

func ApplyCandidates added in v0.11.0

func ApplyCandidates(ctx context.Context, repoRoot string, candidates []Candidate) (applied, skipped []Candidate, err error)

ApplyCandidates attempts to apply each candidate's Replacement at file:line. Candidates with an empty Replacement are always marked skipped (the current simplify-detect.sh never provides one — findings are informational only).

For candidates that do carry a Replacement, the function reads the file, verifies the line still matches the expected content, and rewrites it atomically via temp+rename. Mismatches are skipped (not errors) to be idempotent across re-runs.

func RunSimplifyDetect added in v0.11.0

func RunSimplifyDetect(ctx context.Context, repoRoot string) ([]Candidate, error)

RunSimplifyDetect execs simplify-detect.sh and parses its section output into a []Candidate. Returns nil candidates (not an error) when the script is absent, exits non-zero, or finds nothing.

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"`
	BreakingCount  int            `json:"breaking_count,omitempty"` // count of groups with Breaking=true
	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
	Verb         string            `json:"verb,omitempty"` // "add" | "remove" | "update" — dominant git operation
	SuggestedMsg string            `json:"suggested_msg"`
	Files        []string          `json:"files"`
	Rationale    string            `json:"rationale"`              // why these files cluster (backward-compat string)
	Confidence   float64           `json:"confidence"`             // 0.0–1.0
	Breaking     bool              `json:"breaking,omitempty"`     // true if any constituent file has a breaking-change delta
	DiffOffsets  map[string][2]int `json:"diff_offsets,omitempty"` // file -> [byte_start, byte_end] in refs.diffs
	Evidence     []EdgeEvidence    `json:"evidence,omitempty"`     // per-edge clustering evidence
}

CommitGroup is one proposed commit. The agent ratifies (confidence >= 0.75) or inspects refs.diffs at DiffOffsets to refine grouping/messaging.

func ConsolidateGroups added in v0.11.0

func ConsolidateGroups(groups []CommitGroup) []CommitGroup

ConsolidateGroups enforces the cap-3/fold-riders/merge-smallest rules from commit-agent.md §93-106. It is a pure function: input groups are not mutated.

Algorithm (deterministic — sort before every decision):

  1. Sort groups by file count desc, then ID alpha (stability).
  2. If ≤3 groups, return as-is.
  3. "Rider" = group with 1-2 files. Fold each rider into the largest group that shares its top-level directory. Riders with no match are left alone.
  4. If still >3 groups, merge the two smallest (by file count, then ID) into the smaller one's entry, keeping the larger group's SuggestedMsg.
  5. Repeat step 4 until ≤3.

type CommitRecord added in v0.10.0

type CommitRecord struct {
	SHA     string `json:"sha"`
	Message string `json:"message"`
}

CommitRecord is one landed commit.

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 Confidence added in v0.13.0

type Confidence string

Confidence represents the reliability tier of a score component.

const (
	ConfidenceConfirmed  Confidence = "confirmed"  // LSP/gopls-verified references
	ConfidenceStructural Confidence = "structural" // parsed structure / import graph
	ConfidenceLexical    Confidence = "lexical"    // by-name string match, may be coincidental
	ConfidenceContextual Confidence = "contextual" // query- or caller-dependent
)

type Config

type Config struct {
	MaxTokens      int      // token budget for output (default: 1024)
	MaxTokensNoCtx int      // budget when no files in conversation (default: 2048)
	Intent         string   // optional BM25 query for task-aware ranking
	ConsumedPaths  []string // optional: paths the caller has already read — these are downranked
	SymbolRefs     bool     // optional approximate cross-language symbol reference scoring
	Explain        bool     // append per-file confidence-tier score breakdown to text output
	IncludeTests   bool     // rank test files at full weight (default: demoted)
}

Config holds repomap configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

type ContextOptions added in v0.12.0

type ContextOptions struct {
	Kind           string
	File           string
	MaxSourceLines int
}

ContextOptions controls symbol context extraction.

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 EdgeEvidence added in v0.9.0

type EdgeEvidence struct {
	A      string  `json:"a"`      // first file path
	B      string  `json:"b"`      // second file path
	Weight float64 `json:"weight"` // edge weight (1.0 test-pair, 0.8/0.6 symbol-dep, 0.5 co-change, 0.3 sibling)
	Reason string  `json:"reason"` // "test-pair" | "symbol-dep" | "co-change" | "sibling"
}

EdgeEvidence records one weighted edge that contributed to a group's clustering, so agents can inspect or override the grouping logic without pattern-matching on the Rationale string.

type ExecuteOptions added in v0.10.0

type ExecuteOptions struct {
	Root             string // repo root (default ".")
	PlanFile         string // path to CommitAnalysis JSON (required)
	Push             bool   // git push origin <branch> --follow-tags
	Tag              string // annotated tag to create at HEAD (semver)
	NoRelease        bool   // skip gh release create
	ReleaseNotesFrom string // --notes-start-tag for gh release create
	DryRun           bool   // print actions, mutate nothing
	JSON             bool   // machine-readable result on stdout
	SkipFix          bool   // bypass consolidation pass
}

ExecuteOptions configures a commit-execute run.

type ExecuteResult added in v0.10.0

type ExecuteResult struct {
	Branch     string          `json:"branch"`
	Commits    []CommitRecord  `json:"commits"`
	Tag        *string         `json:"tag"`
	Pushed     bool            `json:"pushed"`
	ReleaseURL *string         `json:"release_url"`
	Postflight PostflightCheck `json:"postflight"`
}

ExecuteResult is the JSON-serializable result of a successful execute run.

func ExecuteCommit added in v0.10.0

func ExecuteCommit(ctx context.Context, opts ExecuteOptions) (*ExecuteResult, error)

ExecuteCommit loads the plan, validates it, consolidates groups, then executes git add/commit per group, then push/tag/release.

func ExecuteFromGroups added in v0.11.0

func ExecuteFromGroups(ctx context.Context, repoRoot string, groups []CommitGroup, opts ExecuteOptions) (*ExecuteResult, error)

ExecuteFromGroups runs the commit pipeline directly from a validated slice of CommitGroups, bypassing the plan-file load path. Intended for commit finish, which already has groups in memory. opts.PlanFile and opts.SkipFix are ignored.

type ExplainResult added in v0.11.3

type ExplainResult struct {
	File            StructuredFile    `json:"file"`
	Score           int               `json:"score"`
	ScoreComponents map[string]int    `json:"score_components,omitempty"`
	ComponentTotal  int               `json:"component_total"`
	DetailLevel     int               `json:"detail_level"`
	OmittedReason   string            `json:"omitted_reason,omitempty"`
	ScoreByTier     map[string]int    `json:"score_by_tier,omitempty"`    // tier label -> summed subtotal
	ComponentTiers  map[string]string `json:"component_tiers,omitempty"`  // component key -> tier label
	ParseMethod     string            `json:"parse_method,omitempty"`     // parser tier: go_ast/tree_sitter/ctags/regex
	ParseConfidence string            `json:"parse_confidence,omitempty"` // confidence tier of ParseMethod
}

ExplainResult describes why one file ranked and rendered the way it did.

type FileInfo

type FileInfo struct {
	Path     string // relative to project root
	Language string // language ID
}

FileInfo holds a discovered file with its language.

func ScanFiles

func ScanFiles(ctx context.Context, root string, cfg *BlocklistConfig) ([]FileInfo, error)

ScanFiles discovers source files in the given directory. Falls back to directory walk if not inside a git repo or if git ls-files fails. cfg may be nil — nil means no path filtering.

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   // "go_ast", "tree_sitter", "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

func ParseWithCtags(ctx context.Context, root string, files []FileInfo) ([]*FileSymbols, error)

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.

func ApplyFixFindings added in v0.11.0

func ApplyFixFindings(ctx context.Context, repoRoot string, findings []Finding) (applied, skipped []Finding, err error)

ApplyFixFindings applies the substitution table to all findings whose DefaultAction is "fix". Each line is rewritten in place using an atomic temp+rename write. Idempotent: if the placeholder is already present at that line, the finding is marked skipped.

Returns the applied and skipped findings, or an error on I/O failure.

func LoadFindings added in v0.11.0

func LoadFindings(path string) ([]Finding, error)

LoadFindings reads a findings JSON file. Returns nil, nil when absent.

type ImpactResult added in v0.11.3

type ImpactResult struct {
	File            StructuredFile `json:"file"`
	Imports         []string       `json:"imports,omitempty"`
	ImportedBy      []string       `json:"imported_by,omitempty"`
	Tests           []string       `json:"tests,omitempty"`
	ExportedSymbols []Symbol       `json:"exported_symbols,omitempty"`
	Boundaries      []string       `json:"boundaries,omitempty"`
	ScoreComponents map[string]int `json:"score_components,omitempty"`
	ParseMethod     string         `json:"parse_method,omitempty"`
}

ImpactResult is the factual blast-radius summary for one file.

type IntentScorer added in v0.11.1

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

IntentScorer holds the corpus index and scores files against a query.

func NewIntentScorer added in v0.11.1

func NewIntentScorer(ranked []RankedFile) *IntentScorer

NewIntentScorer builds the per-file keyword index from ranked files.

func (*IntentScorer) Score added in v0.11.1

func (s *IntentScorer) Score(ranked []RankedFile, query string) []RankedFile

Score re-ranks files in place by multiplying base scores with BM25 relevance. Returns the same slice (mutated) sorted by final_score descending.

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 New

func New(root string, cfg Config) *Map

New creates a new Map for the given project root.

func (*Map) AuditBrief added in v0.13.0

func (m *Map) AuditBrief(ctx context.Context, limit int) (AuditBriefReport, error)

AuditBrief computes risks, surface, effects, and a grouped first-read queue from one built Map.

func (*Map) AuditEffects added in v0.13.0

func (m *Map) AuditEffects(ctx context.Context, limit int) (AuditEffectReport, error)

AuditEffects extracts side-effect and trust-boundary packets from source.

func (*Map) AuditRisks added in v0.13.0

func (m *Map) AuditRisks(limit int) AuditRiskReport

AuditRisks converts a built map into deterministic audit-lane packets.

func (*Map) AuditSurface added in v0.13.0

func (m *Map) AuditSurface(ctx context.Context, limit int) (AuditSurfaceReport, error)

AuditSurface extracts command, flag, env, config, route, and output surfaces.

func (*Map) Build

func (m *Map) Build(ctx context.Context) error

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

func (m *Map) BuiltAt() time.Time

BuiltAt returns the time of the last successful build, or zero time if never built.

func (*Map) Config added in v0.7.0

func (m *Map) Config() Config

Config returns the configuration this Map was created with.

func (*Map) Context added in v0.12.0

func (m *Map) Context(query string, opts ContextOptions) (SymbolContext, error)

Context returns a bounded context bundle for the best matching symbol.

func (*Map) Explain added in v0.11.3

func (m *Map) Explain(relPath string) (ExplainResult, error)

Explain returns score and budget evidence for relPath.

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) Impact added in v0.11.3

func (m *Map) Impact(relPath string) (ImpactResult, error)

Impact returns a deterministic local blast-radius summary for relPath.

func (*Map) LoadCache

func (m *Map) LoadCache(cacheDir string) bool

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

func (m *Map) LoadCacheIncremental(ctx context.Context, cacheDir string) (bool, []string)

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) OrphanCandidates added in v0.13.0

func (m *Map) OrphanCandidates(ctx context.Context, q RefsQuerier) (OrphanReport, error)

OrphanCandidates returns exported symbols with zero inbound references (ZeroRefs) and exported symbols referenced only by *_test.go files (TestOnlyRefs). Entry points (RankedFile.Tag == "entry") are excluded. The caller owns the LSP lifecycle.

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

func (m *Map) SaveCache(cacheDir string) error

SaveCache writes the current map state to disk.

func (*Map) SaveCacheContext added in v0.12.0

func (m *Map) SaveCacheContext(ctx context.Context, cacheDir string) error

SaveCacheContext writes the current map state to disk with caller cancellation.

func (*Map) SetCacheDir

func (m *Map) SetCacheDir(dir string)

SetCacheDir enables disk caching. Build() will save to this directory.

func (*Map) Stale

func (m *Map) Stale() bool

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

func (m *Map) String() 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

func (m *Map) StringCompact() string

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

func (m *Map) StringDetail() string

StringDetail returns the full detailed map output with signatures and struct fields.

func (*Map) StringLines

func (m *Map) StringLines() string

StringLines returns the source-line format showing actual code definitions.

func (*Map) StringVerbose

func (m *Map) StringVerbose() string

StringVerbose returns the full verbose map output (all symbols, no summarization).

func (*Map) StringXML

func (m *Map) StringXML() string

StringXML returns the structured XML format.

func (*Map) StructuredJSON added in v0.11.3

func (m *Map) StructuredJSON() ([]byte, error)

StructuredJSON returns the structured map encoded as indented JSON.

func (*Map) StructuredOutput added in v0.11.3

func (m *Map) StructuredOutput() StructuredOutput

StructuredOutput returns a structured snapshot of the built map.

func (*Map) StructuredOutputForRanked added in v0.11.3

func (m *Map) StructuredOutputForRanked(ranked []RankedFile) StructuredOutput

StructuredOutputForRanked returns structured output for an adjusted ranked slice while reusing this Map's config, root, diagnostics, and file overrides.

type OrphanCandidate added in v0.13.0

type OrphanCandidate struct {
	Name     string `json:"name"`
	Kind     string `json:"kind"`
	Receiver string `json:"receiver,omitempty"`
	File     string `json:"file"`
	Line     int    `json:"line"`
}

OrphanCandidate is one exported symbol with zero inbound non-test references.

type OrphanReport added in v0.13.0

type OrphanReport struct {
	Caveat       string            `json:"caveat"`
	ZeroRefs     []OrphanCandidate `json:"zero_refs"`
	TestOnlyRefs []OrphanCandidate `json:"test_only_refs"`
}

OrphanReport buckets exported symbols by inbound-reference status.

type PostflightCheck added in v0.10.0

type PostflightCheck struct {
	Clean     bool `json:"clean"`
	Convent   bool `json:"conventional"`
	TagLocal  bool `json:"tag_local"`
	TagRemote bool `json:"tag_remote"`
	Release   bool `json:"release"`
}

PostflightCheck records the result of each postflight verification. Checks that are not applicable (e.g. TagRemote when --push was not set) are set to true so callers can use postflightOK() without special-casing.

type PrepLowConf added in v0.11.0

type PrepLowConf struct {
	GroupID   string   `json:"group_id"`
	Files     []string `json:"files"`
	DiffSlice string   `json:"diff_slice"`
}

PrepLowConf is one group requiring LLM subject polish (capped at 3; diff_slice ≤500 chars).

type PrepPayload added in v0.11.0

type PrepPayload struct {
	Preflight       PrepPreflight    `json:"preflight"`
	ModeHint        string           `json:"mode_hint"` // "FULL" | "LOCAL"
	PrepToken       string           `json:"prep_token"`
	Status          string           `json:"status"` // "ready" | "needs_judgment" | "abort"
	AbortReason     string           `json:"abort_reason,omitempty"`
	Plan            []PrepPlanGroup  `json:"plan"`
	Review          []PrepReviewItem `json:"review"`
	LowConfSubjects []PrepLowConf    `json:"low_conf_subjects"`
	ReleaseRecipe   bool             `json:"release_recipe"`
	SessionRepos    []string         `json:"session_repos"`
	ReleaseGate     *PrepReleaseGate `json:"release_gate,omitempty"`
}

PrepPayload is the JSON document emitted by `repomap commit prep --json`.

type PrepPlanGroup added in v0.11.0

type PrepPlanGroup struct {
	Type       string   `json:"type"`
	Scope      string   `json:"scope"`
	Subject    string   `json:"subject"`
	Files      []string `json:"files"`
	Confidence float64  `json:"confidence"`
}

PrepPlanGroup is one consolidated commit in the plan.

func GroupsToPlan added in v0.11.0

func GroupsToPlan(groups []CommitGroup) []PrepPlanGroup

GroupsToPlan converts CommitGroups to PrepPlanGroups for the payload.

type PrepPreflight added in v0.11.0

type PrepPreflight struct {
	Branch    string `json:"branch"`
	Working   string `json:"working"`
	Remote    string `json:"remote"`
	Unpushed  string `json:"unpushed"`
	LatestTag string `json:"latest_tag"`
	GHAuth    string `json:"gh_auth"`
}

PrepPreflight mirrors the cpt.md context block fields.

type PrepReleaseGate added in v0.11.0

type PrepReleaseGate struct {
	Applied []any `json:"applied"`
	BuildOK bool  `json:"build_ok"`
}

PrepReleaseGate holds the result of running the release gate.

func RunReleaseGate added in v0.11.0

func RunReleaseGate(repoRoot string) *PrepReleaseGate

RunReleaseGate shells out to release-gate.sh and returns a summary. build_ok=true when the script exits 0 or is absent.

func RunReleaseGateContext added in v0.12.0

func RunReleaseGateContext(ctx context.Context, repoRoot string) *PrepReleaseGate

RunReleaseGateContext is RunReleaseGate with caller cancellation.

type PrepReviewItem added in v0.11.0

type PrepReviewItem struct {
	ID            string `json:"id"`
	File          string `json:"file"`
	Line          int    `json:"line"`
	Snippet       string `json:"snippet"`
	Detail        string `json:"detail"`
	DefaultAction string `json:"default_action"`
	ByteOffset    int    `json:"byte_offset"`
	ByteLength    int    `json:"byte_length"`
}

PrepReviewItem is one finding that needs LLM judgment (capped at 5; snippet ≤200 chars).

func BuildReviewItems added in v0.11.0

func BuildReviewItems(findings []Finding, maxItems int) []PrepReviewItem

BuildReviewItems extracts REVIEW findings into PrepReviewItems, capped at maxItems.

type PrepState added in v0.11.0

type PrepState struct {
	Analysis      *CommitAnalysis  `json:"analysis"`
	Plan          []CommitGroup    `json:"plan"`
	SessionRepos  []string         `json:"session_repos"`
	ReleaseRecipe bool             `json:"release_recipe"`
	ReleaseGate   *PrepReleaseGate `json:"release_gate,omitempty"`
	RepoRoot      string           `json:"repo_root"`
}

PrepState is persisted to tmpdir and loaded by `commit finish`.

func LoadPrepState added in v0.11.0

func LoadPrepState(token string) (*PrepState, error)

LoadPrepState reads a persisted PrepState from tmpdir by token.

type RankedFile

type RankedFile struct {
	*FileSymbols
	Score           int            // higher = more important
	ScoreComponents map[string]int `json:"score_components,omitempty"` // stable score deltas by heuristic
	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, cfg *BlocklistConfig) []RankedFile

func BudgetFilesCompact added in v0.7.0

func BudgetFilesCompact(ranked []RankedFile, maxTokens int, cfg *BlocklistConfig) []RankedFile

BudgetFilesCompact assigns DetailLevel to each RankedFile using compactCost estimates, matching the lean orientation renderer (path + exported symbol names only). cfg may be nil — nil means no file-level overrides (backward compatible). 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).

func OrphanQuerier added in v0.13.0

func OrphanQuerier(root string) (q RefsQuerier, shutdown func(context.Context), err error)

OrphanQuerier constructs an in-process gopls querier and its Manager. The caller MUST call shutdown(ctx) when done. Errors if gopls is absent.

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 RepoStatus added in v0.11.0

type RepoStatus struct {
	Repo  string   `json:"repo"`
	Dirty []string `json:"dirty"` // lines from git status --porcelain; empty = clean
}

RepoStatus records the porcelain status of a single repo.

func CrossRepoVerify added in v0.11.0

func CrossRepoVerify(ctx context.Context, sessionRepos []string) (results []RepoStatus, allClean bool)

CrossRepoVerify checks git porcelain status across multiple repos.

type ReviewDecision added in v0.11.0

type ReviewDecision struct {
	ID          string `json:"id"`          // matches Finding identity (file+line)
	Verdict     string `json:"verdict"`     // "safe" | "unsafe"
	Replacement string `json:"replacement"` // applied when verdict="unsafe"
}

ReviewDecision is one LLM verdict for a REVIEW finding.

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 SourceLine added in v0.12.0

type SourceLine struct {
	Number int    `json:"number"`
	Text   string `json:"text"`
}

SourceLine is one line of source extracted for a symbol.

type StructuredConfig added in v0.11.3

type StructuredConfig struct {
	MaxTokens      int      `json:"max_tokens"`
	MaxTokensNoCtx int      `json:"max_tokens_no_ctx"`
	Intent         string   `json:"intent,omitempty"`
	ConsumedPaths  []string `json:"consumed_paths,omitempty"`
	SymbolRefs     bool     `json:"symbol_refs,omitempty"`
}

StructuredConfig records the inputs that materially affect map selection.

type StructuredFile added in v0.11.3

type StructuredFile struct {
	Path            string             `json:"path"`
	Language        string             `json:"language,omitempty"`
	Package         string             `json:"package,omitempty"`
	ImportPath      string             `json:"import_path,omitempty"`
	ParseMethod     string             `json:"parse_method,omitempty"`
	Score           int                `json:"score"`
	ScoreComponents map[string]int     `json:"score_components,omitempty"`
	DetailLevel     int                `json:"detail_level"`
	ImportedBy      int                `json:"imported_by,omitempty"`
	DependsOn       int                `json:"depends_on,omitempty"`
	Untested        bool               `json:"untested,omitempty"`
	Boundaries      []string           `json:"boundaries,omitempty"`
	Imports         []string           `json:"imports,omitempty"`
	Symbols         []StructuredSymbol `json:"symbols,omitempty"`
	OmittedReason   string             `json:"omitted_reason,omitempty"`
}

StructuredFile is a machine-readable file block.

type StructuredOutput added in v0.11.3

type StructuredOutput struct {
	SchemaVersion int              `json:"schema_version"`
	Root          string           `json:"root"`
	Totals        StructuredTotals `json:"totals"`
	Config        StructuredConfig `json:"config"`
	Warnings      []string         `json:"warnings,omitempty"`
	Files         []StructuredFile `json:"files"`
}

StructuredOutput is the machine-readable repository map format.

func BuildStructuredOutput added in v0.11.3

func BuildStructuredOutput(root string, cfg Config, ranked []RankedFile, tsAvailable, ctagsAvailable bool, blocklist *BlocklistConfig) StructuredOutput

BuildStructuredOutput builds the machine-readable output for an already-ranked file list. Callers that apply extra score passes, such as --calls, can pass that adjusted ranked slice without mutating Map state.

type StructuredSymbol added in v0.11.3

type StructuredSymbol struct {
	Name        string   `json:"name"`
	Kind        string   `json:"kind"`
	Signature   string   `json:"signature,omitempty"`
	Receiver    string   `json:"receiver,omitempty"`
	Exported    bool     `json:"exported,omitempty"`
	Dead        bool     `json:"dead,omitempty"`
	Line        int      `json:"line,omitempty"`
	EndLine     int      `json:"end_line,omitempty"`
	ParamCount  int      `json:"param_count,omitempty"`
	ResultCount int      `json:"result_count,omitempty"`
	Implements  []string `json:"implements,omitempty"`
	Doc         string   `json:"doc,omitempty"`
}

StructuredSymbol is the machine-readable symbol shape with stable JSON keys.

type StructuredTotals added in v0.11.3

type StructuredTotals struct {
	Files   int `json:"files"`
	Symbols int `json:"symbols"`
}

StructuredTotals records unbudgeted repository totals.

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)
	Dead        bool     // true when exported but no file in the scanned tree imports this file
	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.

func (Symbol) HasFields

func (s Symbol) HasFields() bool

HasFields reports whether the symbol is a struct or interface with populated field/method info in its Signature.

func (Symbol) LineSpan

func (s Symbol) LineSpan() int

LineSpan returns the number of lines the symbol spans, or 0 if unknown.

type SymbolCallers added in v0.7.0

type SymbolCallers map[string][]Location

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 SymbolContext added in v0.12.0

type SymbolContext struct {
	Query      string        `json:"query"`
	Match      SymbolMatch   `json:"match"`
	Ambiguous  []SymbolMatch `json:"ambiguous,omitempty"`
	Callers    []Location    `json:"callers,omitempty"`
	Source     []SourceLine  `json:"source,omitempty"`
	Truncated  bool          `json:"truncated,omitempty"`
	Impact     ImpactResult  `json:"impact"`
	SourceNote string        `json:"source_note,omitempty"`
}

SymbolContext is a bounded, symbol-centered context bundle.

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.

type VerifyResult added in v0.11.0

type VerifyResult struct {
	Mode              string `json:"mode"` // "local" | "full"
	OK                bool   `json:"ok"`
	LastCommitSubject string `json:"last_commit_subject,omitempty"` // local mode
	Tag               string `json:"tag,omitempty"`                 // full mode
	ReleaseURL        string `json:"release_url,omitempty"`         // full mode
	FailureDetail     string `json:"failure_detail,omitempty"`
}

VerifyResult records the outcome of a self-verify run.

func SelfVerify added in v0.11.0

func SelfVerify(ctx context.Context, repoRoot, mode string) (VerifyResult, error)

SelfVerify performs mode-aware verification of the current repo.

Directories

Path Synopsis
cmd
repomap command
internal
cli
lsp
Package lsp provides an LSP client for code intelligence.
Package lsp provides an LSP client for code intelligence.
serve
Package serve implements the NDJSON JSON-RPC 2.0 framing layer for `repomap serve`.
Package serve implements the NDJSON JSON-RPC 2.0 framing layer for `repomap serve`.

Jump to

Keyboard shortcuts

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