cli

package
v0.15.2 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Overview

Package cli provides the Cobra command tree for the codegraph binary. Each verb lives in its own file; this file contains shared UI helpers.

Index

Constants

View Source
const ExitNeedsUpgrade = 3

ExitNeedsUpgrade is the process exit code for an index that cannot be read until a read-write `codegrapher sync` (or --refresh) upgrades it. It is distinct from the generic failure code 1 so scripts and pollers can tell "run sync" apart from a real error.

Variables

This section is empty.

Functions

func ExitCodeFor added in v0.14.3

func ExitCodeFor(err error) int

ExitCodeFor maps a command error to the process exit code.

func NewRootCmd

func NewRootCmd() *cobra.Command

NewRootCmd builds and returns the root Cobra command with all sub-commands attached. It does NOT call Execute() — the caller does.

func ReportAndExitCode added in v0.14.3

func ReportAndExitCode(err error, stderr io.Writer) int

ReportAndExitCode prints err (unless the command already reported it) and returns the process exit code for it.

Types

type BriefSymbol added in v0.5.0

type BriefSymbol struct {
	ID            string         `json:"id"`
	Kind          model.NodeKind `json:"kind"`
	Name          string         `json:"name"`
	QualifiedName string         `json:"qualifiedName"`
	FilePath      string         `json:"filePath"`
	Language      model.Language `json:"language"`
	StartLine     int            `json:"startLine"`
	EndLine       int            `json:"endLine"`
	StartColumn   int            `json:"startColumn"`
	EndColumn     int            `json:"endColumn"`
	Signature     string         `json:"signature,omitempty"`
	Metadata      map[string]any `json:"metadata,omitempty"`
}

BriefSymbol is the compact, stable discovery shape for automation. It intentionally excludes documentation, decorators, and result scores so an agent can choose a symbol before requesting its source with `node`.

type CalleesResult

type CalleesResult struct {
	Symbol  string      `json:"symbol"`
	Callees []SymbolRef `json:"callees"`
	Note    string      `json:"note,omitempty"`
}

CalleesResult is the JSON payload for `codegrapher callees <symbol>`.

type CallersResult

type CallersResult struct {
	Symbol  string      `json:"symbol"`
	Callers []SymbolRef `json:"callers"`
	Note    string      `json:"note,omitempty"`
}

CallersResult is the JSON payload for `codegrapher callers <symbol>`.

type ContextCallee added in v0.14.0

type ContextCallee struct {
	Symbol     BriefSymbol `json:"symbol"`
	Seam       string      `json:"seam,omitempty"`       // interface | field | parameter
	SeamSource string      `json:"seamSource,omitempty"` // graph | inferred; set whenever Seam is non-empty
}

ContextCallee is section (c): a direct callee, signature only.

Seam is "interface" (a real graph fact: an incoming contains edge from a KindInterface owner) or "field"/"parameter" (a best-effort text scan over the caller's own source/signature — see seamKind). SeamSource makes that distinction explicit for consumers: "graph" for interface, "inferred" for field/parameter. It is set whenever Seam is non-empty.

type ContextCoverage added in v0.14.2

type ContextCoverage struct {
	Freshness string         `json:"freshness"` // current | stale | unavailable
	Ref       string         `json:"ref,omitempty"`
	RunAt     int64          `json:"runAt,omitempty"`
	Covered   int            `json:"statementsCovered"`
	Total     int            `json:"statementsTotal"`
	Percent   float64        `json:"percent"`
	Lines     []CoverageLine `json:"lines,omitempty"`
}

type ContextNotFound added in v0.14.0

type ContextNotFound struct {
	Requested  string        `json:"requested"`
	Status     string        `json:"status"` // not_found | ambiguous
	Hint       string        `json:"hint,omitempty"`
	Candidates []BriefSymbol `json:"candidates,omitempty"`
}

ContextNotFound reports a requested symbol that did not resolve to exactly one node; it never blocks the other requested symbols.

type ContextResult added in v0.14.0

type ContextResult struct {
	Requested       []string          `json:"requested"`
	Budget          int               `json:"budget"`
	Unresolved      []ContextNotFound `json:"unresolved,omitempty"`
	Sources         []ContextSource   `json:"sources,omitempty"`
	Types           []ContextType     `json:"types,omitempty"`
	Callees         []ContextCallee   `json:"callees,omitempty"`
	Tests           []ContextTestRef  `json:"tests,omitempty"`
	Helpers         []ContextType     `json:"helpers,omitempty"`
	Omitted         []string          `json:"omitted,omitempty"`
	TokensEstimated int               `json:"tokensEstimated"`
}

ContextResult is the JSON payload for `codegrapher context`.

type ContextSource added in v0.14.0

type ContextSource struct {
	Symbol    BriefSymbol      `json:"symbol"`
	Source    string           `json:"source"`
	Coverage  *ContextCoverage `json:"coverage,omitempty"`
	Narrowed  bool             `json:"narrowed,omitempty"`
	StartLine int              `json:"startLine,omitempty"`
	EndLine   int              `json:"endLine,omitempty"`
}

ContextSource is section (a): one requested symbol's line-bounded source.

A --line target that falls inside a nested function literal (a closure with no name of its own — an anonymous RunE callback; a switch/loop body has none of these either, but those are not literals) resolves to the innermost NAMED enclosing function/method, per A1 (resolveByFileLine), and Source is that function's WHOLE body, not just the literal: a closure only makes sense read alongside the function that declares the variables it captures and wires it up (founder correction, 2026-09-25 — the earlier design narrowed to the literal's own few lines and lost exactly that context). Every line of a target literal carries a trailing "// TARGET" marker (see A1/resolveClosureNarrowing) so the reader can still find it inside the full function. StartLine/EndLine are always the enclosing node's own declared bounds, even when Narrowed is true.

