query

package
v0.2.8 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindBest

func FindBest(g graph.Graph, query string) (graph.Node, bool)

func IsTargetError

func IsTargetError(err error, kind TargetErrorKind) bool

IsTargetError reports whether err is a target-resolution error of kind.

func ShortestPath

func ShortestPath(g graph.Graph, fromQuery, toQuery string) ([]graph.Node, bool)

func WriteAffected

func WriteAffected(w io.Writer, result Retrieval, jsonOut bool) error

WriteAffected writes the same bounded retrieval envelope with an explicit reverse-impact label in compact text mode.

func WriteExplanation

func WriteExplanation(w io.Writer, ex Explanation, jsonOut bool) error

func WritePath

func WritePath(w io.Writer, nodes []graph.Node, jsonOut bool) error

func WritePathResult

func WritePathResult(w io.Writer, result PathResult, jsonOut bool) error

WritePathResult emits explicit mode, edge kind, edge orientation, and hop direction. It never renders a reverse fallback hop as a directed arrow.

func WriteRetrieval

func WriteRetrieval(w io.Writer, result Retrieval, jsonOut bool) error

WriteRetrieval writes compact, model-safe text or the structured result.

func WriteSearch

func WriteSearch(w io.Writer, results []SearchResult, jsonOut bool) error

Types

type AffinityRescue added in v0.2.6

type AffinityRescue struct {
	ID             string  `json:"id"`
	OriginalRank   int     `json:"originalRank"`
	RerankedRank   int     `json:"rerankedRank"`
	Affinity       float64 `json:"affinity"`
	AffinityMargin float64 `json:"affinityMargin"`
}

AffinityRescue describes one below-cutoff lexical candidate promoted by bounded graph affinity. Margin is relative to the strongest rejected rescue.

type ContextEdge

type ContextEdge struct {
	ID         string         `json:"id"`
	Kind       graph.EdgeKind `json:"kind"`
	From       string         `json:"from"`
	To         string         `json:"to"`
	Confidence string         `json:"confidence,omitempty"`
	Evidence   string         `json:"evidence,omitempty"`
	Rationale  string         `json:"rationale,omitempty"`
	Path       string         `json:"path,omitempty"`
	Line       int            `json:"line,omitempty"`
	Resolved   *bool          `json:"resolved,omitempty"`
}

type ContextNode

type ContextNode struct {
	ID         string         `json:"id"`
	Kind       graph.NodeKind `json:"kind"`
	Name       string         `json:"name"`
	Path       string         `json:"path,omitempty"`
	Package    string         `json:"package,omitempty"`
	StartLine  int            `json:"startLine,omitempty"`
	EndLine    int            `json:"endLine,omitempty"`
	Score      int            `json:"score,omitempty"`
	Depth      int            `json:"depth"`
	Degree     int            `json:"degree"`
	Seed       bool           `json:"seed,omitempty"`
	ViaEdgeID  string         `json:"viaEdgeId,omitempty"`
	Confidence string         `json:"confidence,omitempty"`
	Resolved   *bool          `json:"resolved,omitempty"`
}

type Direction

type Direction string
const (
	DirectionOut  Direction = "out"
	DirectionIn   Direction = "in"
	DirectionBoth Direction = "both"
)

type Explanation

type Explanation struct {
	Target    graph.Node   `json:"target"`
	Defines   []graph.Node `json:"defines,omitempty"`
	Imports   []graph.Node `json:"imports,omitempty"`
	Calls     []graph.Node `json:"calls,omitempty"`
	CalledBy  []graph.Node `json:"calledBy,omitempty"`
	Contained []graph.Node `json:"contained,omitempty"`
	DefinedIn []graph.Node `json:"definedIn,omitempty"`
	Outgoing  []Relation   `json:"outgoing,omitempty"`
	Incoming  []Relation   `json:"incoming,omitempty"`
}

func Explain

func Explain(g graph.Graph, target string) (Explanation, bool)

type Index

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

Index is an immutable, reusable query index over a graph. It keeps retrieval state out of graph.json while avoiding repeated normalization and adjacency construction for benchmark suites and long-running integrations.

func LoadOrBuildIndex added in v0.2.8

func LoadOrBuildIndex(graphData []byte, cacheDir string) (*Index, bool, error)

LoadOrBuildIndex loads a graph-hash-keyed immutable index from cache or builds one from graphData. Cache failures are intentionally best-effort: malformed or unwritable cache state never prevents a valid graph query.

func NewIndex

func NewIndex(g graph.Graph) *Index

NewIndex constructs a deterministic, in-memory retrieval index.

func (*Index) Affected

func (idx *Index) Affected(target string, options RetrieveOptions) (Retrieval, error)

Affected is the reusable-index form of impact retrieval.

func (*Index) Counts added in v0.2.8

func (idx *Index) Counts() (nodes, edges int)

Counts reports the immutable graph size represented by the index.

func (*Index) Explain

func (idx *Index) Explain(target string) (Explanation, bool)

Explain returns the immediate relationships for the best matching target while reusing the index's immutable graph snapshot.

