graph

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package graph builds a per-repository code graph — symbols (functions, types, methods, …) and the call/reference edges between them — and stores it in SQLite so an AI coding agent can query structure instead of reading whole files.

Parsing is pluggable: each language is handled by a ParserProvider. Go uses the standard library (precise); other languages use tree-sitter or ast-grep backends registered alongside it. All backends are pure-Go or out-of-process, so orchard stays a CGo-free binary.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ASTGrepAvailable

func ASTGrepAvailable() bool

ASTGrepAvailable reports whether orchard can use the ast-grep backend for non-Go languages. It follows the same resolution order as DefaultRegistry.

func ASTGrepSupports

func ASTGrepSupports(lang string) bool

ASTGrepSupports reports whether ast-grep is orchard's parser backend for the given graph language label.

func DBPath

func DBPath(repoAbs string) (string, error)

DBPath returns the graph database path for a repo's absolute path.

func InstallASTGrep

func InstallASTGrep(ctx context.Context) (string, error)

InstallASTGrep downloads the pinned ast-grep for the current platform into <user-config>/orchard/bin (verifying its SHA-256) and returns the binary path, so non-Go languages work without the user installing ast-grep separately. Downloading via Go's HTTP client (not a browser) means no macOS quarantine xattr is set, so the binary runs without a Gatekeeper prompt.

func RemoveForRepo

func RemoveForRepo(repoAbs string) (bool, error)

RemoveForRepo deletes a repo's code-graph database and its WAL/SHM sidecars. It returns ok=true if a graph existed and was removed. A deleted graph is simply rebuilt on the next build, so this is a safe, reversible cleanup.

Types

type BuildStats

type BuildStats struct {
	Files         int
	Symbols       int
	Edges         int
	ResolvedEdges int
	Skipped       int          // dropped by binary/generated/oversize filters
	Unsupported   int          // recognized language with no registered provider
	Diagnostics   int          // files that parsed with warnings/errors
	ByTier        map[Tier]int // files per quality tier
}

BuildStats summarizes a build for reporting.

type CallerRow

type CallerRow struct {
	Caller, Path string
	Line         int
	Rank         float64
}

CallerRow is an inbound call/reference site returned by WhoCalls.

type Confidence

type Confidence string

Confidence labels how an edge's target was resolved. go/ast edges are syntactically exact; tree-sitter / ast-grep edges are heuristic name matches.

const (
	// Extracted: the referenced name resolves to a single indexed definition.
	Extracted Confidence = "extracted"
	// Inferred: a reference whose target was not found (external / unknown).
	Inferred Confidence = "inferred"
	// Ambiguous: the name matches more than one indexed definition.
	Ambiguous Confidence = "ambiguous"
)

type DefRow

type DefRow struct {
	Name, Kind, Signature, Path string
	Line                        int
	Rank                        float64
}

DefRow is a definition site returned by FindDef.

type DiscoveredFile

type DiscoveredFile struct {
	Rel  string // repo-relative path
	Lang string // language label (see extLang)
	Data []byte
	SHA  string // sha256 of Data (hex), for incremental reindex later
}

DiscoveredFile is one candidate source file together with its contents.

func Discover

func Discover(ctx context.Context, repo string) (files []DiscoveredFile, skipped int, err error)

Discover lists git-tracked source files in repo, skipping ignored (untracked) files for free and dropping binary, generated, and oversized files. skipped counts files dropped by the binary/generated/oversize filters.

type Edge

type Edge struct {
	SrcName string // enclosing definition where the reference appears ("" = file scope)
	DstName string // the referenced name (the callee)
	Kind    EdgeKind
	Line    int
}

Edge is a reference from an enclosing symbol to a (possibly external) name.

type EdgeKind

type EdgeKind string

EdgeKind classifies a relationship between a symbol and a referenced name.

const (
	EdgeCall      EdgeKind = "call"
	EdgeReference EdgeKind = "reference"
	EdgeImport    EdgeKind = "import"
	EdgeInherit   EdgeKind = "inherit"
)