Narrowed is true only when the enclosing function is longer than --max-function-lines: Source then keeps just the target literal(s) whole, the lines declaring the free variables they capture (go/ast scope), and the statement that registers/calls each literal, joined by explicit "// … N lines elided" markers — never a silent drop.

type ContextTestRef added in v0.14.0

type ContextTestRef struct {
	Name      string `json:"name"`
	FilePath  string `json:"filePath"`
	StartLine int    `json:"startLine"`
	Hops      int    `json:"hops"` // 1 = direct, 2 = one hop
}

ContextTestRef is section (d): an existing test that calls the symbol.

type ContextType added in v0.14.0

type ContextType struct {
	Roles          []string    `json:"roles"`
	HeuristicRoles []string    `json:"heuristicRoles,omitempty"` // subset of Roles that are text-scan-derived, not graph-verified
	For            string      `json:"for,omitempty"`            // constructor's target type name
	Symbol         BriefSymbol `json:"symbol"`
	Source         string      `json:"source"`
}

ContextType is section (b)/(e): a full type or constructor declaration.

Roles are a mix of graph-verified facts (receiver, parameter/result, constructor — all real edges/lookups) and, for "field", a best-effort text scan (see fieldReadsOf/parseStructFields) that can miss or misfire on a shadowed receiver name, an unparsed embedded/generic field, etc. HeuristicRoles names the subset of Roles that came from that text scan rather than the graph, so a consumer can tell "the graph says so" from "a regex guessed" instead of trusting every role at the same confidence.

type CoverageLine added in v0.14.2

type CoverageLine struct {
	Line  int    `json:"line"`
	State string `json:"state"` // hit | miss | partial | unmeasured
}

type ExitError added in v0.14.3

type ExitError struct{ Code int }

ExitError ends a command with a specific exit code after the command has already reported the reason itself (no extra "error:" line is printed).

func (*ExitError) Error added in v0.14.3

func (e *ExitError) Error() string

type FileInfo

type FileInfo struct {
	Path      string         `json:"path"`
	Language  model.Language `json:"language"`
	NodeCount int            `json:"nodeCount"`
	Size      int64          `json:"size"`
}

FileInfo is one entry in the `files` JSON array.

type GraphQuerier

type GraphQuerier interface {
	// SearchNodes runs the symbol-search pipeline and returns scored results.
	SearchNodes(rawQuery string, opts SearchOptions) ([]model.SearchResult, error)

	// Callers returns the set of symbols that call the given symbol name.
	Callers(symbol string) (*CallersResult, error)

	// Callees returns the set of symbols that the given symbol name calls.
	Callees(symbol string) (*CalleesResult, error)

	// Impact returns the blast-radius for the given symbol name.
	Impact(symbol string, depth int) (*ImpactResult, error)

	// Status returns index statistics.
	Status(projectPath string) (*StatusResult, error)

	// Files returns the list of indexed files.
	Files() ([]FileInfo, error)
}

GraphQuerier is the narrow read-only interface the CLI needs from the query layer. Implement it against the real query package; use mockQuerier in tests.

