repomap

package module
v0.25.0 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 50 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, fast Go go/ast mapping with on-demand go/packages/go/types semantics, tree-sitter, ctags/regex fallback, import graphs, and BM25 intent ranking. It does not call an LLM.

Why LLMs Should Use Repomap

Outputs below are abridged; paths, counts, scores, and timestamps vary by repository.

  1. Spend context on the code that matters. Repomap ranks files and fits their most useful symbols, signatures, and documentation into a bounded token budget.

    repomap -t 256 .
    
    ## Repository Map · enriched (244 files, 1189 symbols, ~248 tokens)
    
    ### Flow
    entry: cmd/repomap/main.go
    spine: repomap.go, types.go, calls.go, audit_packets.go
    
    repomap.go [imported by 33]
      3 types, 2 funcs, 16 methods, 1 vars · Config, GoDiagnostic
    ...
    
  2. Orient before reading broadly. repomap brief combines repository identity, agent instructions, verification commands, Git state, likely ownership, and the ranked map.

    repomap brief .
    
    Good evening, agent — here's your briefing.
    
    # repomap — Go module
      module github.com/dotcommander/repomap
    
    ## Verify
      build: go build ./...
      test:  go test ./...
      vet:   go vet ./...
    
    ## State
      branch: main   dirty: ...
    
    ## Rules
      conventions: CLAUDE.md — read before editing
    
    ## Map
    ## Repository Map · enriched (...)
    
  3. Focus the map on the current task. --intent reranks paths, packages, imports, symbols, and signatures against the work the LLM is about to perform.

    repomap --intent "harden CLI output" -t 256 .
    
    ## Repository Map · enriched (...)
    
    ### Flow
    entry: cmd/repomap/main.go
    spine: repomap.go, structured_json.go, audit_packets.go,
    ...
    
  4. Build an implementation packet. task composes task-relevant owners, symbols, source, consumers, callers, tests, effects, rules, dirty overlap, and verification commands within one complete-output budget.

    repomap task "harden CLI output" -t 4096 .
    

    Abridged output:

    # Task: harden CLI output
    
    Root: /checkout
    Budget: 1638/4096 tokens
    
    ## Targets
    - internal/cli/render.go confidence=high package=cli risk=medium parse=go_ast
      evidence path: internal/cli/render.go
      symbol function renderStandard lines=43-61 (...) error
      relationship consumer internal/cli/root.go (syntactic)
      relationship test internal/cli/root_test.go (exact)
      source renderStandard:
        43: func renderStandard(...) error {
        ...
    
    ## Verify
    - go test ./internal/cli
    

    The same report drives schema-versioned JSON. Selected fields:

    repomap task "harden CLI output" --json .
    
    {
      "schema_version": 1,
      "root": "/checkout",
      "goal": "harden CLI output",
      "budget": {"max_tokens": 4096, "used_tokens": 1638},
      "selection": {"strategy": "structural owner, task relevance, score, path", "limit": 6, "selected": 1},
      "rules": [{"path": "AGENTS.md"}],
      "related_changes": [],
      "targets": [{"path": "internal/cli/render.go", "confidence": "high"}],
      "read_next": [],
      "verify_commands": ["go test ./internal/cli"],
      "follow_up_commands": [],
      "diagnostics": [],
      "truncations": []
    }
    

    Confidence is deterministic selection strength, not a correctness claim. Relationship provenance is exact for semantic evidence, syntactic for parsed source relationships, and heuristic for naming or adjacency. Generated follow-ups suggest an exact larger-budget rerun; fixed field caps may still require direct inspection. Pass --consumed=PATHS to retain known owners and relationships while spending source budget on unread files.

  5. Avoid rereading known files. --consumed downranks files already in context and raises their importers, helping the next map add new information.

    repomap --consumed audit_packets.go -t 256 .
    
    ## Repository Map · enriched (...)
    
    ### Flow
    entry: cmd/repomap/main.go
    spine: repomap.go, types.go, calls.go,
           structured_json.go
    ...
    
  6. Retrieve a coherent symbol packet. repomap context returns the best symbol match, bounded source, ambiguity hints, caller context, and owning-file impact facts.

    repomap context AuditBrief --max-source-lines 8 .
    
    audit_brief.go:57  method  (*Map) AuditBrief(ctx context.Context, limit int) (AuditBriefReport, error)
    also matched:
      audit_brief.go:13  struct  AuditBriefReport{...}
    
    source:
      57 | func (m *Map) AuditBrief(ctx context.Context, limit int) (...) {
      58 |     risks := m.AuditRisks(limit)
         ...
    audit_brief.go
      parsed: go_ast
      risk: high
      affected packages: cli, repomap
      check next: inspect importer internal/cli/audit.go
    
  7. Estimate change risk before editing. repomap impact reports imports, reverse imports, tests, exported symbols, boundaries, risk, likely test commands, and what to inspect next.

    repomap impact audit_packets.go --markdown
    
    # Impact: `audit_packets.go`
    
    - **Risk:** high
    - **Parsed:** go_ast
    - **Score:** 166
    
    ## Affected Packages
    - `cli`
    - `repomap`
    
    ## Imported By
    - `internal/cli/audit.go`
    - `internal/cli/brief.go`
    ...
    
  8. Trace code with semantic evidence. Go caller expansion uses semantic analysis, while lsp refs, lsp def, lsp hover, and lsp symbols expose installed language-server results.

    repomap context AuditBrief --calls --calls-limit 2 --max-source-lines 4 .
    
    audit_brief.go:57  method  (*Map) AuditBrief(...)
    
    source:
      57 | func (m *Map) AuditBrief(...) (...) {
      58 |     risks := m.AuditRisks(limit)
         ...
    
    callers:
      internal/cli/audit.go:96:0
    
  9. Start audits from deterministic leads. Audit packets identify risks, public surfaces, side effects, trust boundaries, first-read queues, evidence quality, and every truncation.

    repomap audit brief --json --limit 1 . |
      jq '{schema_version, risk_files: (.risks.files|length),
           surface_files: (.surface.files|length),
           effect_files: (.effects.files|length),
           first_read_groups: (.first_read_queue|length)}'
    
    {
      "schema_version": 3,
      "risk_files": 1,
      "surface_files": 1,
      "effect_files": 1,
      "first_read_groups": 11
    }
    
  10. Integrate without scraping prose. Schema-versioned JSON, XML, line output, artifacts, and JSON-RPC let agents consume stable machine-readable results.

    repomap --json-structured -t 64 . |
      jq '{schema_version, files: [.files[0] |
           {path, score, detail_level, omitted_reason}]}'
    
    {
      "schema_version": 2,
      "totals": {"files": 244, "symbols": 1189},
      "selection": {"total_files": 244, "total_symbols": 1189, "selected_files": 1, "selected_symbols": 3, "omitted_files": 243, "omitted_symbols": 1186, "omitted_reason": "complete-output token budget"},
      "files": [
        {
          "path": "repomap.go",
          "score": 195,
          "detail_level": 0,
          "omitted_reason": null
        }
      ]
    }
    
  11. Keep repository analysis local and repeatable. Repomap sends no code to an LLM, and disk caching plus repomap serve make repeated queries cheaper without changing the evidence source.

    repomap cache warm . --cache-dir /tmp/repomap-cache
    
    cache: fresh
      path: /tmp/repomap-cache/repomap-<root-hash>.json
      reason: fresh
      built: <timestamp>
      tracked files: 244
      saved HEAD: 28cce277...
      current HEAD: 28cce277...
    

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 task "debug caller expansion timeouts" .