func (*Index) ExplainResolved

func (idx *Index) ExplainResolved(target string) (Explanation, error)

ExplainResolved returns the immediate relationships for a strictly resolved target. Unlike the compatibility Explain wrapper, it preserves ambiguity and not-found errors for interactive callers.

func (*Index) FindBest

func (idx *Index) FindBest(query string) (graph.Node, bool)

FindBest resolves exact IDs, paths, and names before falling back to ranked retrieval. Exact matching remains stable for explain and path compatibility.

func (*Index) ResolveTarget

func (idx *Index) ResolveTarget(query string) (graph.Node, error)

ResolveTarget resolves IDs first, then source/container paths, then names. Duplicate exact names are rejected rather than depending on graph order. A canonical source node wins an exact path shared with symbols defined in that source (for example a file path shared by every function in the file).

func (*Index) Retrieve

func (idx *Index) Retrieve(text string, options RetrieveOptions) (Retrieval, error)

Retrieve ranks multiple lexical seeds and expands their graph neighborhood.

func (*Index) Search

func (idx *Index) Search(text string, limit int) []SearchResult

Search performs ranked lexical retrieval without graph expansion.

func (*Index) ShortestPath

func (idx *Index) ShortestPath(fromQuery, toQuery string) ([]graph.Node, bool)

ShortestPath finds a directed path first and then an undirected fallback while reusing the index's immutable graph snapshot.

func (*Index) ShortestPathResult

func (idx *Index) ShortestPathResult(fromQuery, toQuery string) (PathResult, bool, error)

ShortestPathResult is the reusable-index form of ShortestPathResultFor.

type PathHop

type PathHop struct {
	From      string           `json:"from"`
	To        string           `json:"to"`
	Direction PathHopDirection `json:"direction"`
	Edge      graph.Edge       `json:"edge"`
}

PathHop preserves both traversal direction and the original edge orientation. Reverse hops occur only in an undirected fallback.

type PathHopDirection

type PathHopDirection string
const (
	PathHopForward PathHopDirection = "forward"
	PathHopReverse PathHopDirection = "reverse"
)

type PathMode

type PathMode string
const (
	PathDirected           PathMode = "directed"
	PathUndirectedFallback PathMode = "undirected_fallback"
)

type PathResult

type PathResult struct {
	Mode  PathMode     `json:"mode"`
	Nodes []graph.Node `json:"nodes"`
	Hops  []PathHop    `json:"hops"`
}

PathResult is an honest shortest-path envelope. Mode distinguishes a fully directed path from a connectivity-only undirected fallback.

func ShortestPathResultFor

func ShortestPathResultFor(g graph.Graph, fromQuery, toQuery string) (PathResult, bool, error)

ShortestPathResult resolves both targets strictly, searches directed edges first, and labels any undirected fallback explicitly.

type Relation

type Relation struct {
	Kind graph.EdgeKind    `json:"kind"`
	Node graph.Node        `json:"node"`
	Meta map[string]string `json:"meta,omitempty"`
}

type Retrieval

type Retrieval struct {
	Version int            `json:"version"`
	Query   string         `json:"query"`
	Nodes   []ContextNode  `json:"nodes"`
	Edges   []ContextEdge  `json:"edges"`
	Stats   RetrievalStats `json:"stats"`
}

func Affected

func Affected(g graph.Graph, target string, options RetrieveOptions) (Retrieval, error)

Affected retrieves dependents for one resolved graph target. Dependency relations are traversed in reverse. Explicit affects/flows_to queries are traversed forward because those edge kinds already point at affected nodes.

func Retrieve

func Retrieve(g graph.Graph, text string, options RetrieveOptions) (Retrieval, error)

Retrieve is the graph-level compatibility wrapper around Index.Retrieve.

type RetrievalStats

type RetrievalStats struct {
	Traversal               Traversal        `json:"traversal"`
	Direction               Direction        `json:"direction"`
	DirectionPreference     Direction        `json:"directionPreference,omitempty"`
	Depth                   int              `json:"depth"`
	SeedIDs                 []string         `json:"seedIds"`
	RelationFilters         []graph.EdgeKind `json:"relationFilters,omitempty"`
	RelationFilterFrom      string           `json:"relationFilterFrom,omitempty"`
	TokenBudget             int              `json:"tokenBudget"`
	OutputTokenBudget       int              `json:"outputTokenBudget,omitempty"`
	EstimatedTokens         int              `json:"estimatedTokens"`
	HubThreshold            int              `json:"hubThreshold,omitempty"`
	BranchFanout            int              `json:"branchFanout,omitempty"`
	HubsSuppressed          int              `json:"hubsSuppressed,omitempty"`
	BranchesPruned          int              `json:"branchesPruned,omitempty"`
	ExploredNodes           int              `json:"exploredNodes"`
	LexicalCandidates       int              `json:"lexicalCandidates,omitempty"`
	DeduplicatedNodes       int              `json:"deduplicatedNodes,omitempty"`
	ExplanationEdgesOmitted int              `json:"explanationEdgesOmitted,omitempty"`
	UnselectedNodes         int              `json:"unselectedNodes,omitempty"`
	HeaderTokens            int              `json:"headerTokens,omitempty"`
	CandidateTokens         int              `json:"candidateTokens,omitempty"`
	ExplanationTokens       int              `json:"explanationTokens,omitempty"`
	OmittedNodes            int              `json:"omittedNodes,omitempty"`
	OmittedEdges            int              `json:"omittedEdges,omitempty"`
	Truncated               bool             `json:"truncated"`
	TruncatedReason         []string         `json:"truncatedReason,omitempty"`
	CommunityBoost          bool             `json:"communityBoost,omitempty"`
	SameFileRescues         []SameFileRescue `json:"sameFileRescues,omitempty"`
	AffinityRescues         []AffinityRescue `json:"affinityRescues,omitempty"`
	StructuredCandidates    int              `json:"structuredCandidates,omitempty"`
	StructuredQueryAnchors  int              `json:"structuredQueryAnchors,omitempty"`
	TraceNodes              []RetrievalTrace `json:"traceNodes,omitempty"`
}