func NewStoreQuerier

func NewStoreQuerier(stores ...*store.Store) GraphQuerier

NewStoreQuerier wraps one or more *store.Store as a GraphQuerier. With a single store it behaves identically to the original single-store wrapper.

type ImpactResult

type ImpactResult struct {
	Symbol    string      `json:"symbol"`
	Depth     int         `json:"depth"`
	NodeCount int         `json:"nodeCount"`
	EdgeCount int         `json:"edgeCount"`
	Affected  []SymbolRef `json:"affected"`
	Note      string      `json:"note,omitempty"`
}

ImpactResult is the JSON payload for `codegrapher impact <symbol>`.

type IndexInfo

type IndexInfo struct {
	BuiltWithVersion           string `json:"builtWithVersion"`
	BuiltWithExtractionVersion int    `json:"builtWithExtractionVersion"`
	CurrentExtractionVersion   int    `json:"currentExtractionVersion"`
	ReindexRecommended         bool   `json:"reindexRecommended"`
}

IndexInfo mirrors the `index` block of the status payload.

type NodeFreshness added in v0.5.0

type NodeFreshness struct {
	Refreshed bool `json:"refreshed"`
	Verified  bool `json:"verified"`
	// Stale is set when the file on disk no longer matches the index and the
	// command did not refresh (run it with --refresh to see current source).
	Stale bool `json:"stale,omitempty"`
}

type NodeRelation added in v0.5.0

type NodeRelation struct {
	Direction         string         `json:"direction"`
	Kind              model.EdgeKind `json:"kind"`
	Symbol            BriefSymbol    `json:"symbol"`
	Provenance        string         `json:"provenance,omitempty"`
	Line              int            `json:"line,omitempty"`
	Column            int            `json:"column,omitempty"`
	Metadata          map[string]any `json:"metadata,omitempty"`
	ViaSemanticCodeID string         `json:"viaSemanticCodeId,omitempty"`
}

type NodeResult added in v0.5.0

type NodeResult struct {
	Requested   string         `json:"requested"`
	Status      string         `json:"status"`
	Hint        string         `json:"hint,omitempty"`
	Symbol      *BriefSymbol   `json:"symbol,omitempty"`
	Source      string         `json:"source,omitempty"`
	SourceRange string         `json:"sourceRange,omitempty"`
	Freshness   NodeFreshness  `json:"freshness"`
	Relations   []NodeRelation `json:"relations,omitempty"`
	Candidates  []BriefSymbol  `json:"candidates,omitempty"`
}

NodeResult is a symbol-oriented view of an indexed node. Source is omitted from JSON by default; text output renders it as a raw fenced code block.

type PathEdge added in v0.10.0

type PathEdge struct {
	Kind       model.EdgeKind `json:"kind"`
	Line       int            `json:"line,omitempty"`
	Column     int            `json:"column,omitempty"`
	Provenance string         `json:"provenance,omitempty"`
}

type PathResult added in v0.10.0

type PathResult struct {
	Start            string        `json:"start"`
	Target           string        `json:"target"`
	Status           string        `json:"status"`
	Hint             string        `json:"hint,omitempty"`
	Freshness        NodeFreshness `json:"freshness"`
	MaxHops          int           `json:"maxHops"`
	MaxNodes         int           `json:"maxNodes"`
	MaxEdges         int           `json:"maxEdges"`
	VisitedNodes     int           `json:"visitedNodes"`
	VisitedEdges     int           `json:"visitedEdges"`
	Truncated        bool          `json:"truncated,omitempty"`
	Steps            []PathStep    `json:"steps,omitempty"`
	StartCandidates  []BriefSymbol `json:"startCandidates,omitempty"`
	TargetCandidates []BriefSymbol `json:"targetCandidates,omitempty"`
}

PathResult is one bounded, directed call path. A path is static graph evidence: it describes one possible route, not an observed execution.

type PathStep added in v0.10.0

type PathStep struct {
	Symbol BriefSymbol `json:"symbol"`
	Edge   *PathEdge   `json:"edge,omitempty"`
	Source string      `json:"source,omitempty"`
}

PathStep is a symbol on a path. Edge describes the transition from the preceding step; it is omitted for the starting symbol.

type PendingChanges

type PendingChanges struct {
	Added    int `json:"added"`
	Modified int `json:"modified"`
	Removed  int `json:"removed"`
}

PendingChanges mirrors the pendingChanges field in the status payload.

type SearchOptions