Build a bounded implementation-decision packet instead of chaining map, impact, context, and audit-effect queries manually.

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

Boot an Agent with brief
repomap brief

One call answers everything an agent needs at session start: a time-aware greeting, module identity, the project's verify chain (build/test/vet, plus lint only when a golangci config exists), current git state (branch, changed files, recent commits), any agent-convention rules it should read first (CLAUDE.md, AGENTS.md, .cursorrules), and the enriched repo map capped to the top-ranked files.

For multi-package repos the digest ends with a Likely ownership routing section that clusters the top files by owning directory (e.g. internal/cli/ — cli (38 files: Execute, Run, Write)), so the agent knows which packages own the surface before opening anything. It is omitted entirely for flat or single-area repos so it never adds noise.

repomap brief ./other-repo     # defaults to the current directory
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
repomap impact ranker.go --markdown
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]
  risk: medium
  check next: inspect importer internal/cli/root.go; run or inspect likely test ranker_test.go
  likely test commands: go test .
  read next:
    - ranker.go:49-92 inspect exported symbol RankFiles

Use --markdown for a compact human handoff and --json for tooling. impact reports local facts plus deterministic workflow guidance: imports, reverse imports, nearby tests, exported symbols, boundaries, parser backend, score components, risk level, next files to inspect, likely Go test commands, and bounded read_next source ranges.

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 callers from the in-process Go semantic graph.

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": 2,
  "totals": {"files": 244, "symbols": 1189},
  "selection": {"total_files": 244, "total_symbols": 1189, "selected_files": 13, "selected_symbols": 65, "omitted_files": 231, "omitted_symbols": 1124, "omitted_reason": "complete-output token budget"},
  "files": [
    {
      "path": "ranker.go",
      "language": "go",
      "parse_method": "go_ast",
      "score": 133,
      "score_components": {
        "imports": 120,
        "symbols": 3,
        "transitive": 10
      },
      "detail_level": 2,
      "symbols": [
        {
          "name": "RankFiles",
          "kind": "function",
          "line": 48
        }
      ]
    }
  ]
}

totals describes the complete repository. selection records the emitted and omitted file and symbol counts plus the omission reason. The CLI emits the largest whole-file prefix that fits; it never cuts a JSON record.

Expand Go Callers
repomap --calls --calls-threshold 2 --calls-limit 8

--calls selects exported symbols in files meeting --calls-threshold from semantic caller analysis. Receiver-qualified identities keep same-named methods distinct. Add --calls-include-tests to load test variants and include test callers. The lsp status, lsp refs, lsp def, lsp hover, and lsp symbols commands expose installed language-server results.

Inspect Cache State
repomap cache status
repomap cache status --json
repomap cache warm .
repomap cache warm . --cache-dir /tmp/repomap-cache

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. cache warm builds the map, saves it, and prints the same fresh status only after the saved entry is usable and fresh.

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. First-read groups include bounded read_next ranges when the static evidence has line numbers. 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. It suppresses dependency/archive noise from paths such as node_modules/, vendor/, .work/archive/, and archive/, while retaining suppressed counts in JSON. 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.

Risk packets remain at schema_version 2. Surface, effects, and brief packets use schema_version 3 and add structured truncations entries (field, shown, total, reason) so every cap is accounted for. Each packet carries a stable id (e.g. repomap:risk:internal-cli-audit-go) for citation, an evidence_class (import_graph, ast, git_history, or heuristic) with a derived confidence tier, and a per-file verify_cmd for Go targets. Signals blind to out-of-repo callers — dead code, untested exports — carry a caveat and are capped at low confidence. Empty file lists serialize as [] (never null) with a files_omitted_reason, and truncated per-file packets report an omitted_reason.