type FileGraph

type FileGraph struct {
	File    fileMeta
	Symbols []Symbol
	Edges   []Edge
}

FileGraph is one file's contribution to the graph: its metadata plus the symbols and edges a provider extracted from it.

type FileResult

type FileResult struct {
	Symbols     []Symbol
	Edges       []Edge
	Diagnostics []string // parse warnings/errors; empty means a clean parse
}

FileResult is what a ParserProvider returns for one file.

type Freshness

type Freshness struct {
	BuiltAt    time.Time
	HeadCommit string
	DirtyFiles int
}

Freshness describes when/what the graph was last built against.

type Graph

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

Graph is a per-repository code graph backed by SQLite.

func Open

func Open(dbPath string) (*Graph, error)

Open opens (or creates) the graph database at dbPath.

func OpenForRepo

func OpenForRepo(repoAbs string) (*Graph, error)

OpenForRepo opens (creating dirs/DB as needed) the graph for a repo's absolute path, under orchard's config directory.

func (*Graph) BlastRadius

func (g *Graph) BlastRadius(name string, maxDepth, limit int) ([]ImpactRow, error)

BlastRadius returns everything transitively reachable backwards from name (its callers, their callers, …) up to maxDepth, capped at limit — the impact of changing it.

func (*Graph) Build

func (g *Graph) Build(ctx context.Context, repoPath string, reg *Registry) (BuildStats, error)

Build performs a full (re)index of repoPath, choosing a provider per language via reg, and replaces the graph. It is I/O- and CPU-heavy; run it off the UI thread.

func (*Graph) Close

func (g *Graph) Close() error

Close closes the underlying database.

func (*Graph) Counts

func (g *Graph) Counts() (files, symbols, edges, resolvedEdges int)

Counts returns the graph's row totals plus how many edges resolved.

func (*Graph) FindDef

func (g *Graph) FindDef(name string, limit int) ([]DefRow, error)

FindDef returns up to limit definition sites for a symbol name, important first.

func (*Graph) Freshness

func (g *Graph) Freshness() Freshness

Freshness returns the recorded build metadata (for surfacing to the agent).

func (*Graph) RepoMap

func (g *Graph) RepoMap(limit int) ([]MapRow, error)

RepoMap returns the top-ranked definitions (a PageRank-ordered skeleton), capped at limit — the token-budgeted overview of the repo.

func (*Graph) SearchSymbols

func (g *Graph) SearchSymbols(query string, limit int) ([]DefRow, error)

SearchSymbols finds definitions whose name contains query, important first, capped at limit.

func (*Graph) Stale

func (g *Graph) Stale(ctx context.Context, repoPath string) (stale bool, changed int, err error)

Stale reports whether the working tree differs from the indexed graph (by content hash) without rebuilding, and how many files changed/added/deleted.

func (*Graph) TierCounts

func (g *Graph) TierCounts() map[Tier]int

TierCounts returns indexed file counts grouped by parser quality tier.

func (*Graph) TrustLabels

func (g *Graph) TrustLabels() []LangTrust

TrustLabels returns indexed file counts grouped by language and parser tier.

func (*Graph) Update

func (g *Graph) Update(ctx context.Context, repoPath string, reg *Registry) (UpdateStats, error)

Update incrementally reindexes repoPath: it re-parses only files whose content hash changed (or are new), reuses unchanged files from the DB, and re-resolves the whole graph — producing the same result as a full Build but without re-parsing untouched files. If nothing changed it only refreshes metadata.

func (*Graph) WhoCalls

func (g *Graph) WhoCalls(name string, limit, offset int) ([]CallerRow, error)

WhoCalls returns inbound call/reference sites for a symbol name, ordered by caller importance, paginated by limit/offset.

type GraphState

type GraphState struct {
	HeadCommit string
	DirtyFiles int
	BuiltAt    time.Time
	Files      int
	Symbols    int
	Edges      int
	Tiers      map[Tier]int
	Trust      []LangTrust
	Stale      bool
	Changed    int
}