type SearchOptions struct {
	Limit     int
	Offset    int
	Kinds     []model.NodeKind
	Languages []model.Language
}

SearchOptions controls result set size and filtering.

type StackTraceFrame added in v0.10.0

type StackTraceFrame struct {
	Index          int           `json:"index"`
	Raw            string        `json:"raw"`
	Function       string        `json:"function,omitempty"`
	FilePath       string        `json:"filePath,omitempty"`
	Line           int           `json:"line,omitempty"`
	Column         int           `json:"column,omitempty"`
	Status         string        `json:"status"`
	Hint           string        `json:"hint,omitempty"`
	Symbol         *BriefSymbol  `json:"symbol,omitempty"`
	Candidates     []BriefSymbol `json:"candidates,omitempty"`
	PathCandidates []string      `json:"pathCandidates,omitempty"`
	Source         string        `json:"source,omitempty"`
}

type StackTraceResult added in v0.10.0

type StackTraceResult struct {
	Status    string            `json:"status"`
	Hint      string            `json:"hint,omitempty"`
	Freshness NodeFreshness     `json:"freshness"`
	Revision  string            `json:"revision,omitempty"`
	MaxFrames int               `json:"maxFrames"`
	Truncated bool              `json:"truncated,omitempty"`
	Frames    []StackTraceFrame `json:"frames"`
}

StackTraceResult maps runtime frames to the current, freshly-indexed source. It intentionally does not infer edges between frames: a stack is runtime evidence and may cross reflection, generated code, or framework callbacks.

type StatusResult

type StatusResult struct {
	Initialized      bool                   `json:"initialized"`
	Version          string                 `json:"version"`
	ProjectPath      string                 `json:"projectPath"`
	IndexPath        string                 `json:"indexPath"`
	LastIndexed      string                 `json:"lastIndexed"`
	FileCount        int                    `json:"fileCount"`
	NodeCount        int                    `json:"nodeCount"`
	EdgeCount        int                    `json:"edgeCount"`
	DBSizeBytes      int64                  `json:"dbSizeBytes"`
	Backend          string                 `json:"backend"`
	JournalMode      string                 `json:"journalMode"`
	NodesByKind      map[model.NodeKind]int `json:"nodesByKind"`
	Languages        []string               `json:"languages"`
	PendingChanges   *PendingChanges        `json:"pendingChanges"` // null when not checked (--no-pending, stale index)
	WorktreeMismatch any                    `json:"worktreeMismatch"`
	Index            IndexInfo              `json:"index"`
	// UpgradeNeeded is set when the index cannot be read fully until
	// `codegrapher sync` (or --refresh) upgrades it; the other fields are then
	// best-effort.
	UpgradeNeeded string   `json:"upgradeNeeded,omitempty"`
	Warnings      []string `json:"warnings,omitempty"`
}

StatusResult is the JSON payload for `codegrapher status`.

type StoreQuerier

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

StoreQuerier implements GraphQuerier by fanning each operation out across a slice of per-scope stores and merging the results in Go. The data model is one SQLite DB per (language, version) scope; every underlying query func is single-scope, so whole-repo answers come from running each query per store and merging — mirroring mcp.MultiBackend.

For a single store, every method delegates to behavior byte-identical to the previous single-store StoreQuerier.

Tests use mockQuerier instead.

func (*StoreQuerier) Callees

func (q *StoreQuerier) Callees(symbol string) (*CalleesResult, error)

func (*StoreQuerier) Callers

func (q *StoreQuerier) Callers(symbol string) (*CallersResult, error)

func (*StoreQuerier) Files

func (q *StoreQuerier) Files() ([]FileInfo, error)

func (*StoreQuerier) Impact

func (q *StoreQuerier) Impact(symbol string, depth int) (*ImpactResult, error)

func (*StoreQuerier) SearchNodes

func (q *StoreQuerier) SearchNodes(rawQuery string, opts SearchOptions) ([]model.SearchResult, error)

func (*StoreQuerier) Status

func (q *StoreQuerier) Status(projectPath string) (*StatusResult, error)

type SymbolRef

type SymbolRef struct {
	Name      string         `json:"name"`
	Kind      model.NodeKind `json:"kind"`
	FilePath  string         `json:"filePath"`
	StartLine int            `json:"startLine"`
}

SymbolRef is the shape used in callers/callees/affected arrays. Matches the `callers`/`callees` array element shape in the golden JSON.

Jump to

Keyboard shortcuts

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