Commands

repomap [directory]                 # default enriched map
repomap -t 4096                     # token budget
repomap -f compact                  # path + exported symbol names
repomap -f verbose                  # all symbols, complete-output budget
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-structured           # schema-versioned map data
repomap --artifact out.md           # save long output without shell redirection
repomap task "add task packets" .   # owners + source + contracts + impact + verify
repomap task "add task packets" --json --consumed=task.go .
repomap brief [directory]           # agent boot digest: identity + verify + state + map
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 impact ranker.go --markdown # compact human handoff
repomap endpoint "GET /users/{id}"  # route -> handler -> callees -> tests
repomap inventory --boundary Postgres # ownership answer for DB work
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 audit effects --kind database --paths-only # DB boundary paths
repomap cache status                # inspect disk cache freshness
repomap cache warm .                # build and save a fresh disk cache
repomap lsp status                  # inspect LSP server coverage without starting servers
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 lsp symbols ranker.go
repomap lsp def ranker.go 48 RankFiles
repomap lsp refs ranker.go 48 RankFiles
repomap lsp hover ranker.go 48 RankFiles
Complete CLI flag index

There are 24 executable leaves: the default map; brief; task; audit hygiene, audit brief, audit risks, audit surface, audit effects; cache status, cache warm; find, impact, inventory, context, endpoint, explain, orphans, init; lsp status, lsp refs, lsp def, lsp hover, lsp symbols; and serve.

All leaves accept --artifact and --help. Root map flags are --tokens=2048 (>0), --format=enriched (enriched|compact|verbose|detail|lines|xml), --json, --json-structured, --calls, --calls-threshold=2 (>=0), --calls-limit=10 (0 = unlimited), --calls-include-tests, --intent, --consumed, --symbol-refs, --explain, and --include-tests.

Subcommand flags are: task --tokens, -t=4096, --json, --consumed; audit --limit=20, --top-files=0, --intent, --json, --language; brief additionally accepts --history-window and --refactor-signatures, while effects adds --kind and --paths-only; cache --cache-dir and status --json; find --kind, --file, --limit=20, --format=text; impact --json, --markdown; inventory --boundary, --json; context --kind, --file, --max-source-lines=200, --max-output-lines=400, --max-output-bytes=65536, --json, --calls, --calls-include-tests, --calls-limit=10; endpoint --json, --max-output-lines=400; explain/orphans/LSP query commands --json; init --force, --no-hook, --no-config.

Zero means unlimited only for documented result/caller/audit/output limits; tokens and context source lines must be positive. Structured JSON is mutually exclusive with --json; --top-files overrides --limit; impact JSON and Markdown conflict. See Configuration for accepted audit kinds, required flags, aliases, hidden compatibility behavior, and full precedence.

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 yes
detail All symbols plus signatures and fields yes
lines Actual declaration lines yes
xml Structured XML yes
--json Rendered verbose lines in JSON yes
--json-structured Files, symbols, call sites, ranks, parser data, budget data yes

Every bounded format counts the complete encoded stdout using ceil(UTF-8 bytes / 4), including headers, dependency flow, explanations, and JSON or XML envelopes. Repomap never byte-cuts structured output. Map formats select the largest whole-file prefix that fits; task packets additionally record field-level omissions in truncations. If the minimum valid envelope cannot fit, the command fails before writing stdout or replacing an artifact.

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
Structural call sites non-Go files called by other scanned 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

For database work, a compact flow is:

repomap --intent "PostgreSQL database psql pgx migrations schema queries" --explain
repomap inventory --boundary Postgres --json
repomap audit effects --kind database --paths-only
repomap impact internal/database/connection.go --markdown

Check exact evidence with:

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

Languages

Supported file types:

Language Parser path
Go go/packages + go/types for active packages; go/ast syntax fallback
PHP tree-sitter with signatures, visibility, constructor promotion, PHPDoc
TypeScript, TSX, JavaScript, JSX, Python, Rust, C, C++, Java, Ruby tree-sitter when available, ctags/regex fallback
Lua, Zig, Swift, Kotlin extension-only: ctags/regex fallback

Structured output includes parse_method: go_ast, tree_sitter, ctags, or regex. Go files also report build_active and analysis_mode.

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

The installed post-commit hook runs repomap cache warm . in the background.

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.Task(ctx, "goal", repomap.TaskOptions{}) // bounded implementation evidence
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
  • public analysis 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.

Contributing

See CONTRIBUTING.md for setup, formatting, tests, and local verification.

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 provides deterministic, local repository analysis for Go integrations. Its public API covers mapping, rendering, structured reports, audit, task, context, and impact analysis; commit mutation workflows are available through the repomap CLI.

Index

Constants

This section is empty.

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 ApplyCallSiteReferenceBonus added in v0.18.1

func ApplyCallSiteReferenceBonus(ranked []RankedFile)

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 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 CheckGopls added in v0.7.0

func CheckGopls() error

CheckGopls verifies that gopls is on PATH for callers that require the language-server-backed reference service.

func ConfidenceOrder added in v0.13.0

func ConfidenceOrder() []string

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

func CtagsAvailable

func CtagsAvailable() bool

CtagsAvailable reports whether ctags with JSON output support is on PATH.

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 FileHandle added in v0.15.0

func FileHandle(path string) string

FileHandle returns a stable handle for a repository-relative file path.

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 FormatTask added in v0.23.0

func FormatTask(r TaskReport) string

FormatTask renders the human packet exclusively from the shared task report.

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 FormatXMLWithSelection added in v0.25.0

func FormatXMLWithSelection(files []RankedFile, selection OutputSelection) string

FormatXMLWithSelection renders files with caller-supplied repository totals.