GraphState is a quick, read-only snapshot of a repo's built graph, for UI badges and the detail view. It parses and builds nothing.

func StateFor

func StateFor(repoAbs string) (GraphState, bool)

StateFor returns the stored graph snapshot for a repo, or ok=false if no (non-empty) graph has been built yet. It opens the existing DB read-only and never creates one, so it is cheap enough to call per-repo off the UI thread.

type ImpactRow

type ImpactRow struct {
	Name, Path string
	Depth      int
}

ImpactRow is a transitively-affected symbol returned by BlastRadius.

type Kind

type Kind string

Kind classifies a defined symbol.

const (
	KindFunc      Kind = "function"
	KindMethod    Kind = "method"
	KindClass     Kind = "class"
	KindStruct    Kind = "struct"
	KindInterface Kind = "interface"
	KindType      Kind = "type"
	KindVar       Kind = "var"
	KindConst     Kind = "const"
	KindModule    Kind = "module"
)

type LangTrust

type LangTrust struct {
	Lang  string `json:"language"`
	Tier  Tier   `json:"tier"`
	Files int    `json:"files"`
}

LangTrust describes the parser quality used for a language in a built graph.

type MapRow

type MapRow struct {
	Path, Kind, Name, Signature string
	Rank                        float64
}

MapRow is one entry in the ranked repo map.

type ParserProvider

type ParserProvider interface {
	// Name identifies the backend, e.g. "go/ast" or "ast-grep".
	Name() string
	// Tier reports the expected parse quality for a language label.
	Tier(lang string) Tier
	// Extract parses files (all of language lang, located under repoRoot) and
	// returns a FileResult keyed by SourceFile.Rel. A file that partially fails
	// should yield a FileResult with Diagnostics rather than aborting the batch,
	// so one bad file never fails the build.
	Extract(ctx context.Context, repoRoot, lang string, files []SourceFile) (map[string]FileResult, error)
}

ParserProvider extracts symbols and edges from a batch of same-language files.

Implementations are language backends (go/ast in-process; ast-grep out-of-process). Batch (rather than per-file) so an external tool like ast-grep can scan a whole repo in one invocation instead of spawning a process per file. A provider may handle several languages; Tier reports its expected quality per language so callers can label results.

type Registry

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

Registry maps a language label to the ParserProvider that handles it.

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry wires the providers available in this build:

  • Go via go/ast (precise, in-process);
  • every other supported language via ast-grep (real tree-sitter scanners), when the ast-grep binary is present.

If ast-grep is not installed, the non-Go languages are left unregistered and Build counts them as Unsupported (skipped) rather than mis-parsing them.

func (*Registry) For

func (r *Registry) For(lang string) (ParserProvider, bool)

For returns the provider registered for a language label, if any.

type SourceFile

type SourceFile struct {
	Rel  string
	Data []byte
}

SourceFile is one file handed to a provider: its repo-relative path and bytes.

type Store

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

Store is the per-repo SQLite graph database. It owns the schema and the queries; orchestration lives in Graph (graph.go).

func (*Store) Close

func (s *Store) Close() error

Close closes the underlying database.

type Symbol

type Symbol struct {
	Name      string
	Kind      Kind
	Signature string // one-line skeleton (no body), for the repo map
	StartLine int
	EndLine   int
}

Symbol is a defined entity in a file — a node in the graph.

type Tier

type Tier string

Tier is the parse quality a provider expects for a language. It is surfaced to the agent so it knows how much to trust the graph versus reading the file.

const (
	TierPrecise     Tier = "precise"     // exact semantics (Go via go/ast)
	TierGood        Tier = "good"        // clean tree-sitter parse
	TierBestEffort  Tier = "best-effort" // partial parse; some symbols may be missing
	TierUnsupported Tier = "unsupported"
)

type UpdateStats

type UpdateStats struct {
	Changed, Added, Deleted, Reused      int
	Files, Symbols, Edges, ResolvedEdges int
}

UpdateStats summarizes an incremental update.

Jump to

Keyboard shortcuts

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