type RetrievalTrace added in v0.2.6

type RetrievalTrace struct {
	ID                  string  `json:"id"`
	Indexed             bool    `json:"indexed"`
	LexicalRank         int     `json:"lexicalRank,omitempty"`
	PromotionRank       int     `json:"promotionRank,omitempty"`
	PromotionExclusion  string  `json:"promotionExclusion,omitempty"`
	OriginalLexicalRank int     `json:"originalLexicalRank,omitempty"`
	SameFileRescued     bool    `json:"sameFileRescued,omitempty"`
	SameFileAnchorPath  string  `json:"sameFileAnchorPath,omitempty"`
	AffinityRescued     bool    `json:"affinityRescued,omitempty"`
	AffinityScore       float64 `json:"affinityScore,omitempty"`
	AffinityMargin      float64 `json:"affinityMargin,omitempty"`
	TraversalExclusion  string  `json:"traversalExclusion,omitempty"`
	Seeded              bool    `json:"seeded,omitempty"`
	Traversed           bool    `json:"traversed,omitempty"`
	Depth               int     `json:"depth,omitempty"`
	WalkRank            int     `json:"walkRank,omitempty"`
	CandidateRank       int     `json:"candidateRank,omitempty"`
	ReturnedRank        int     `json:"returnedRank,omitempty"`
	Deduplicated        bool    `json:"deduplicated,omitempty"`
	DroppedReason       string  `json:"droppedReason,omitempty"`
}

RetrievalTrace records how one requested node moved through retrieval. It is diagnostic only: traced nodes never affect ranking, traversal, or packing.

type RetrieveOptions

type RetrieveOptions struct {
	Traversal                Traversal        `json:"traversal"`
	Direction                Direction        `json:"direction"`
	Relations                []graph.EdgeKind `json:"relations,omitempty"`
	DisableRelationInference bool             `json:"disableRelationInference,omitempty"`
	SeedLimit                int              `json:"seedLimit"`
	MaxDepth                 int              `json:"maxDepth"`
	MaxNodes                 int              `json:"maxNodes"`
	BranchFanout             int              `json:"branchFanout"`
	HubDegreeThreshold       int              `json:"hubDegreeThreshold"`
	TokenBudget              int              `json:"tokenBudget"`
	CommunityBoost           bool             `json:"communityBoost,omitempty"`
	CandidateShortlist       bool             `json:"candidateShortlist,omitempty"`
	TraceNodeIDs             []string         `json:"traceNodeIds,omitempty"`
}

RetrieveOptions controls ranked seeding, graph traversal, and output bounds. Zero values select the documented defaults. Set HubDegreeThreshold to -1 to disable hub suppression.

type SameFileRescue added in v0.2.6

type SameFileRescue struct {
	ID             string `json:"id"`
	AnchorPath     string `json:"anchorPath"`
	AnchorCount    int    `json:"anchorCount"`
	OriginalRank   int    `json:"originalRank"`
	StructuralSlot int    `json:"structuralSlot"`
}

SameFileRescue describes one lexical candidate promoted because a stronger candidate or bounded traversal result points at the same source file.

type SearchResult

type SearchResult struct {
	Node  graph.Node `json:"node"`
	Score int        `json:"score"`
}
func Search(g graph.Graph, term string, limit int) []SearchResult

type TargetError

type TargetError struct {
	Kind       TargetErrorKind
	Query      string
	Candidates []graph.Node
}

TargetError reports an unresolved or ambiguous target. Candidates are sorted by stable node ID so callers can present deterministic guidance.

func (*TargetError) Error

func (e *TargetError) Error() string

type TargetErrorKind

type TargetErrorKind string

TargetErrorKind identifies why an exact query target could not be resolved.

const (
	TargetNotFound  TargetErrorKind = "not_found"
	TargetAmbiguous TargetErrorKind = "ambiguous"
)

type Traversal

type Traversal string
const (
	TraversalBFS Traversal = "bfs"
	TraversalDFS Traversal = "dfs"
)

Jump to

Keyboard shortcuts

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