func LanguageCapabilityTier added in v0.15.0

func LanguageCapabilityTier(language string) string

LanguageCapabilityTier returns the declared semantic extraction tier for a language.

func LanguageFor

func LanguageFor(ext string) string

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

func MarshalTaskJSON added in v0.23.0

func MarshalTaskJSON(report TaskReport) ([]byte, error)

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 ParseSymbolHandle added in v0.15.0

func ParseSymbolHandle(handle string) (file, name, kind string, line int, ok bool)

ParseSymbolHandle parses handles emitted by SymbolHandle.

func ScoreComponentTotal added in v0.11.3

func ScoreComponentTotal(f RankedFile) int

ScoreComponentTotal returns the sum of tracked score components.

func SymbolHandle added in v0.15.0

func SymbolHandle(file string, sym Symbol) string

SymbolHandle returns a stable handle for a symbol in a repository-relative file.

func TreeSitterAvailable

func TreeSitterAvailable() bool

TreeSitterAvailable reports whether tree-sitter parsing is available.

func WriteTaskJSON added in v0.23.0

func WriteTaskJSON(w io.Writer, report TaskReport) error

Types

type AuditBriefOptions added in v0.25.0

type AuditBriefOptions struct {
	AuditOptions
	HistoryWindow      int
	RefactorSignatures bool
}

AuditBriefOptions controls optional, potentially more expensive evidence. History and refactor sections remain omitted unless explicitly requested so schema-3 brief output stays compatible with existing consumers.

func (AuditBriefOptions) Validate added in v0.25.0

func (o AuditBriefOptions) Validate() error

type AuditBriefReport added in v0.13.0

type AuditBriefReport struct {
	SchemaVersion  int                  `json:"schema_version"`
	Root           string               `json:"root"`
	Language       string               `json:"language,omitempty"`
	Risks          AuditRiskReport      `json:"risks"`
	Surface        AuditSurfaceReport   `json:"surface"`
	Effects        AuditEffectReport    `json:"effects"`
	FirstReadQueue []AuditReadGroup     `json:"first_read_queue"`
	ReviewPlan     []AuditReviewLane    `json:"review_plan"`
	History        *AuditHistoryReport  `json:"history,omitempty"`
	Refactors      *AuditRefactorReport `json:"refactors,omitempty"`
}

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"`
	SuppressedUntrackedCode int `json:"suppressed_untracked_code,omitempty"`
	Ignored                 int `json:"ignored"`
	IgnoredSource           int `json:"ignored_source"`
	SuppressedIgnoredSource int `json:"suppressed_ignored_source,omitempty"`
}

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"`
	Provenance string `json:"provenance"`
}

AuditEffect is one static side-effect lead.

type AuditEffectFile added in v0.13.0

type AuditEffectFile struct {
	ID            string        `json:"id"`
	Path          string        `json:"path"`
	Score         int           `json:"score"`
	EvidenceClass string        `json:"evidence_class,omitempty"`
	Confidence    string        `json:"confidence,omitempty"`
	Lanes         []string      `json:"lanes"`
	Effects       []AuditEffect `json:"effects"`
	OmittedReason string        `json:"omitted_reason,omitempty"`
	// contains filtered or unexported fields
}

AuditEffectFile groups side-effect leads by source file.

func (AuditEffectFile) AllEffects added in v0.23.0

func (f AuditEffectFile) AllEffects() []AuditEffect

AllEffects returns the uncapped effects used to derive this file packet. Callers that apply an additional filter must filter this set before applying the public per-file cap represented by Effects.

type AuditEffectKind added in v0.13.0

type AuditEffectKind struct {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	Reason        string   `json:"reason"`
	Lane          string   `json:"lane"`
	Files         []string `json:"files"`
	Caveat        string   `json:"caveat,omitempty"`
	Command       string   `json:"command,omitempty"`
	OmittedReason string   `json:"omitted_reason,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"`
	FilesOmittedReason string            `json:"files_omitted_reason,omitempty"`
	Kinds              []AuditEffectKind `json:"kinds"`
	Truncations        []AuditTruncation `json:"truncations,omitempty"`
}

AuditEffectReport captures files with side effects and trust boundaries.

type AuditFileRisk added in v0.13.0

type AuditFileRisk struct {
	ID            string   `json:"id"`
	Path          string   `json:"path"`
	Language      string   `json:"language,omitempty"`
	Package       string   `json:"package,omitempty"`
	Score         int      `json:"score"`
	AuditScore    int      `json:"audit_score"`
	EvidenceClass string   `json:"evidence_class,omitempty"`
	Confidence    string   `json:"confidence,omitempty"`
	Lanes         []string `json:"lanes,omitempty"`
	Reasons       []string `json:"reasons,omitempty"`
	Caveat        string   `json:"caveat,omitempty"`
	VerifyCmd     string   `json:"verify_cmd,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 AuditHistoryCoupling added in v0.25.0

type AuditHistoryCoupling struct {
	ID         string   `json:"id"`
	Paths      []string `json:"paths"`
	Commits    int      `json:"commits"`
	Confidence float64  `json:"confidence_score"`
}

type AuditHistoryHotspot added in v0.25.0

type AuditHistoryHotspot struct {
	ID            string                `json:"id"`
	Path          string                `json:"path"`
	RelativeChurn int                   `json:"relative_churn"`
	Touches       int                   `json:"touches"`
	LastTouched   string                `json:"last_touched"`
	CoChanges     []AuditHistoryPartner `json:"co_changes,omitempty"`
}

type AuditHistoryOmission added in v0.25.0

type AuditHistoryOmission struct {
	Commit string `json:"commit"`
	Reason string `json:"reason"`
}

type AuditHistoryPartner added in v0.25.0

type AuditHistoryPartner struct {
	Path       string  `json:"path"`
	Commits    int     `json:"commits"`
	Confidence float64 `json:"confidence"`
}

type AuditHistoryReport added in v0.25.0

type AuditHistoryReport struct {
	SchemaVersion int                    `json:"schema_version"`
	Root          string                 `json:"root"`
	Hotspots      []AuditHistoryHotspot  `json:"hotspots"`
	Couplings     []AuditHistoryCoupling `json:"couplings"`
	Omissions     []AuditHistoryOmission `json:"omissions,omitempty"`
}

AuditHistoryReport is bounded, deterministic Git history evidence. Empty history is valid; command failures are returned to the requested caller.

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 {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	Reason        string   `json:"reason"`
	Files         []string `json:"files"`
	Caveat        string   `json:"caveat,omitempty"`
	Command       string   `json:"command,omitempty"`
	OmittedReason string   `json:"omitted_reason,omitempty"`
}

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

type AuditOptions added in v0.25.0

type AuditOptions struct {
	Limit    int
	Language string
}

AuditOptions controls the deterministic source packets. A zero value keeps the historical unfiltered, unlimited behavior.

func (AuditOptions) Validate added in v0.25.0

func (o AuditOptions) Validate() error

Validate rejects unsupported language IDs before any audit packet is built.

type AuditReadGroup added in v0.13.0

type AuditReadGroup struct {
	ID            string         `json:"id"`
	Group         string         `json:"group"`
	Lane          string         `json:"lane"`
	EvidenceClass string         `json:"evidence_class,omitempty"`
	Confidence    string         `json:"confidence,omitempty"`
	Reasons       []string       `json:"reasons"`
	Caveat        string         `json:"caveat,omitempty"`
	Files         []string       `json:"files"`
	ReadNext      []ReadNextItem `json:"read_next,omitempty"`
	OmittedReason string         `json:"omitted_reason,omitempty"`
}

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 AuditRefactorGroup added in v0.25.0

type AuditRefactorGroup struct {
	ID         string              `json:"id"`
	Kind       string              `json:"kind"`
	Confidence string              `json:"confidence"`
	Caveat     string              `json:"caveat"`
	TestAnchor string              `json:"test_anchor"`
	Sites      []AuditRefactorSite `json:"sites"`
}

type AuditRefactorReport added in v0.25.0

type AuditRefactorReport struct {
	SchemaVersion int                  `json:"schema_version"`
	Root          string               `json:"root"`
	Groups        []AuditRefactorGroup `json:"groups"`
}

AuditRefactorReport contains exact duplicate function-body leads. They are intentionally structural evidence, not proof that extraction is desirable.

type AuditRefactorSite added in v0.25.0

type AuditRefactorSite struct {
	Path      string `json:"path"`
	Symbol    string `json:"symbol"`
	StartLine int    `json:"start_line"`
	EndLine   int    `json:"end_line"`
}

type AuditReviewLane added in v0.13.0

type AuditReviewLane struct {
	ID            string   `json:"id"`
	Lane          string   `json:"lane"`
	Group         string   `json:"group"`
	EvidenceClass string   `json:"evidence_class,omitempty"`
	Confidence    string   `json:"confidence,omitempty"`
	Files         []string `json:"files"`
	Caveat        string   `json:"caveat,omitempty"`
	Gates         []string `json:"gates"`
	Verify        []string `json:"verify"`
	Why           []string `json:"why"`
	OmittedReason string   `json:"omitted_reason,omitempty"`
}

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"`
	FilesOmittedReason string          `json:"files_omitted_reason,omitempty"`
	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 {
	ID            string            `json:"id"`
	Path          string            `json:"path"`
	Score         int               `json:"score"`
	EvidenceClass string            `json:"evidence_class,omitempty"`
	Confidence    string            `json:"confidence,omitempty"`
	Kinds         []string          `json:"kinds"`
	Hits          []AuditSurfaceHit `json:"hits"`
	OmittedReason string            `json:"omitted_reason,omitempty"`
	// contains filtered or unexported fields
}

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"`
	Hidden   bool   `json:"hidden,omitempty"`
}

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"`
	FilesOmittedReason  string             `json:"files_omitted_reason,omitempty"`
	Truncations         []AuditTruncation  `json:"truncations,omitempty"`
	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"`
	Jobs                []AuditSurfaceHit  `json:"jobs,omitempty"`
	ModelFields         []AuditSurfaceHit  `json:"model_fields,omitempty"`
	Policies            []AuditSurfaceHit  `json:"policies,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 AuditTruncation added in v0.23.0

type AuditTruncation struct {
	Field  string `json:"field"`
	Shown  int    `json:"shown"`
	Total  int    `json:"total"`
	Reason string `json:"reason"`
}

AuditTruncation accounts for every deterministic packet cap.

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 CallSite added in v0.18.1

type CallSite struct {
	Name string `json:"name"`
	Line int    `json:"line"`
}

CallSite is one parser-backed call expression observed in a source file. Name is the captured callee expression, normalized for stable matching.

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 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)
	GoAnalysis      bool     // load active Go packages for semantic metadata and relationships
	GoAnalysisCalls bool     // build the SSA/CHA caller graph during Go semantic analysis
	GoAnalysisTests bool     // include Go test variants in semantic callers and type relationships
	MaxFileSize     int      // max file size in bytes to scan (default: 50_000; negative disables the cap)
}

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 EndpointContext added in v0.20.0

type EndpointContext struct {
	Route     RouteRegistration `json:"route"`
	Handler   *SymbolMatch      `json:"handler,omitempty"`
	Ambiguous []SymbolMatch     `json:"ambiguous,omitempty"`
	Callees   []string          `json:"callees,omitempty"`
	Tests     []Location        `json:"tests,omitempty"`
	Impact    ImpactResult      `json:"impact"`
}

EndpointContext is the vertical-slice bundle for one resolved route: the registration, its handler symbol, the handler's direct callee names, the tests that touch it, and the file-level impact summary.

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)
	CallSites    []CallSite
	ParseMethod  string // "go_ast", "tree_sitter", "ctags", or "regex" — signals symbol fidelity
	BuildActive  bool   `json:"build_active,omitempty"`  // true when included by the active Go build context
	AnalysisMode string `json:"analysis_mode,omitempty"` // "semantic", "syntax_only", or empty for non-Go
}

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 ParseGoSource added in v0.21.0

func ParseGoSource(source []byte, path, root string) (*FileSymbols, error)

ParseGoSource performs syntax-only Go parsing for dirty buffers, historical revisions, inactive build files, and invalid workspace states.

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 GoDiagnostic added in v0.21.0

type GoDiagnostic struct {
	PackagePath string `json:"package_path,omitempty"`
	Position    string `json:"position,omitempty"`
	Message     string `json:"message"`
}

GoDiagnostic reports a package loader or type-checker diagnostic while allowing successfully analyzed packages to remain usable.

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"`
	RiskLevel          string         `json:"risk_level,omitempty"`
	AffectedPackages   []string       `json:"affected_packages,omitempty"`
	CheckNext          []string       `json:"check_next,omitempty"`
	LikelyTestCommands []string       `json:"likely_test_commands,omitempty"`
	ReadNext           []ReadNextItem `json:"read_next,omitempty"`
	OmittedReason      string         `json:"omitted_reason,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) AuditBriefWithOptions added in v0.25.0

func (m *Map) AuditBriefWithOptions(ctx context.Context, options AuditBriefOptions) (AuditBriefReport, error)

AuditBriefWithOptions composes language-scoped deterministic evidence before deriving queues and review plans.

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. It is retained for compatibility; new callers should use AuditEffectsWithOptions.

func (*Map) AuditEffectsWithOptions added in v0.25.0

func (m *Map) AuditEffectsWithOptions(ctx context.Context, options AuditOptions) (AuditEffectReport, error)

func (*Map) AuditHistory added in v0.25.0

func (m *Map) AuditHistory(ctx context.Context, window int) (AuditHistoryReport, error)

AuditHistory collects a bounded numstat history for currently tracked Go files. It intentionally does not use scanner results so ignored or untracked work cannot become historical evidence.

func (*Map) AuditRefactorSignatures added in v0.25.0

func (m *Map) AuditRefactorSignatures(ctx context.Context) (AuditRefactorReport, error)

AuditRefactorSignatures detects exact normalized bodies only within a Go package. It deliberately avoids type-checking or whole-program analysis.

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. It is retained for compatibility; new callers should use AuditRisksWithOptions.

func (*Map) AuditRisksWithOptions added in v0.25.0

func (m *Map) AuditRisksWithOptions(options AuditOptions) (AuditRiskReport, error)

AuditRisksWithOptions applies the language filter before ranking, lanes, and the output limit so a broad repository cannot crowd out selected evidence.

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. It is retained for compatibility; new callers should use AuditSurfaceWithOptions.

func (*Map) AuditSurfaceWithOptions added in v0.25.0

func (m *Map) AuditSurfaceWithOptions(ctx context.Context, options AuditOptions) (AuditSurfaceReport, error)

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) Endpoint added in v0.20.0

func (m *Map) Endpoint(ctx context.Context, pattern string) (EndpointContext, error)

Endpoint resolves a single route by pattern and returns its vertical-slice bundle: the matched RouteRegistration, its handler symbol (best FindSymbol hit), the handler's depth-1 lexical callee names, and the file-level impact. The CLI layer fills EndpointContext.Tests afterward (gopls-backed). Zero matches is an error; multiple matches populate Ambiguous (capped at 5).

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). A name with the "symbol:" prefix is
       treated as a stable handle produced by SymbolHandle and resolved to the
       single exact match (score 100), bypassing the fuzzy ranking below.
       Otherwise the plain name is 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) FindSymbolHandle added in v0.15.0

func (m *Map) FindSymbolHandle(file, name, kind string, line int) []SymbolMatch

FindSymbolHandle resolves an exact symbol handle emitted by SymbolHandle.

func (*Map) GoDiagnostics added in v0.21.0

func (m *Map) GoDiagnostics() []GoDiagnostic

GoDiagnostics returns diagnostics from the latest semantic analysis.

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 preserves the historical public fast-path API. Build consumes cacheLoadPlan directly so it can distinguish exact cache hits from incremental merges that need cache metadata persisted.

func (*Map) OrphanCandidates added in v0.13.0

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

OrphanCandidates returns exported symbols with zero inbound references and test-only references. An optional OrphanOptions value preserves caller-known framework dispatch as a distinct, inspectable bucket. Entry points are excluded, and 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) Routes added in v0.20.0

func (m *Map) Routes(ctx context.Context) ([]RouteRegistration, error)

Routes returns every route registration discovered across the scanned Go source files. It reuses auditStaticFiles (non-test file set) and readAuditLines (bounded, ctx-cancellable line read). An empty result is success, not an error.

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) SemanticCallers added in v0.21.0

func (m *Map) SemanticCallers() SymbolCallers

SemanticCallers returns the caller projection produced by the Map's single module-aware Go analysis. The returned map is a defensive copy.

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 the tracked tree has changed since the last build. See StaleContext.

func (*Map) StaleContext added in v0.19.0

func (m *Map) StaleContext(ctx context.Context) bool

StaleContext reports whether any tracked file has been modified since the last build (mtime polling), or whether the discovered file set itself has changed (fresh scan vs stored fingerprint — catches newly created files, which mtime polling over recorded paths can never see). 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) StringBriefMap added in v0.16.0

func (m *Map) StringBriefMap(maxFiles int) (body string, total int)

StringBriefMap returns the enriched map for the top maxFiles ranked files (the highest-scoring, since m.ranked is sorted descending) and the total ranked-file count so the caller can report how many were dropped. Single- package repos report a uniform ImportedBy — every file "imported by N" where N is the package's importer count, a constant with no per-file signal — which is zeroed out (when uniform across the shown files) so the digest map drops that noise. maxFiles <= 0 means no cap.

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.

func (*Map) Task added in v0.23.0

func (m *Map) Task(ctx context.Context, goal string, opts TaskOptions) (TaskReport, error)

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"`
	Reason   string `json:"reason,omitempty"`
}

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

type OrphanOptions added in v0.25.0

type OrphanOptions struct {
	ProtectedSymbols []OrphanProtection
}

OrphanOptions supplies caller-owned knowledge that static references cannot see.

type OrphanProtection added in v0.25.0

type OrphanProtection struct {
	Name     string
	Receiver string
	File     string
	Reason   string
}

OrphanProtection identifies a symbol reached through framework dispatch.

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"`
	FrameworkDispatched []OrphanCandidate `json:"framework_dispatched"`
}

OrphanReport buckets exported symbols by inbound-reference status.

type OutputSelection added in v0.25.0

type OutputSelection struct {
	TotalFiles      int    `json:"total_files"`
	TotalSymbols    int    `json:"total_symbols"`
	SelectedFiles   int    `json:"selected_files"`
	SelectedSymbols int    `json:"selected_symbols"`
	OmittedFiles    int    `json:"omitted_files"`
	OmittedSymbols  int    `json:"omitted_symbols"`
	OmittedReason   string `json:"omitted_reason,omitempty"`
}

OutputSelection accounts for the complete repository versus emitted records.

func DescribeOutputSelection added in v0.25.0

func DescribeOutputSelection(all, selected []RankedFile, reason string) OutputSelection

DescribeOutputSelection derives deterministic selection accounting.

type ParseCoverage added in v0.14.0

type ParseCoverage struct {
	FilesScanned      int            `json:"files_scanned"`
	FilesParsed       int            `json:"files_parsed"`
	ParseFailures     int            `json:"parse_failures,omitempty"`
	ByLanguage        map[string]int `json:"by_language,omitempty"`
	ByParseMethod     map[string]int `json:"by_parse_method,omitempty"`
	FailuresByLang    map[string]int `json:"failures_by_language,omitempty"`
	TreeSitterEnabled bool           `json:"tree_sitter_enabled"`
	CtagsEnabled      bool           `json:"ctags_enabled"`
	GoSemanticActive  int            `json:"go_semantic_active,omitempty"`
	GoSyntaxInactive  int            `json:"go_syntax_inactive,omitempty"`
	GoAnalysisFailed  int            `json:"go_analysis_failed,omitempty"`
}

ParseCoverage records observed parser fidelity for a build.

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 ReadNextItem added in v0.18.1

type ReadNextItem struct {
	File      string `json:"file"`
	StartLine int    `json:"start_line"`
	EndLine   int    `json:"end_line"`
	Reason    string `json:"reason"`
}

ReadNextItem is a bounded source range worth reading next.

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.

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 RouteRegistration added in v0.20.0

type RouteRegistration struct {
	Method    string // "GET", "POST", ... or "ANY" for a method-less net/http registration
	Pattern   string // path pattern as written, e.g. "/users/{id}"
	Handler   string // handler identifier text, or "<inline>" for a closure
	Framework string // "net/http" | "chi"
	File      string // path relative to the map root
	Line      int    // 1-based line number of the registration
}

RouteRegistration is one HTTP route binding discovered lexically in a source file: an HTTP method, the path pattern as written, the handler identifier text, and the framework it was registered with.

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 StructuredCallSite added in v0.18.1

type StructuredCallSite struct {
	Name string `json:"name"`
	Line int    `json:"line,omitempty"`
}

StructuredCallSite is one parser-backed call expression emitted for tools that need relation evidence without re-reading source.

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 StructuredEvidence added in v0.14.0

type StructuredEvidence struct {
	Kind          string `json:"kind"`
	EvidenceClass string `json:"evidence_class"`
	Confidence    string `json:"confidence"`
	Detail        string `json:"detail"`
	Caveat        string `json:"caveat,omitempty"`
}

StructuredEvidence explains a relationship signal that was used by ranking or emitted for structured consumers.

type StructuredFile added in v0.11.3

type StructuredFile struct {
	Path             string               `json:"path"`
	Handle           string               `json:"handle,omitempty"`
	Language         string               `json:"language,omitempty"`
	CapabilityTier   string               `json:"capability_tier,omitempty"`
	Package          string               `json:"package,omitempty"`
	ImportPath       string               `json:"import_path,omitempty"`
	ParseMethod      string               `json:"parse_method,omitempty"`
	BuildActive      bool                 `json:"build_active,omitempty"`
	AnalysisMode     string               `json:"analysis_mode,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"`
	RelationEvidence []StructuredEvidence `json:"relation_evidence,omitempty"`
	Symbols          []StructuredSymbol   `json:"symbols,omitempty"`
	CallSites        []StructuredCallSite `json:"call_sites,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"`
	Coverage      ParseCoverage    `json:"coverage"`
	Warnings      []string         `json:"warnings,omitempty"`
	Selection     OutputSelection  `json:"selection"`
	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, coverage ParseCoverage) 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"`
	Handle      string   `json:"handle,omitempty"`
	FileHandle  string   `json:"file_handle,omitempty"`
	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"`
	Hash        string   `json:"hash,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)
	Hash        string   `json:"hash,omitempty"` // sha256 hex of the symbol's raw source bytes over Line..EndLine; empty when span unavailable
}

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 SelectSemanticCallers added in v0.21.0

func SelectSemanticCallers(all SymbolCallers, ranked []RankedFile, cfg CallsConfig) SymbolCallers

SelectSemanticCallers applies the existing --calls threshold, test, and limit policy to callers produced by the canonical semantic analysis.

func (SymbolCallers) CallersFor added in v0.19.0

func (sc SymbolCallers) CallersFor(file, symbol string) []Location

CallersFor returns the caller locations recorded for the given file+symbol, or nil if the symbol has no recorded callers. It builds the same lookup key used at construction (callsKey); on an exact-key miss it retries with forward-slash-normalized separators (filepath.ToSlash) so a lookup passing an OS-native path still matches keys built with root-relative slashed paths.

func (SymbolCallers) CallersForSymbol added in v0.21.0

func (sc SymbolCallers) CallersForSymbol(file string, symbol Symbol) []Location

CallersForSymbol resolves receiver-qualified semantic caller keys and falls back to the legacy file/name key for cached and external caller maps.

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"`
	ReadNext   []ReadNextItem `json:"read_next,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
	Handle      string  // stable symbol handle; accepted by Context
	FileHandle  string  // stable file handle for the owning file
	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 TaskBudget added in v0.23.0

type TaskBudget struct {
	MaxTokens  int `json:"max_tokens"`
	UsedTokens int `json:"used_tokens"`
}

type TaskEffect added in v0.23.0

type TaskEffect struct {
	Effect     AuditEffect `json:"effect"`
	Provenance string      `json:"provenance"`
}

type TaskEvidence added in v0.23.0

type TaskEvidence struct {
	Field string `json:"field"`
	Value string `json:"value"`
}

type TaskOptions added in v0.23.0

type TaskOptions struct {
	MaxTokens     int
	ConsumedPaths []string
}

type TaskRelatedChange added in v0.23.0

type TaskRelatedChange struct {
	Path   string `json:"path"`
	Status string `json:"status"`
}

type TaskRelationship added in v0.23.0

type TaskRelationship struct {
	Kind       string `json:"kind"`
	Path       string `json:"path"`
	Symbol     string `json:"symbol,omitempty"`
	Provenance string `json:"provenance"`
}

type TaskReport added in v0.23.0

type TaskReport struct {
	SchemaVersion    int                 `json:"schema_version"`
	Root             string              `json:"root"`
	Goal             string              `json:"goal"`
	Budget           TaskBudget          `json:"budget"`
	Selection        TaskSelection       `json:"selection"`
	Rules            []TaskRule          `json:"rules"`
	RelatedChanges   []TaskRelatedChange `json:"related_changes"`
	Targets          []TaskTarget        `json:"targets"`
	ReadNext         []ReadNextItem      `json:"read_next"`
	VerifyCommands   []string            `json:"verify_commands"`
	FollowUpCommands []string            `json:"follow_up_commands"`
	Diagnostics      []string            `json:"diagnostics"`
	Truncations      []TaskTruncation    `json:"truncations"`
}

TaskReport is schema version 1. The top-level JSON keys are a compatibility contract.

type TaskRule added in v0.23.0

type TaskRule struct {
	Path string `json:"path"`
}

type TaskSelection added in v0.23.0

type TaskSelection struct {
	Strategy string `json:"strategy"`
	Limit    int    `json:"limit"`
	Selected int    `json:"selected"`
}

type TaskSource added in v0.23.0

type TaskSource struct {
	Symbol string       `json:"symbol"`
	Lines  []SourceLine `json:"lines"`
}

type TaskTarget added in v0.23.0

type TaskTarget struct {
	Path             string             `json:"path"`
	Package          string             `json:"package"`
	AffectedPackages []string           `json:"affected_packages"`
	Confidence       string             `json:"confidence"`
	Symbols          []Symbol           `json:"symbols"`
	Evidence         []TaskEvidence     `json:"evidence"`
	Relationships    []TaskRelationship `json:"relationships"`
	Consumers        []string           `json:"consumers"`
	Callers          []Location         `json:"callers"`
	Tests            []string           `json:"tests"`
	Imports          []string           `json:"imports"`
	Effects          []TaskEffect       `json:"effects"`
	Boundaries       []string           `json:"boundaries"`
	Risk             string             `json:"risk"`
	Parse            string             `json:"parse"`
	Source           []TaskSource       `json:"source"`
	Consumed         bool               `json:"consumed"`
}

type TaskTruncation added in v0.23.0

type TaskTruncation struct {
	Field  string `json:"field"`
	Shown  int    `json:"shown"`
	Total  int    `json:"total"`
	Reason string `json:"reason"`
}

Directories

Path Synopsis
cmd
repomap command
internal
cli
goanalysis
Package goanalysis owns module-aware Go semantic loading for repomap.
Package goanalysis owns module-aware Go semantic loading for repomap.
lsp
Package lsp provides an LSP client for code intelligence.
Package lsp provides an LSP client for code intelligence.
safefs
Package safefs provides narrow filesystem primitives for cache publication.
Package safefs provides narrow filesystem primitives for cache publication.
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