tools

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: AGPL-3.0 Imports: 37 Imported by: 0

Documentation

Overview

Package tools provides CLI tools for graph queries.

Tool implementations have been refactored into individual files:

  • tool_find_callers.go: find_callers tool
  • tool_find_callees.go: find_callees tool
  • tool_find_implementations.go: find_implementations tool
  • tool_find_symbol.go: find_symbol tool
  • tool_get_call_chain.go: get_call_chain tool
  • tool_find_references.go: find_references tool
  • tool_find_hotspots.go: find_hotspots tool
  • tool_find_dead_code.go: find_dead_code tool
  • tool_find_cycles.go: find_cycles tool
  • tool_find_path.go: find_path tool
  • tool_find_entry_points.go: find_entry_points tool
  • tool_find_important.go: find_important tool
  • tool_find_communities.go: find_communities tool
  • tool_find_similar_code.go: find_similar_code tool
  • tool_find_config_usage.go: find_config_usage tool

Shared helpers are in tool_helpers.go.

Package tools provides the tool registry and execution framework for the agent.

Tools are the primary mechanism for the agent to interact with the codebase and external systems. Each tool is defined by a ToolDefinition that describes its parameters and capabilities, and implements the Tool interface for execution.

Thread Safety:

All types in this package are designed for concurrent use.

Index

Constants

View Source
const (
	// MaxToolCallsPerRequest limits tool calls per dispatch to prevent DoS.
	MaxToolCallsPerRequest = 20

	// MaxParamsSize limits parameter JSON size to prevent memory exhaustion.
	MaxParamsSize = 1 << 20 // 1MB

	// MaxOutputSize limits output size before truncation.
	MaxOutputSize = 1 << 22 // 4MB
)

Security limits.

View Source
const (
	// DefaultMaxOutputBytes is the default maximum output size.
	DefaultMaxOutputBytes = 100 * 1024 // 100KB

	// DefaultMaxOutputTokens is the soft limit for context budget.
	DefaultMaxOutputTokens = 30000

	// CharsPerTokenEstimate is the character-to-token ratio for estimation.
	CharsPerTokenEstimate = 3.5
)

Default configuration values.

View Source
const (
	// MetaKeySanitized indicates if content was sanitized.
	MetaKeySanitized = "sanitized"

	// MetaKeyEscapedPatterns lists patterns that were escaped.
	MetaKeyEscapedPatterns = "escaped_patterns"

	// MetaKeySuspiciousPatterns lists suspicious patterns found.
	MetaKeySuspiciousPatterns = "suspicious_patterns"

	// MetaKeyOriginalLength is the original content length.
	MetaKeyOriginalLength = "original_length"

	// MetaKeyWasTruncated indicates if content was truncated.
	MetaKeyWasTruncated = "was_truncated"
)

Metadata keys for sanitization results.

View Source
const DefaultMaxOutputLen = 30000

DefaultMaxOutputLen is the default maximum output length before truncation.

View Source
const DefaultTruncateMsg = "\n... [output truncated]"

DefaultTruncateMsg is the message appended when output is truncated.

Variables

View Source
var (
	// ErrToolNotFound indicates the requested tool does not exist.
	ErrToolNotFound = errors.New("tool not found")

	// ErrValidationFailed indicates parameter validation failed.
	ErrValidationFailed = errors.New("parameter validation failed")

	// ErrExecutionFailed indicates tool execution failed.
	ErrExecutionFailed = errors.New("tool execution failed")

	// ErrTimeout indicates the tool execution timed out.
	ErrTimeout = errors.New("tool execution timed out")

	// ErrRequirementNotMet indicates a tool requirement is not satisfied.
	ErrRequirementNotMet = errors.New("tool requirement not met")
)

Sentinel errors for the executor.

View Source
var (
	// ErrNoToolCalls indicates no tool calls were found in the input.
	ErrNoToolCalls = errors.New("no tool calls found")

	// ErrMalformedToolCall indicates a tool call was found but malformed.
	ErrMalformedToolCall = errors.New("malformed tool call")

	// ErrInvalidParams indicates parameters could not be parsed as JSON.
	ErrInvalidParams = errors.New("invalid parameters JSON")
)

Sentinel errors for parsing.

Functions

func DetectEntryPoint

func DetectEntryPoint(ctx context.Context, idx *index.SymbolIndex, analytics *graph.GraphAnalytics) (string, error)

DetectEntryPoint finds a suitable entry point for dominator analysis.

Description:

Searches for well-known entry point functions (main, init) using the symbol
index, then falls back to graph analytics to detect nodes with no incoming edges.
This is the canonical method for finding entry points and should be used by all
tools requiring dominator tree computation.

Inputs:

  • ctx: Context for cancellation. Must not be nil.
  • idx: Symbol index for name-based search. May be nil (will skip index search).
  • analytics: Graph analytics for detecting entry nodes. Must not be nil.

Outputs:

  • string: Node ID of the detected entry point.
  • error: Non-nil if no suitable entry point found.

Thread Safety: Safe for concurrent use (read-only operations).

func DisambiguateGraphNodes

func DisambiguateGraphNodes(syms []*ast.Symbol) *ast.Symbol

DisambiguateGraphNodes picks the best symbol from multiple graph nodes with the same name using multi-signal scoring. Uses the same penalty signals as phases.disambiguateMultipleMatches (IT-05 SR1) to maintain scoring consistency.

Description:

IT-00a-1 Phase 2: When the graph fallback returns multiple nodes matching a
function name, this function scores each candidate and returns the best one
instead of taking an arbitrary first result.

Scoring signals (lower is better):
  - Test file: +50000
  - Unexported: +20000
  - Underscore prefix: +10000
  - Directory depth beyond 2: +1000 per level
  - Kind: function/method = 0, type = +1, other = +2

Inputs:

syms - Slice of symbols to choose from (len >= 1).

Outputs:

*ast.Symbol - The best-scoring symbol.

Thread Safety: Safe for concurrent use (stateless function).

func IsGraphNodeTestFile

func IsGraphNodeTestFile(filePath string) bool

IsGraphNodeTestFile checks if a file path indicates a test file. Mirrors phases.isTestFilePath and index.isTestFile for cross-package consistency.

func RegisterExploreTools

func RegisterExploreTools(registry *Registry, g *graph.Graph, idx *index.SymbolIndex)

RegisterExploreTools registers all CB-20 explore tools with the registry.

Description:

Registers adapters for the exploration tools from the explore package.
These tools require a graph and index to be initialized.

Inputs:

registry - The tool registry
g - The code graph
idx - The symbol index

func RegisterSemanticTools

func RegisterSemanticTools(
	registry *Registry,
	wvClient *weaviate.Client,
	dataSpace string,
	embedClient *rag.EmbedClient,
	idx *index.SymbolIndex,
)

RegisterSemanticTools registers CRS-26m semantic search tools with the registry.

Description:

Registers tools for vector-based semantic code search. These tools require
Weaviate for vector storage and an EmbedClient for query embedding.
Gracefully degrades if dependencies are nil.

Inputs:

registry - The tool registry.
wvClient - Weaviate client for vector search.
dataSpace - Project isolation key for Weaviate.
embedClient - Embedding client for query vectorization.
idx - Symbol index for O(1) lookups.

Thread Safety: Safe for concurrent use after construction.

func ResolveFunctionCandidates

func ResolveFunctionCandidates(
	ctx context.Context,
	idx *index.SymbolIndex,
	name string,
	logger *slog.Logger,
	maxCandidates int,
	opts ...ResolveFuzzyOpt,
) ([]*ast.Symbol, error)

ResolveFunctionCandidates returns up to maxCandidates symbols matching the given name, ranked with callable kinds (function/method) first.

Description:

IT-12 Rev 3: When graph traversal tools resolve a name to a type that has
0 call edges, they need alternative candidates to retry with. This function
provides ranked alternatives so tools can iterate until a useful result.

Uses the same resolution strategies as ResolveFunctionWithFuzzy (exact match,
dot-notation, bare method, fuzzy) but collects ALL matching symbols instead
of picking one, then sorts by callableFirstRank(). Within the same callable
rank, uses kindSignificance as tiebreaker (non-test files, shorter paths).

Inputs:

  • ctx: Context for timeout control. Must not be nil.
  • idx: Symbol index to search. Must not be nil.
  • name: Symbol name to resolve. Must not be empty.
  • logger: Logger for debugging. Must not be nil.
  • maxCandidates: Maximum number of candidates to return (must be >= 1).
  • opts: Optional configuration (WithKindFilter, WithBareMethodFallback).

Outputs:

  • []*ast.Symbol: Ranked candidates, callable-first. May be empty if no matches.
  • error: Non-nil if index is nil or name is empty.

Thread Safety: This function is safe for concurrent use.

Example:

candidates, err := ResolveFunctionCandidates(ctx, idx, "Sites", logger, 3,
    WithKindFilter(KindFilterAny), WithBareMethodFallback())
for _, c := range candidates {
    result := graph.GetCallGraph(ctx, c.ID)
    if len(result.Edges) > 0 { /* use this candidate */ break }
}

func ResolveFunctionWithFuzzy

func ResolveFunctionWithFuzzy(
	ctx context.Context,
	index *index.SymbolIndex,
	name string,
	logger *slog.Logger,
	opts ...ResolveFuzzyOpt,
) (*ast.Symbol, bool, error)

ResolveFunctionWithFuzzy attempts to resolve a function name using exact match first, then falls back to fuzzy search if exact match fails.

Description:

Shared resolution helper for all graph query tools. Resolves a user-provided
symbol name to a concrete *ast.Symbol via a multi-strategy pipeline:
  1. Full-ID bypass: if name contains ":", treat as a full symbol ID
  2. Exact match: index.GetByName(name) with kind filtering
  3. Dot-notation: "Type.Method" split via resolveTypeDotMethod (4 strategies)
  4. Bare method fallback: try just method part when dot-notation fails (opt-in)
  5. Fuzzy search: index.Search with kind filtering

IT-00a (Feb 18, 2026): Extended with configurable kind filtering via
ResolveFuzzyOpt options. Default behavior (no options) preserves original
Function/Method/Property filtering for backward compatibility.

Inputs:

  • ctx: Context for timeout control (2 second timeout for fuzzy search). Must not be nil.
  • index: Symbol index to search. Must not be nil.
  • name: Symbol name to resolve (may be partial, dot-notation, or full ID).
  • logger: Logger for debugging and observability. Must not be nil.
  • opts: Optional configuration (WithKindFilter, WithBareMethodFallback).

Outputs:

  • *ast.Symbol: The resolved symbol. Never nil if error is nil.
  • bool: True if fuzzy matching was used, false for exact/dot-notation match.
  • error: Non-nil if symbol could not be found by any method.

Thread Safety: This function is safe for concurrent use.

Example:

// Default (callable symbols):
symbol, fuzzy, err := ResolveFunctionWithFuzzy(ctx, index, "Process", logger)

// Type-only symbols:
symbol, fuzzy, err := ResolveFunctionWithFuzzy(ctx, index, "Router", logger,
    WithKindFilter(KindFilterType))

// Any kind with bare method fallback:
symbol, fuzzy, err := ResolveFunctionWithFuzzy(ctx, index, "DB.Open", logger,
    WithKindFilter(KindFilterAny), WithBareMethodFallback())

func ResolveMultipleFunctionsWithFuzzy

func ResolveMultipleFunctionsWithFuzzy(
	ctx context.Context,
	index *index.SymbolIndex,
	names []string,
	logger *slog.Logger,
	opts ...ResolveFuzzyOpt,
) ([]*ast.Symbol, []bool, error)

ResolveMultipleFunctionsWithFuzzy resolves multiple function names, using fuzzy matching as fallback for each.

Description:

Batch version of ResolveFunctionWithFuzzy for tools that accept multiple
targets (e.g., find_common_dependency, find_path). Passes through any
ResolveFuzzyOpt options to each individual resolution call.

Inputs:

  • ctx: Context for timeout control. Must not be nil.
  • index: Symbol index to search. Must not be nil.
  • names: Function names to resolve. Must not be empty.
  • logger: Logger for debugging. Must not be nil.
  • opts: Optional configuration passed to each ResolveFunctionWithFuzzy call.

Outputs:

  • []*ast.Symbol: Resolved symbols (length matches input names). Nil on error.
  • []bool: Fuzzy match indicators (parallel to symbols). Nil on error.
  • error: Non-nil if ANY symbol could not be found.

Thread Safety: This function is safe for concurrent use.

Example:

symbols, fuzzy, err := ResolveMultipleFunctionsWithFuzzy(ctx, index,
    []string{"Handler", "Middleware"}, logger, WithKindFilter(KindFilterCallable))
if err != nil {
    return fmt.Errorf("failed to resolve targets: %w", err)
}

func SanitizeParams

func SanitizeParams(toolName string, params json.RawMessage) json.RawMessage

SanitizeParams removes or masks sensitive fields before logging.

Description:

Sanitizes parameters to prevent credential leaks in logs.
Must be called before any structured logging of tool parameters.

Inputs:

toolName - The tool name
params - The raw parameter JSON

Outputs:

json.RawMessage - Sanitized parameters safe for logging

Thread Safety: This function is safe for concurrent use.

func ScoreGraphNode

func ScoreGraphNode(sym *ast.Symbol) int

ScoreGraphNode computes a disambiguation score for a graph node symbol. Lower scores indicate more relevant symbols. Aligned with phases.scoreForDisambiguation to maintain cross-package scoring consistency.

func ValidateSymbolName

func ValidateSymbolName(name, paramName string, examples string) error

ValidateSymbolName checks that a symbol name parameter is non-empty and not a generic English word. Returns a user-facing error message that guides the LLM to retry with the correct symbol name.

Description:

Shared validation for all tools that accept a symbol/function/type name
parameter from LLM-extracted input. Rejects empty strings and generic words
with an error message that includes example symbol names to help the LLM
self-correct on retry.

Inputs:

  • name: The candidate symbol name to validate.
  • paramName: The parameter name for error messages (e.g., "function_name", "interface_name").
  • examples: Example valid symbol names for the error hint (e.g., "handleRequest", "Router").

Outputs:

  • error: Non-nil if validation fails, with a descriptive message.

Thread Safety: Safe for concurrent use.

Types

type APIFunction

type APIFunction struct {
	// ID is the full node identifier.
	ID string `json:"id"`

	// Name is the function name extracted from the ID.
	Name string `json:"name"`

	// ExternalCallers is the count of external nodes calling this function.
	ExternalCallers int `json:"external_callers"`

	// InternalNodesDominated is the count of internal nodes this function dominates.
	InternalNodesDominated int `json:"internal_nodes_dominated"`

	// Coverage is the fraction of the module dominated by this function (0.0 to 1.0).
	Coverage float64 `json:"coverage"`

	// Description is a human-readable explanation.
	Description string `json:"description"`
}

APIFunction represents a single API entry point.

type ApprovalFunc

type ApprovalFunc func(tool *ToolDefinition, params map[string]any) (bool, error)

ApprovalFunc is called to check if a tool execution should proceed. Returns true if approved, false if declined. The error return is for approval system failures, not user declining.

type ArticulationPointInfo

type ArticulationPointInfo struct {
	// ID is the full node ID of the articulation point.
	ID string `json:"id"`

	// Name is the function name of the articulation point.
	Name string `json:"name"`

	// File is the source file containing this articulation point.
	File string `json:"file,omitempty"`

	// Line is the line number in the source file.
	Line int `json:"line,omitempty"`

	// Kind is the symbol kind (function, method, etc.).
	Kind string `json:"kind,omitempty"`
}

ArticulationPointInfo holds information about a single articulation point.

type BackEdgeInfo

type BackEdgeInfo struct {
	From string `json:"from"`
	To   string `json:"to"`
}

BackEdgeInfo represents a back edge in a loop.

type BridgeInfo

type BridgeInfo struct {
	// From is the source node ID.
	From string `json:"from"`

	// To is the target node ID.
	To string `json:"to"`

	// FromName is the source function name.
	FromName string `json:"from_name"`

	// ToName is the target function name.
	ToName string `json:"to_name"`
}

BridgeInfo holds information about a critical edge.

type CallChainNode

type CallChainNode struct {
	// ID is the node ID.
	ID string `json:"id"`

	// Name is the function name.
	Name string `json:"name,omitempty"`

	// File is the source file path.
	File string `json:"file,omitempty"`

	// Line is the line number.
	Line int `json:"line,omitempty"`

	// Package is the package name.
	Package string `json:"package,omitempty"`

	// Depth is the BFS depth from the root node (0 for root).
	Depth int `json:"depth"`

	// CalledBy is the parent node ID in the call chain.
	CalledBy string `json:"called_by,omitempty"`

	// IsExternal indicates this node is an external dependency boundary.
	// IT-05a: Set when the node represents a call to an external library
	// that is not part of the indexed project.
	IsExternal bool `json:"is_external,omitempty"`

	// ExternalPkg is the inferred external package/module name.
	// Only set when IsExternal is true.
	ExternalPkg string `json:"external_package,omitempty"`
}

CallChainNode holds information about a node in the call chain.

type CalleeInfo

type CalleeInfo struct {
	// Name is the callee function name.
	Name string `json:"name"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Package is the package name.
	Package string `json:"package"`

	// Signature is the function signature.
	Signature string `json:"signature,omitempty"`

	// SourceID is the ID of the caller symbol.
	SourceID string `json:"source_id"`
}

CalleeInfo holds information about an in-codebase callee.

type CallerInfo

type CallerInfo struct {
	// Name is the caller function name.
	Name string `json:"name"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Package is the package name.
	Package string `json:"package"`

	// Signature is the function signature.
	Signature string `json:"signature,omitempty"`
}

CallerInfo holds information about a caller.

type CallerResult

type CallerResult struct {
	// TargetID is the symbol ID being called.
	TargetID string `json:"target_id"`

	// CallerCount is the number of callers for this target.
	CallerCount int `json:"caller_count"`

	// Callers is the list of caller symbols.
	Callers []CallerInfo `json:"callers"`
}

CallerResult represents callers for a specific target symbol.

type CheckReducibilityOutput

type CheckReducibilityOutput struct {
	// IsReducible is true if the entire graph is reducible.
	IsReducible bool `json:"is_reducible"`

	// Score is the percentage of nodes NOT in irreducible regions (0.0 to 1.0).
	Score float64 `json:"score"`

	// QualityLabel is a human-readable quality label.
	QualityLabel string `json:"quality_label"`

	// IrreducibleRegions contains detected irreducible subgraphs.
	IrreducibleRegions []IrreducibleRegionInfo `json:"irreducible_regions,omitempty"`

	// Summary contains aggregate statistics.
	Summary CheckReducibilitySummary `json:"summary"`

	// Recommendation provides actionable guidance.
	Recommendation string `json:"recommendation"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

CheckReducibilityOutput contains the structured result.

type CheckReducibilityParams

type CheckReducibilityParams struct {
	// ShowIrreducible indicates whether to list specific irreducible regions.
	// Default: true
	ShowIrreducible bool
}

CheckReducibilityParams contains the validated input parameters.

func (CheckReducibilityParams) ToMap

func (p CheckReducibilityParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (CheckReducibilityParams) ToolName

func (p CheckReducibilityParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type CheckReducibilitySummary

type CheckReducibilitySummary struct {
	// TotalNodes is the total nodes analyzed.
	TotalNodes int `json:"total_nodes"`

	// TotalEdges is the total edges analyzed.
	TotalEdges int `json:"total_edges"`

	// IrreducibleNodeCount is nodes in irreducible regions.
	IrreducibleNodeCount int `json:"irreducible_node_count"`

	// IrreducibleRegionCount is the number of irreducible regions.
	IrreducibleRegionCount int `json:"irreducible_region_count"`

	// CrossEdgeCount is the number of cross edges found.
	CrossEdgeCount int `json:"cross_edge_count"`

	// WellStructuredPercent is the percentage of well-structured code.
	WellStructuredPercent float64 `json:"well_structured_percent"`
}

CheckReducibilitySummary contains aggregate statistics.

type CommunityInfo

type CommunityInfo struct {
	// ID is the community identifier.
	ID int `json:"id"`

	// Size is the number of members in this community.
	Size int `json:"size"`

	// DominantPackage is the most common package in this community.
	DominantPackage string `json:"dominant_package"`

	// Packages lists all packages represented in this community.
	Packages []string `json:"packages"`

	// IsCrossPackage indicates if this community spans multiple packages.
	IsCrossPackage bool `json:"is_cross_package"`

	// Connectivity is the ratio of internal to total edges.
	Connectivity float64 `json:"connectivity"`

	// InternalEdges is the count of edges within this community.
	InternalEdges int `json:"internal_edges"`

	// ExternalEdges is the count of edges to other communities.
	ExternalEdges int `json:"external_edges"`

	// Members is a sample of member node IDs (limited to 10).
	Members []CommunityMember `json:"members"`
}

CommunityInfo holds information about a single community.

type CommunityMember

type CommunityMember struct {
	ID string `json:"id"`
}

CommunityMember represents a member of a community.

type ControlDependencySummary

type ControlDependencySummary struct {
	// TotalDependencies is the total control dependencies found.
	TotalDependencies int `json:"total_dependencies"`

	// MaxDepth is the maximum depth of the dependency chain.
	MaxDepth int `json:"max_depth"`

	// TopControllers is the number of controllers with most dependents.
	TopControllers int `json:"top_controllers"`

	// NodesAnalyzed is the total nodes considered.
	NodesAnalyzed int `json:"nodes_analyzed"`
}

ControlDependencySummary contains aggregate statistics.

type ControllerInfo

type ControllerInfo struct {
	// ID is the full node ID of the controller.
	ID string `json:"id"`

	// Name is the function name of the controller.
	Name string `json:"name"`

	// File is the source file path.
	File string `json:"file,omitempty"`

	// Line is the line number.
	Line int `json:"line,omitempty"`

	// Package is the package name.
	Package string `json:"package,omitempty"`

	// DependentsCount is how many nodes this controller controls.
	DependentsCount int `json:"dependents_count,omitempty"`

	// Depth is the distance from target in the dependency chain.
	Depth int `json:"depth,omitempty"`
}

ControllerInfo holds information about a controlling node.

type CriticalFunction

type CriticalFunction struct {
	ID               string  `json:"id"`
	Name             string  `json:"name"`
	File             string  `json:"file"`
	Line             int     `json:"line"`
	CriticalityScore float64 `json:"criticality_score"`
	DominatorScore   float64 `json:"dominator_score"`
	PageRankScore    float64 `json:"pagerank_score"`
	DominatedCount   int     `json:"dominated_count"`
	Quadrant         string  `json:"quadrant"`
	RiskLevel        string  `json:"risk_level"`
	Recommendation   string  `json:"recommendation"`
}

CriticalFunction represents one critical function with combined scores.

type CriticalPathNode

type CriticalPathNode struct {
	// ID is the full node identifier.
	ID string `json:"id"`

	// Name is the function name extracted from the ID.
	Name string `json:"name"`

	// Depth is the distance from the entry point.
	Depth int `json:"depth"`

	// IsMandatory is always true for critical path nodes.
	IsMandatory bool `json:"is_mandatory"`

	// Reason explains why this node is in the path.
	Reason string `json:"reason"`
}

CriticalPathNode represents a single node in the critical path.

type CriticalitySummary

type CriticalitySummary struct {
	TotalAnalyzed   int     `json:"total_analyzed"`
	HighRiskCount   int     `json:"high_risk_count"`
	MediumRiskCount int     `json:"medium_risk_count"`
	AvgCriticality  float64 `json:"avg_criticality"`
}

CriticalitySummary contains aggregate statistics.

type CrossEdgeInfo

type CrossEdgeInfo struct {
	FromCommunity int `json:"from_community"`
	ToCommunity   int `json:"to_community"`
	Count         int `json:"count"`
}

CrossEdgeInfo represents edges between communities.

type CycleInfo

type CycleInfo struct {
	// CycleNumber is the position in the result list (1-based).
	CycleNumber int `json:"cycle_number"`

	// Length is the number of nodes in this cycle.
	Length int `json:"length"`

	// Packages lists the packages involved in this cycle.
	Packages []string `json:"packages"`

	// Nodes is the list of nodes in the cycle.
	Nodes []CycleNode `json:"nodes"`
}

CycleInfo holds information about a single cycle.

type CycleNode

type CycleNode struct {
	// ID is the node ID.
	ID string `json:"id"`

	// Name is the symbol name.
	Name string `json:"name,omitempty"`

	// File is the source file path.
	File string `json:"file,omitempty"`

	// Line is the line number.
	Line int `json:"line,omitempty"`
}

CycleNode represents a node in a cycle.

type DeadCodeSymbol

type DeadCodeSymbol struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind (function, type, etc.).
	Kind string `json:"kind"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Package is the package name.
	Package string `json:"package"`

	// Exported indicates if the symbol is exported.
	Exported bool `json:"exported"`

	// Reason explains why the symbol is considered dead.
	Reason string `json:"reason"`
}

DeadCodeSymbol holds information about a potentially dead symbol.

type DispatchResult

type DispatchResult struct {
	// Results contains individual tool execution results.
	Results []ExecutionResult `json:"results"`

	// FormattedOutput is the results formatted for LLM consumption.
	FormattedOutput string `json:"formatted_output"`

	// RemainingText is the LLM output text with tool calls removed.
	RemainingText string `json:"remaining_text"`

	// TotalDuration is the total time for all tool executions.
	TotalDuration time.Duration `json:"total_duration"`

	// FailedCount is the number of tools that failed.
	FailedCount int `json:"failed_count"`

	// ApprovedCount is the number of tools that required and received approval.
	ApprovedCount int `json:"approved_count"`

	// DeclinedCount is the number of tools that were declined by the approver.
	DeclinedCount int `json:"declined_count"`
}

DispatchResult contains the outcome of a dispatch operation.

func MergeResults

func MergeResults(results ...*DispatchResult) *DispatchResult

MergeResults combines multiple DispatchResults into one.

Description:

Merges results from multiple dispatch operations. Useful when
executing tool calls in batches or from multiple sources.
RemainingText takes the first non-empty value found.

Inputs:

results - The results to merge. Nil results are skipped.

Outputs:

*DispatchResult - Combined results

Thread Safety: This function is safe for concurrent use.

type Dispatcher

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

Dispatcher orchestrates tool execution with validation, approval, and formatting.

Description:

The dispatcher is the high-level entry point for tool execution.
It coordinates between the parser (which extracts calls from LLM output),
the executor (which runs individual tools), and the formatter (which
prepares results for the LLM).

Thread Safety: Dispatcher is safe for concurrent use.

func NewDispatcher

func NewDispatcher(registry *Registry, executor *Executor, opts ...DispatcherOption) *Dispatcher

NewDispatcher creates a new tool dispatcher.

Description:

Creates a dispatcher that coordinates tool parsing, execution, and formatting.
The registry and executor are required; other components use defaults if nil.

Inputs:

registry - The tool registry. Must not be nil.
executor - The tool executor. Must not be nil.
opts - Configuration options

Outputs:

*Dispatcher - The configured dispatcher. Returns nil if registry or executor is nil.

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(ctx context.Context, llmOutput string) (*DispatchResult, error)

Dispatch parses and executes tool calls from LLM output.

Description:

Parses the LLM output for tool calls, executes them sequentially,
and returns formatted results. This is the main entry point for
processing LLM output that may contain tool calls.

Inputs:

ctx - Context for cancellation and timeout
llmOutput - The raw LLM output text

Outputs:

*DispatchResult - Execution results and formatted output
error - Non-nil if dispatch completely failed (partial failures in results)

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) DispatchWithRetry

func (d *Dispatcher) DispatchWithRetry(ctx context.Context, calls []ToolCall, maxRetries int) (*DispatchResult, error)

DispatchWithRetry executes tool calls with retry logic for transient failures.

Description:

Wraps Execute with retry logic for tools that fail with retryable errors.
Uses exponential backoff between retries.

Inputs:

ctx - Context for cancellation and timeout
calls - The tool calls to execute
maxRetries - Maximum retries per tool (0 = no retries)

Outputs:

*DispatchResult - Final execution results
error - Non-nil only for catastrophic failures

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) Execute

func (d *Dispatcher) Execute(ctx context.Context, calls []ToolCall) (*DispatchResult, error)

Execute runs a set of parsed tool calls sequentially.

Description:

Executes tool calls in order, collecting results. Execution continues
even if individual tools fail (partial success is allowed).

Inputs:

ctx - Context for cancellation and timeout
calls - The tool calls to execute

Outputs:

*DispatchResult - Execution results
error - Non-nil only for catastrophic failures

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) ExecuteParallel

func (d *Dispatcher) ExecuteParallel(ctx context.Context, calls []ToolCall, maxConcurrent int) (*DispatchResult, error)

ExecuteParallel runs tool calls concurrently with bounded parallelism.

Description:

Executes tool calls concurrently up to maxConcurrent at a time.
Results are returned in the same order as input calls.
This is useful when tools are independent and can run simultaneously.

Inputs:

ctx - Context for cancellation and timeout
calls - The tool calls to execute
maxConcurrent - Maximum concurrent executions (0 = NumCPU)

Outputs:

*DispatchResult - Execution results in input order
error - Non-nil only for catastrophic failures

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) GenerateToolsPrompt

func (d *Dispatcher) GenerateToolsPrompt(enabledCategories []string, disabledTools []string) string

GenerateToolsPrompt generates a system prompt section describing available tools.

Description:

Creates a formatted description of all available tools for inclusion
in the LLM system prompt.

Inputs:

enabledCategories - Categories to include (empty = all)
disabledTools - Specific tools to exclude

Outputs:

string - Formatted tool descriptions

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) GetAvailableToolNames

func (d *Dispatcher) GetAvailableToolNames(enabledCategories []string, disabledTools []string) []string

GetAvailableToolNames returns the names of tools that can be executed.

Description:

Returns tool names filtered by category and excluding disabled tools.
Results are sorted alphabetically.

Inputs:

enabledCategories - Categories to include (empty = all)
disabledTools - Specific tools to exclude

Outputs:

[]string - Sorted list of available tool names

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) GetFormatter

func (d *Dispatcher) GetFormatter() *Formatter

GetFormatter returns the dispatcher's formatter.

Outputs:

*Formatter - The formatter instance

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) GetParser

func (d *Dispatcher) GetParser() *Parser

GetParser returns the dispatcher's parser.

Outputs:

*Parser - The parser instance

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) GetRecovery

func (d *Dispatcher) GetRecovery() *ErrorRecovery

GetRecovery returns the dispatcher's error recovery helper.

Outputs:

*ErrorRecovery - The error recovery helper

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) GroupToolCallsByCategory

func (d *Dispatcher) GroupToolCallsByCategory(calls []ToolCall) map[ToolCategory][]ToolCall

GroupToolCallsByCategory groups tool calls by their tool's category.

Description:

Groups tool calls by the category of the tool they invoke.
Calls for unknown tools are silently skipped.

Inputs:

calls - Tool calls to group

Outputs:

map[ToolCategory][]ToolCall - Grouped tool calls

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) SetApprover

func (d *Dispatcher) SetApprover(fn ApprovalFunc)

SetApprover sets or replaces the approval function.

Thread Safety: This method is safe for concurrent use.

func (*Dispatcher) ToolExists

func (d *Dispatcher) ToolExists(name string) bool

ToolExists checks if a tool is registered.

Inputs:

name - The tool name to check

Outputs:

bool - True if the tool exists

Thread Safety: This method is safe for concurrent use.

type DispatcherOption

type DispatcherOption func(*Dispatcher)

DispatcherOption configures the Dispatcher.

func WithApprover

func WithApprover(fn ApprovalFunc) DispatcherOption

WithApprover sets the approval function for tools requiring user consent.

Description:

The approval function is called for tools with SideEffects=true.
Return true to allow execution, false to decline.

Inputs:

fn - The approval function. May be nil to disable approval checks.

func WithDispatchFormatter

func WithDispatchFormatter(f *Formatter) DispatcherOption

WithDispatchFormatter sets a custom formatter.

Description:

Overrides the default formatter used to format results for LLM consumption.

Inputs:

f - The formatter. Must not be nil.

func WithDispatchParser

func WithDispatchParser(p *Parser) DispatcherOption

WithDispatchParser sets a custom parser.

Description:

Overrides the default parser used to extract tool calls from LLM output.

Inputs:

p - The parser. Must not be nil.

func WithDispatchTimeout

func WithDispatchTimeout(timeout time.Duration) DispatcherOption

WithDispatchTimeout sets the default timeout for tool execution.

Description:

Sets the maximum duration for a single tool execution.
Default is 30 seconds.

Inputs:

timeout - The timeout duration. Zero or negative uses default.

type DominatorInfo

type DominatorInfo struct {
	// ID is the full node ID.
	ID string `json:"id"`

	// Name is the function name.
	Name string `json:"name"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number in the source file.
	Line int `json:"line"`

	// Depth is the depth in the dominator tree (0 = entry).
	Depth int `json:"depth"`
}

DominatorInfo holds information about a single dominator.

type EmptyParams

type EmptyParams struct {
	// Tool is the name of the tool these empty parameters belong to.
	Tool string
}

EmptyParams represents a tool invocation with no parameters.

Description:

Used by tools like list_packages, find_entry_points, and
find_extractable_regions that require no input parameters.

Thread Safety: Safe for concurrent use (immutable after creation).

func (EmptyParams) ToMap

func (p EmptyParams) ToMap() map[string]any

ToMap returns an empty parameter map.

func (EmptyParams) ToolName

func (p EmptyParams) ToolName() string

ToolName returns the tool name for empty parameters.

type EnhancedParser

type EnhancedParser struct {
	*Parser
	// contains filtered or unexported fields
}

EnhancedParser extends Parser with model-aware parsing.

Description:

Provides model-aware parsing that handles multiple tool call formats
and includes detailed parse results with fallback/partial information.

Thread Safety: Safe for concurrent use.

func NewEnhancedParser

func NewEnhancedParser(model agent.ModelType, formats ...ParseFormat) *EnhancedParser

NewEnhancedParser creates a model-aware parser.

Inputs:

model - The LLM model type for format-aware parsing.
formats - Formats to try (nil uses defaults).

Outputs:

*EnhancedParser - The configured parser.

func (*EnhancedParser) GetModel

func (p *EnhancedParser) GetModel() agent.ModelType

GetModel returns the configured model type.

func (*EnhancedParser) ParseWithResult

func (p *EnhancedParser) ParseWithResult(text string) ParseResult

ParseWithResult parses with full result metadata.

Description:

Parses tool calls from text and returns detailed result including
whether this was a fallback (no format matched) or partial parse.

Inputs:

text - The LLM output text to parse.

Outputs:

ParseResult - Full parse result with metadata.

Thread Safety: Safe for concurrent use.

func (*EnhancedParser) ShouldPreserveAnthropicFormat

func (p *EnhancedParser) ShouldPreserveAnthropicFormat() bool

ShouldPreserveAnthropicFormat returns true if Anthropic format should be preserved.

Description:

For Claude models, the Anthropic function_calls format is native and
should be preserved rather than stripped as leaked markup.

type ErrorRecovery

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

ErrorRecovery provides error analysis and fix suggestions for tool failures.

Description:

Analyzes tool execution errors and suggests fixes that can be
relayed to the LLM to help it recover from failures.

Thread Safety: ErrorRecovery is safe for concurrent use.

func NewErrorRecovery

func NewErrorRecovery() *ErrorRecovery

NewErrorRecovery creates a new error recovery helper.

Outputs:

*ErrorRecovery - The configured recovery helper

func (*ErrorRecovery) AddCustomSuggestion

func (r *ErrorRecovery) AddCustomSuggestion(pattern, suggestion string)

AddCustomSuggestion adds a custom error pattern and suggestion.

Description:

Registers a custom suggestion for errors matching a pattern.
The pattern is matched as a substring of the error message.

Inputs:

pattern - Substring to match in error messages
suggestion - Suggestion to return when pattern matches

Thread Safety: This method is safe for concurrent use.

func (*ErrorRecovery) Analyze

func (r *ErrorRecovery) Analyze(err error, call ToolCall) *RecoveryResult

Analyze performs full error analysis and returns structured results.

Description:

Provides detailed analysis including error category and retryability.

Inputs:

err - The error to analyze
call - The tool call that failed

Outputs:

*RecoveryResult - Analysis results

Thread Safety: This method is safe for concurrent use.

func (*ErrorRecovery) SuggestFix

func (r *ErrorRecovery) SuggestFix(err error, call ToolCall) string

SuggestFix analyzes an error and suggests a recovery action.

Description:

Examines the error and tool call context to suggest fixes.
Returns an empty string if no suggestion is available.

Inputs:

err - The error that occurred
call - The tool call that failed

Outputs:

string - A suggested fix, or empty string if none available

Thread Safety: This method is safe for concurrent use.

type ExecutionResult

type ExecutionResult struct {
	// Call is the original tool call.
	Call ToolCall `json:"call"`

	// Result is the execution result.
	Result *Result `json:"result"`

	// Approved indicates if the tool required and received approval.
	Approved bool `json:"approved,omitempty"`

	// Declined indicates if the user declined approval for the tool.
	Declined bool `json:"declined,omitempty"`
}

ExecutionResult represents the outcome of a single tool execution. This is used by the dispatcher for tracking execution details.

type Executor

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

Executor handles tool invocations with validation and observability.

Thread Safety:

Executor is safe for concurrent use. Multiple tool executions can
run simultaneously.

func NewExecutor

func NewExecutor(registry *Registry, opts *ExecutorOptions) *Executor

NewExecutor creates a new tool executor.

Inputs:

registry - The tool registry
opts - Executor options (uses defaults if nil)

Outputs:

*Executor - The configured executor

func NewExecutorWithOptions

func NewExecutorWithOptions(registry *Registry, execOpts *ExecutorOptions, opts ...ExecutorOption) *Executor

NewExecutorWithOptions creates an executor with functional options.

Inputs

  • registry: The tool registry.
  • execOpts: Executor configuration options (uses defaults if nil).
  • opts: Functional options for additional configuration.

Outputs

  • *Executor: The configured executor.

func (*Executor) ClearCache

func (e *Executor) ClearCache()

ClearCache clears the result cache.

Thread Safety: This method is safe for concurrent use.

func (*Executor) Execute

func (e *Executor) Execute(ctx context.Context, invocation *Invocation) (*Result, error)

Execute runs a tool with the given invocation.

Description:

Validates the invocation, checks requirements, executes the tool,
and optionally caches the result.

Inputs:

ctx - Context for cancellation and timeout
invocation - The tool invocation to execute

Outputs:

*Result - The execution result
error - Non-nil if execution failed

Errors:

ErrToolNotFound - Tool does not exist
ErrValidationFailed - Parameter validation failed
ErrRequirementNotMet - Tool requirement not satisfied
ErrTimeout - Execution timed out
ErrExecutionFailed - Tool returned an error

Thread Safety: This method is safe for concurrent use.

func (*Executor) GetAvailableTools

func (e *Executor) GetAvailableTools(enabledCategories []string, disabledTools []string) []ToolDefinition

GetAvailableTools returns tools available with current requirements.

Inputs:

enabledCategories - Categories to include (empty = all)
disabledTools - Specific tool names to exclude

Outputs:

[]ToolDefinition - Definitions for available tools

Thread Safety: This method is safe for concurrent use.

func (*Executor) IsRequirementSatisfied

func (e *Executor) IsRequirementSatisfied(requirement string) bool

IsRequirementSatisfied checks if a requirement is satisfied.

Inputs:

requirement - The requirement name

Outputs:

bool - True if the requirement is satisfied

Thread Safety: This method is safe for concurrent use.

func (*Executor) SatisfyRequirement

func (e *Executor) SatisfyRequirement(requirement string)

SatisfyRequirement marks a requirement as satisfied.

Inputs:

requirement - The requirement name (e.g., "graph_initialized")

Thread Safety: This method is safe for concurrent use.

func (*Executor) SetSessionID

func (e *Executor) SetSessionID(sessionID string)

SetSessionID sets the session ID for trace correlation.

Thread Safety: This method is safe for concurrent use.

func (*Executor) UnsatisfyRequirement

func (e *Executor) UnsatisfyRequirement(requirement string)

UnsatisfyRequirement marks a requirement as not satisfied.

Inputs:

requirement - The requirement name

Thread Safety: This method is safe for concurrent use.

type ExecutorOption

type ExecutorOption func(*Executor)

ExecutorOption configures an Executor.

func WithSessionID

func WithSessionID(sessionID string) ExecutorOption

WithSessionID sets the session ID for trace correlation.

func WithTransactionManager

func WithTransactionManager(tm *transaction.Manager) ExecutorOption

WithTransactionManager sets the transaction manager for the executor.

When set, side-effect tools are wrapped in a transaction that is automatically committed on success or rolled back on error.

type ExecutorOptions

type ExecutorOptions struct {
	// DefaultTimeout is the default execution timeout.
	DefaultTimeout time.Duration

	// MaxOutputTokens limits output size (estimated).
	MaxOutputTokens int

	// EnableCaching enables result caching.
	EnableCaching bool

	// CacheTTL is how long cached results are valid.
	CacheTTL time.Duration
}

ExecutorOptions configures the tool executor.

func DefaultExecutorOptions

func DefaultExecutorOptions() ExecutorOptions

DefaultExecutorOptions returns sensible defaults.

type ExplorePackageParams

type ExplorePackageParams struct {
	// Package is the package name or path to explore.
	Package string

	// IncludeDependencies shows packages this package imports.
	IncludeDependencies bool

	// IncludeDependents shows packages that import this package.
	IncludeDependents bool
}

ExplorePackageParams contains parameters for the explore_package tool.

Thread Safety: Safe for concurrent use (value type).

func (ExplorePackageParams) ToMap

func (p ExplorePackageParams) ToMap() map[string]any

ToMap converts ExplorePackageParams to the map consumed by explore_package.Execute().

func (ExplorePackageParams) ToolName

func (p ExplorePackageParams) ToolName() string

ToolName returns "explore_package".

type ExplorePackageResult

type ExplorePackageResult struct {
	Name         string         `json:"name"`
	Path         string         `json:"path"`
	Files        []FileOverview `json:"files"`
	PublicAPI    PackageAPI     `json:"public_api"`
	Dependencies []string       `json:"dependencies,omitempty"`
	Dependents   []string       `json:"dependents,omitempty"`
	Summary      string         `json:"summary"`
	Purpose      string         `json:"purpose"`
	TotalSymbols int            `json:"total_symbols"`
	IsMain       bool           `json:"is_main,omitempty"`
	IsTest       bool           `json:"is_test,omitempty"`
}

ExplorePackageResult is the output of the explore_package tool.

type ExtractableRegionInfo

type ExtractableRegionInfo struct {
	// Entry is the single entry node ID.
	Entry string `json:"entry"`

	// EntryName is the function name of the entry.
	EntryName string `json:"entry_name"`

	// Exit is the single exit node ID.
	Exit string `json:"exit"`

	// ExitName is the function name of the exit.
	ExitName string `json:"exit_name"`

	// Size is the number of nodes in the region.
	Size int `json:"size"`

	// Depth is the nesting depth (0 = top-level).
	Depth int `json:"depth"`

	// Nodes is the list of node IDs in the region (if small enough).
	Nodes []string `json:"nodes,omitempty"`

	// HasNestedRegions indicates if this region contains nested SESE regions.
	HasNestedRegions bool `json:"has_nested_regions,omitempty"`
}

ExtractableRegionInfo holds information about an extractable SESE region.

type ExtractableRegionsSummary

type ExtractableRegionsSummary struct {
	// TotalRegions is the total SESE regions detected (before filtering).
	TotalRegions int `json:"total_regions"`

	// ExtractableCount is the number meeting size criteria.
	ExtractableCount int `json:"extractable_count"`

	// Returned is the number returned (after top limit).
	Returned int `json:"returned"`

	// MaxDepth is the maximum nesting depth found.
	MaxDepth int `json:"max_depth"`

	// AvgSize is the average region size.
	AvgSize float64 `json:"avg_size"`

	// MinSizeUsed is the actual min_size used (after clamping).
	MinSizeUsed int `json:"min_size_used"`

	// MaxSizeUsed is the actual max_size used (after clamping).
	MaxSizeUsed int `json:"max_size_used"`
}

ExtractableRegionsSummary contains aggregate statistics.

type FileOverview

type FileOverview struct {
	Name      string   `json:"name"`
	Path      string   `json:"path"`
	LineCount int      `json:"line_count,omitempty"`
	Symbols   []string `json:"symbols"`
	IsTest    bool     `json:"is_test,omitempty"`
}

FileOverview contains summary information about a file.

type FileSymbolInfo

type FileSymbolInfo struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind.
	Kind string `json:"kind"`

	// Line is the starting line number (1-indexed).
	Line int `json:"line"`

	// EndLine is the ending line number.
	EndLine int `json:"end_line"`

	// Exported indicates if the symbol is publicly visible.
	Exported bool `json:"exported"`

	// Signature is the type signature (if available).
	Signature string `json:"signature,omitempty"`

	// Receiver is the receiver type (for methods).
	Receiver string `json:"receiver,omitempty"`
}

FileSymbolInfo contains information about a symbol in a file.

type FindArticulationPointsOutput

type FindArticulationPointsOutput struct {
	// ArticulationPoints is the list of detected articulation points.
	ArticulationPoints []ArticulationPointInfo `json:"articulation_points"`

	// Bridges is the list of critical edges.
	Bridges []BridgeInfo `json:"bridges,omitempty"`

	// TotalComponents is the number of connected components.
	TotalComponents int `json:"total_components"`

	// FragilityScore is the ratio of articulation points to total nodes.
	FragilityScore float64 `json:"fragility_score"`

	// FragilityLevel is a human-readable fragility assessment.
	FragilityLevel string `json:"fragility_level"`

	// NodeCount is the total number of nodes analyzed.
	NodeCount int `json:"node_count"`

	// EdgeCount is the total number of edges analyzed.
	EdgeCount int `json:"edge_count"`
}

FindArticulationPointsOutput contains the structured result.

type FindArticulationPointsParams

type FindArticulationPointsParams struct {
	// Top is the number of articulation points to return.
	// Default: 20, Max: 100
	Top int

	// IncludeBridges indicates whether to include critical edges (bridges).
	// Default: true
	IncludeBridges bool

	// Package filters articulation points to those in a matching package/directory.
	// CRS-13: Uses matchesPackageScope() for boundary-aware cross-language matching.
	// Empty string means no filter (all articulation points returned).
	Package string
}

FindArticulationPointsParams contains the validated input parameters.

func (FindArticulationPointsParams) ToMap

func (p FindArticulationPointsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindArticulationPointsParams) ToolName

func (p FindArticulationPointsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindCalleesOutput

type FindCalleesOutput struct {
	// FunctionName is the function that was searched for.
	FunctionName string `json:"function_name"`

	// ResolvedCount is the number of in-codebase callees.
	ResolvedCount int `json:"resolved_count"`

	// ExternalCount is the number of external/stdlib callees.
	ExternalCount int `json:"external_count"`

	// TotalCount is the total number of callees.
	TotalCount int `json:"total_count"`

	// ResolvedCallees are in-codebase callees with file locations.
	ResolvedCallees []CalleeInfo `json:"resolved_callees"`

	// ExternalCallees are external/stdlib callees (names only).
	ExternalCallees []string `json:"external_callees"`

	// ResolvedKind is the ast.SymbolKind of the resolved symbol (e.g., "type", "function").
	// IT-06b Issue 3: Used by formatText to provide kind-specific messages
	// (e.g., "HandlerFunc is a type alias, not a function with a body").
	ResolvedKind string `json:"resolved_kind,omitempty"`
}

FindCalleesOutput contains the structured result.

type FindCalleesParams

type FindCalleesParams struct {
	// FunctionName is the name of the function to find callees for.
	FunctionName string

	// Limit is the maximum number of callees to return.
	// Default: 50, Max: 1000
	Limit int

	// PackageHint is an optional package/module context extracted from the query.
	// IT-06c Bug C: Used to disambiguate when multiple symbols share the same name.
	// For example, "Build" in Hugo matches 11 symbols; "hugolib" narrows to the right one.
	PackageHint string
}

FindCalleesParams contains the validated input parameters.

func (FindCalleesParams) ToMap

func (p FindCalleesParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindCalleesParams) ToolName

func (p FindCalleesParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindCallersOutput

type FindCallersOutput struct {
	// FunctionName is the function that was searched for.
	FunctionName string `json:"function_name"`

	// MatchCount is the number of matching symbol IDs.
	MatchCount int `json:"match_count"`

	// TotalCallers is the total number of callers found.
	TotalCallers int `json:"total_callers"`

	// Results contains the callers grouped by target symbol ID.
	Results []CallerResult `json:"results"`
}

FindCallersOutput contains the structured result.

type FindCallersParams

type FindCallersParams struct {
	// FunctionName is the name of the function to find callers for.
	FunctionName string

	// Limit is the maximum number of callers to return.
	// Default: 50, Max: 1000
	Limit int

	// PackageHint is an optional package/module context extracted from the query.
	// IT-06c Bug C: Used to disambiguate when multiple symbols share the same name.
	PackageHint string
}

FindCallersParams contains the validated input parameters.

func (FindCallersParams) ToMap

func (p FindCallersParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindCallersParams) ToolName

func (p FindCallersParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindCommonDependencyOutput

type FindCommonDependencyOutput struct {
	// LCD contains information about the lowest common dominator.
	LCD LCDInfo `json:"lcd"`

	// Targets is the list of target function names that were analyzed.
	Targets []string `json:"targets"`

	// TargetsResolved is the number of targets that were successfully resolved.
	TargetsResolved int `json:"targets_resolved"`

	// Entry is the entry point name used for dominator analysis.
	Entry string `json:"entry"`

	// EntryID is the full node ID of the entry point.
	EntryID string `json:"entry_id"`

	// PathsToTargets maps each target name to its dominator chain.
	// Each chain is a list of function names from the target up to the LCD.
	PathsToTargets map[string][]string `json:"paths_to_targets"`
}

FindCommonDependencyOutput contains the structured result.

type FindCommonDependencyParams

type FindCommonDependencyParams struct {
	// Targets is the list of function names to find common dependency for.
	// Must contain at least 2 function names.
	Targets []string

	// Entry is the optional entry point for dominator analysis.
	// If empty, auto-detects main/init functions.
	Entry string
}

FindCommonDependencyParams contains the validated input parameters.

func (FindCommonDependencyParams) ToMap

func (p FindCommonDependencyParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindCommonDependencyParams) ToolName

func (p FindCommonDependencyParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindCommunitiesOutput

type FindCommunitiesOutput struct {
	// Modularity is the modularity score (0-1, higher = better separation).
	Modularity float64 `json:"modularity"`

	// ModularityQuality is a human-readable quality label.
	ModularityQuality string `json:"modularity_quality"`

	// CommunityCount is the number of communities returned.
	CommunityCount int `json:"community_count"`

	// TotalCommunities is the total number of communities detected.
	TotalCommunities int `json:"total_communities"`

	// Algorithm is the algorithm used (Leiden).
	Algorithm string `json:"algorithm"`

	// Converged indicates whether the algorithm converged.
	Converged bool `json:"converged"`

	// Iterations is the number of iterations run.
	Iterations int `json:"iterations"`

	// NodeCount is the total number of nodes in the graph.
	NodeCount int `json:"node_count"`

	// EdgeCount is the total number of edges in the graph.
	EdgeCount int `json:"edge_count"`

	// Communities is the list of detected communities.
	Communities []CommunityInfo `json:"communities"`

	// CrossPackageCommunities lists IDs of communities spanning multiple packages.
	CrossPackageCommunities []int `json:"cross_package_communities"`

	// CrossCommunityEdges lists edges between communities.
	CrossCommunityEdges []CrossEdgeInfo `json:"cross_community_edges,omitempty"`
}

FindCommunitiesOutput contains the structured result.

type FindCommunitiesParams

type FindCommunitiesParams struct {
	// MinSize is the minimum community size to report.
	// Default: 3, Max: 100
	MinSize int

	// Resolution controls community granularity.
	// 0.1 = large communities, 1.0 = balanced, 5.0 = small communities.
	// Default: 1.0
	Resolution float64

	// Top is the number of communities to return.
	// Default: 20, Max: 50
	Top int

	// ShowCrossEdges indicates whether to show edges between communities.
	// Default: true
	ShowCrossEdges bool

	// PackageFilter limits results to communities with members in this
	// directory/package (case-insensitive substring match). Default: "" (all).
	PackageFilter string
}

FindCommunitiesParams contains the validated input parameters.

func (FindCommunitiesParams) ToMap

func (p FindCommunitiesParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindCommunitiesParams) ToolName

func (p FindCommunitiesParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindControlDependenciesOutput

type FindControlDependenciesOutput struct {
	// Target is the function that was analyzed.
	Target string `json:"target"`

	// TargetID is the resolved symbol ID.
	TargetID string `json:"target_id,omitempty"`

	// Dependencies lists the nodes that control this target's execution.
	Dependencies []ControllerInfo `json:"dependencies"`

	// DependencyCount is the total number of control dependencies.
	DependencyCount int `json:"dependency_count"`

	// Summary contains aggregate statistics.
	Summary ControlDependencySummary `json:"summary"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindControlDependenciesOutput contains the structured result.

type FindControlDependenciesParams

type FindControlDependenciesParams struct {
	// Target is the function name to analyze.
	Target string

	// Depth is the maximum dependency chain depth.
	// Default: 5, Max: 10
	Depth int
}

FindControlDependenciesParams contains the validated input parameters.

func (FindControlDependenciesParams) ToMap

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindControlDependenciesParams) ToolName

ToolName returns the tool name for TypedParams interface.

type FindCriticalPathOutput

type FindCriticalPathOutput struct {
	// Target is the target function.
	Target string `json:"target"`

	// Entry is the entry point used.
	Entry string `json:"entry"`

	// CriticalPath is the mandatory call sequence from entry to target.
	CriticalPath []CriticalPathNode `json:"critical_path"`

	// PathLength is the number of nodes in the critical path.
	PathLength int `json:"path_length"`

	// Explanation is a human-readable description.
	Explanation string `json:"explanation"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindCriticalPathOutput contains the structured result.

type FindCriticalPathParams

type FindCriticalPathParams struct {
	// Target is the target function to reach.
	// Required.
	Target string

	// Entry is the entry point for analysis.
	// Optional - will auto-detect if not provided.
	Entry string
}

FindCriticalPathParams contains the validated input parameters.

func (FindCriticalPathParams) ToMap

func (p FindCriticalPathParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindCriticalPathParams) ToolName

func (p FindCriticalPathParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindCyclesOutput

type FindCyclesOutput struct {
	// CycleCount is the number of cycles returned.
	CycleCount int `json:"cycle_count"`

	// Cycles is the list of detected cycles.
	Cycles []CycleInfo `json:"cycles"`
}

FindCyclesOutput contains the structured result.

type FindCyclesParams

type FindCyclesParams struct {
	// MinSize is the minimum cycle size to report.
	// Default: 2
	MinSize int

	// Limit is the maximum number of cycles to return.
	// Default: 20, Max: 100
	Limit int

	// PackageFilter filters cycles to those involving a matching package/directory.
	// Case-insensitive substring match against cycle.Packages entries.
	// Empty string means no filter (all cycles returned).
	PackageFilter string

	// SortBy controls the sort order for cycles.
	// "length_desc" (default): largest cycles first.
	// "length_asc": smallest cycles first.
	SortBy string
}

FindCyclesParams contains the validated input parameters.

func (FindCyclesParams) ToMap

func (p FindCyclesParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindCyclesParams) ToolName

func (p FindCyclesParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindDeadCodeOutput

type FindDeadCodeOutput struct {
	// DeadCodeCount is the number of dead code symbols found.
	DeadCodeCount int `json:"dead_code_count"`

	// DeadCode is the list of potentially unused symbols.
	DeadCode []DeadCodeSymbol `json:"dead_code"`
}

FindDeadCodeOutput contains the structured result.

type FindDeadCodeParams

type FindDeadCodeParams struct {
	// IncludeExported includes exported symbols (default: false).
	IncludeExported bool

	// Package filters results to a specific package path.
	Package string

	// Limit is the maximum number of results to return.
	// Default: 50, Max: 500
	Limit int

	// ExcludeTests filters out symbols from test files (default: true).
	ExcludeTests bool
}

FindDeadCodeParams contains the validated input parameters.

func (FindDeadCodeParams) ToMap

func (p FindDeadCodeParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindDeadCodeParams) ToolName

func (p FindDeadCodeParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindDominatorsOutput

type FindDominatorsOutput struct {
	// Target is the resolved target node ID.
	Target string `json:"target"`

	// TargetName is the function name of the target.
	TargetName string `json:"target_name"`

	// Entry is the entry point used for analysis.
	Entry string `json:"entry"`

	// EntryAutoDetected indicates if the entry was auto-detected.
	EntryAutoDetected bool `json:"entry_auto_detected"`

	// Dominators is the list of functions that dominate the target.
	// Ordered from entry to immediate dominator (shallow to deep).
	Dominators []DominatorInfo `json:"dominators"`

	// Depth is the depth of the target in the dominator tree.
	Depth int `json:"depth"`

	// ImmediateDominator is the immediate dominator of the target.
	ImmediateDominator string `json:"immediate_dominator"`

	// Subtree contains nodes dominated by the target (when show_tree=true).
	Subtree []string `json:"subtree,omitempty"`

	// Explanation is a human-readable summary.
	Explanation string `json:"explanation"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindDominatorsOutput contains the structured result.

type FindDominatorsParams

type FindDominatorsParams struct {
	// Target is the target function name or ID to find dominators for.
	// Required.
	Target string

	// Entry is the entry point for dominator analysis.
	// If empty, auto-detects main/init.
	Entry string

	// ShowTree indicates whether to show full dominator subtree of target.
	// Default: false
	ShowTree bool
}

FindDominatorsParams contains the validated input parameters.

func (FindDominatorsParams) ToMap

func (p FindDominatorsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindDominatorsParams) ToolName

func (p FindDominatorsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindExtractableRegionsOutput

type FindExtractableRegionsOutput struct {
	// Regions is the list of extractable SESE regions.
	Regions []ExtractableRegionInfo `json:"regions"`

	// RegionCount is the total number of regions found.
	RegionCount int `json:"region_count"`

	// Summary contains aggregate statistics.
	Summary ExtractableRegionsSummary `json:"summary"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindExtractableRegionsOutput contains the structured result.

type FindExtractableRegionsParams

type FindExtractableRegionsParams struct {
	// MinSize is the minimum region size to report.
	// Default: 3
	MinSize int

	// MaxSize is the maximum region size.
	// Default: 50
	MaxSize int

	// Top is the number of regions to return.
	// Default: 10, Max: 100
	Top int
}

FindExtractableRegionsParams contains the validated input parameters.

func (FindExtractableRegionsParams) ToMap

func (p FindExtractableRegionsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindExtractableRegionsParams) ToolName

func (p FindExtractableRegionsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindHotspotsOutput

type FindHotspotsOutput struct {
	// HotspotCount is the number of hotspots returned.
	HotspotCount int `json:"hotspot_count"`

	// Hotspots is the list of hotspot symbols.
	Hotspots []HotspotInfo `json:"hotspots"`
}

FindHotspotsOutput contains the structured result.

type FindHotspotsParams

type FindHotspotsParams struct {
	// Top is the number of hotspots to return.
	// Default: 10, Max: 100
	Top int

	// Kind filters results by symbol kind.
	// Values: "function", "method", "type", "class", "struct", "interface", "enum", "variable", "constant", "all"
	// Default: "all"
	Kind string

	// Package filters results to a specific package or module path.
	// When set, only hotspots in the matching package (or file path containing
	// the package string) are returned.
	Package string

	// ExcludeTests filters out symbols from test files.
	// When true (default), symbols in files matching test patterns
	// (*_test.go, test_*.py, *.test.ts, *.spec.js, etc.) are excluded.
	ExcludeTests bool

	// SortBy controls the ranking dimension.
	// Values: "score" (default, inDegree*2+outDegree), "in" (InDegree desc), "out" (OutDegree desc)
	SortBy string
}

FindHotspotsParams contains the validated input parameters.

func (FindHotspotsParams) ToMap

func (p FindHotspotsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindHotspotsParams) ToolName

func (p FindHotspotsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindImplementationsOutput

type FindImplementationsOutput struct {
	// InterfaceName is the interface that was searched for.
	InterfaceName string `json:"interface_name"`

	// MatchCount is the number of matching interface IDs.
	MatchCount int `json:"match_count"`

	// TotalImplementations is the total number of implementations found.
	TotalImplementations int `json:"total_implementations"`

	// Results contains the implementations grouped by interface ID.
	Results []ImplementationResult `json:"results"`
}

FindImplementationsOutput contains the structured result.

type FindImplementationsParams

type FindImplementationsParams struct {
	// InterfaceName is the name of the interface to find implementations for.
	InterfaceName string

	// Limit is the maximum number of implementations to return.
	// Default: 50, Max: 1000
	Limit int

	// PackageHint is an optional package/module context extracted from the query.
	// IT-06c: Used to disambiguate when multiple types share the same name.
	PackageHint string
}

FindImplementationsParams contains the validated input parameters.

func (FindImplementationsParams) ToMap

func (p FindImplementationsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindImplementationsParams) ToolName

func (p FindImplementationsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindImportantOutput

type FindImportantOutput struct {
	// ResultCount is the number of results returned.
	ResultCount int `json:"result_count"`

	// Results is the list of important symbols.
	Results []ImportantSymbol `json:"results"`

	// Algorithm is the algorithm used (PageRank).
	Algorithm string `json:"algorithm"`
}

FindImportantOutput contains the structured result.

type FindImportantParams

type FindImportantParams struct {
	// Top is the number of important symbols to return.
	// Default: 10, Max: 100
	Top int

	// Kind filters results by symbol kind.
	// Values: "function", "type", "all"
	// Default: "all"
	Kind string

	// Package filters results to a specific package or module scope.
	// Uses matchesPackageScope() with 3 strategies: Package field match,
	// FilePath segment match, and file stem match.
	// IT-07: Added to match find_hotspots package filter capability.
	// Default: "" (no filter)
	Package string

	// ExcludeTests filters out symbols from test and documentation files.
	// Default: true
	ExcludeTests bool

	// Reverse returns lowest-ranked symbols first (peripheral functions).
	// IT-R2c Fix E: Supports "lowest PageRank" / "peripheral" queries.
	// Default: false
	Reverse bool
}

FindImportantParams contains the validated input parameters.

func (FindImportantParams) ToMap

func (p FindImportantParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindImportantParams) ToolName

func (p FindImportantParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindLoopsOutput

type FindLoopsOutput struct {
	// Loops is the list of detected natural loops.
	Loops []LoopInfo `json:"loops"`

	// Summary contains aggregate statistics.
	Summary LoopsSummary `json:"summary"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindLoopsOutput contains the structured result.

type FindLoopsParams

type FindLoopsParams struct {
	// Top is the number of loops to return.
	// Default: 20, Max: 100
	Top int

	// MinSize is the minimum loop body size.
	// Default: 1
	MinSize int

	// ShowNesting indicates whether to show loop nesting hierarchy.
	// Default: true
	ShowNesting bool
}

FindLoopsParams contains the validated input parameters.

func (FindLoopsParams) ToMap

func (p FindLoopsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindLoopsParams) ToolName

func (p FindLoopsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindMergePointsOutput

type FindMergePointsOutput struct {
	// MergePoints is the list of detected merge points.
	MergePoints []MergePointInfo `json:"merge_points"`

	// Summary contains aggregate statistics.
	Summary MergePointsSummary `json:"summary"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindMergePointsOutput contains the structured result.

type FindMergePointsParams

type FindMergePointsParams struct {
	// Top is the number of merge points to return.
	// Default: 20, Max: 100
	Top int

	// MinSources is the minimum incoming paths to qualify as merge point.
	// Default: 2
	MinSources int
}

FindMergePointsParams contains the validated input parameters.

func (FindMergePointsParams) ToMap

func (p FindMergePointsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindMergePointsParams) ToolName

func (p FindMergePointsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindModuleAPIOutput

type FindModuleAPIOutput struct {
	// Modules is the list of analyzed modules.
	Modules []ModuleAPI `json:"modules"`

	// Summary contains aggregate statistics.
	Summary ModuleAPISummary `json:"summary"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindModuleAPIOutput contains the structured result.

type FindModuleAPIParams

type FindModuleAPIParams struct {
	// CommunityID is the specific community to analyze.
	// -1 means analyze all communities (default).
	CommunityID int

	// Top is the number of communities to analyze.
	// Default: 10, Max: 50.
	Top int

	// MinCommunitySize is the minimum community size to analyze.
	// Default: 3.
	MinCommunitySize int
}

FindModuleAPIParams contains the validated input parameters.

func (FindModuleAPIParams) ToMap

func (p FindModuleAPIParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindModuleAPIParams) ToolName

func (p FindModuleAPIParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindPathOutput

type FindPathOutput struct {
	// From is the starting symbol name.
	From string `json:"from"`

	// To is the target symbol name.
	To string `json:"to"`

	// Length is the path length in hops (-1 if no path found).
	Length int `json:"length"`

	// Found indicates if a path was found.
	Found bool `json:"found"`

	// Path is the list of nodes in the path.
	Path []PathNode `json:"path,omitempty"`

	// Message is an optional status message.
	Message string `json:"message,omitempty"`
}

FindPathOutput contains the structured result.

type FindPathParams

type FindPathParams struct {
	// From is the starting symbol name.
	From string

	// To is the target symbol name.
	To string
}

FindPathParams contains the validated input parameters.

func (FindPathParams) ToMap

func (p FindPathParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindPathParams) ToolName

func (p FindPathParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindReferencesOutput

type FindReferencesOutput struct {
	// SymbolName is the symbol that was searched for.
	SymbolName string `json:"symbol_name"`

	// ResolvedName is the actual symbol name after resolution (may differ from
	// SymbolName if fuzzy matching was used).
	ResolvedName string `json:"resolved_name,omitempty"`

	// DefinedAt is where the resolved symbol is defined (file:line).
	DefinedAt string `json:"defined_at,omitempty"`

	// SymbolKind is the kind of the resolved symbol (function, struct, interface, etc.).
	SymbolKind string `json:"symbol_kind,omitempty"`

	// ReferenceCount is the number of references found.
	ReferenceCount int `json:"reference_count"`

	// References is the list of reference locations.
	References []ReferenceInfo `json:"references"`
}

FindReferencesOutput contains the structured result.

type FindReferencesParams

type FindReferencesParams struct {
	// SymbolName is the name of the symbol to find references for.
	SymbolName string

	// Limit is the maximum number of references to return.
	// Default: 100
	Limit int

	// PackageHint is an optional package/module context extracted from the query.
	// IT-06c: Used to disambiguate when multiple symbols share the same name
	// during ResolveFunctionWithFuzzy exact-match phase.
	PackageHint string
}

FindReferencesParams contains the validated input parameters.

func (FindReferencesParams) ToMap

func (p FindReferencesParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindReferencesParams) ToolName

func (p FindReferencesParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindSimilarSymbolsOutput

type FindSimilarSymbolsOutput struct {
	// SourceSymbol is the symbol that was used as the search anchor.
	SourceSymbol string `json:"source_symbol"`

	// SourceFile is the file containing the source symbol.
	SourceFile string `json:"source_file"`

	// ResultCount is the number of similar symbols found.
	ResultCount int `json:"result_count"`

	// Results contains the ranked similar symbols.
	Results []SemanticSearchResult `json:"results"`
}

FindSimilarSymbolsOutput contains the structured result.

type FindSimilarSymbolsParams

type FindSimilarSymbolsParams struct {
	// SymbolName is the name of the symbol to find similar ones for.
	SymbolName string

	// Limit is the maximum number of similar symbols to return.
	// Default: 10, Max: 50
	Limit int
}

FindSimilarSymbolsParams contains the validated input parameters.

func (FindSimilarSymbolsParams) ToMap

func (p FindSimilarSymbolsParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindSimilarSymbolsParams) ToolName

func (p FindSimilarSymbolsParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindSymbolOutput

type FindSymbolOutput struct {
	// SearchName is the name that was searched for.
	SearchName string `json:"search_name"`

	// MatchCount is the number of matching symbols.
	MatchCount int `json:"match_count"`

	// Symbols is the list of matching symbols.
	Symbols []SymbolInfo `json:"symbols"`
}

FindSymbolOutput contains the structured result.

type FindSymbolParams

type FindSymbolParams struct {
	// Name is the symbol name to search for.
	Name string

	// Kind filters by symbol kind: function, type, interface, variable, constant, method, or all.
	Kind string

	// Package filters by package path (optional).
	Package string
}

FindSymbolParams contains the validated input parameters.

func (FindSymbolParams) ToMap

func (p FindSymbolParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindSymbolParams) ToolName

func (p FindSymbolParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type FindWeightedCriticalityParams

type FindWeightedCriticalityParams struct {
	// Top is the number of critical functions to return.
	// Default: 20, Range: [1, 100].
	Top int

	// Entry is the entry point for dominator analysis.
	// Empty string triggers auto-detection.
	Entry string

	// ShowQuadrant enables quadrant classification in output.
	ShowQuadrant bool

	// Package filters critical functions to those in a matching package/directory.
	// CRS-13: Uses matchesPackageScope() for boundary-aware cross-language matching.
	// Empty string means no filter (all critical functions returned).
	Package string
}

FindWeightedCriticalityParams contains the validated input parameters.

func (FindWeightedCriticalityParams) ToMap

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (FindWeightedCriticalityParams) ToolName

ToolName returns the tool name for TypedParams interface.

type Formatter

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

Formatter formats tool execution results for LLM consumption.

Description:

Converts ExecutionResults into a format suitable for including
in LLM context. Handles truncation of large outputs.

Thread Safety: Formatter is safe for concurrent use.

func NewFormatter

func NewFormatter(opts ...FormatterOption) *Formatter

NewFormatter creates a new result formatter.

Inputs:

opts - Configuration options

Outputs:

*Formatter - The configured formatter

func (*Formatter) Format

func (f *Formatter) Format(results []ExecutionResult) string

Format formats multiple execution results for LLM consumption.

Description:

Formats all results into XML blocks suitable for including in
the LLM's context window. Each result is formatted individually
and joined with newlines.

Inputs:

results - The execution results to format

Outputs:

string - Formatted results as XML

Thread Safety: This method is safe for concurrent use.

func (*Formatter) FormatCompact

func (f *Formatter) FormatCompact(results []ExecutionResult) string

FormatCompact formats results in a more compact format.

Description:

Produces a more compact representation when context space is limited.
Shows only tool name, success status, and first line of output.

Inputs:

results - The execution results to format

Outputs:

string - Compact formatted results

Thread Safety: This method is safe for concurrent use.

func (*Formatter) FormatError

func (f *Formatter) FormatError(toolName string, err error) string

FormatError formats an error for LLM consumption.

Description:

Formats an error that occurred during tool execution into
a consistent XML format.

Inputs:

toolName - The name of the tool that failed
err - The error that occurred

Outputs:

string - Formatted error as XML

Thread Safety: This method is safe for concurrent use.

func (*Formatter) FormatSingle

func (f *Formatter) FormatSingle(result ExecutionResult) string

FormatSingle formats a single execution result for LLM consumption.

Description:

Formats a single result into an XML block. The format is:
<tool_result>
<name>tool_name</name>
<success>true/false</success>
<output>...</output>
</tool_result>

Inputs:

result - The execution result to format

Outputs:

string - Formatted result as XML

Thread Safety: This method is safe for concurrent use.

func (*Formatter) FormatToolList

func (f *Formatter) FormatToolList(definitions []ToolDefinition) string

FormatToolList formats a list of available tools for the LLM system prompt.

Description:

Generates a human-readable description of available tools
for inclusion in the system prompt.

Inputs:

definitions - The tool definitions to format

Outputs:

string - Formatted tool list

Thread Safety: This method is safe for concurrent use.

func (*Formatter) Truncate

func (f *Formatter) Truncate(output string) string

Truncate truncates output to the maximum length.

Description:

If the output exceeds maxOutputLen, truncates it and appends
the truncation message.

Inputs:

output - The output to potentially truncate

Outputs:

string - The (possibly truncated) output

Thread Safety: This method is safe for concurrent use.

type FormatterOption

type FormatterOption func(*Formatter)

FormatterOption configures the Formatter.

func WithMaxOutputLen

func WithMaxOutputLen(n int) FormatterOption

WithMaxOutputLen sets the maximum output length before truncation.

func WithTruncateMessage

func WithTruncateMessage(msg string) FormatterOption

WithTruncateMessage sets the truncation indicator message.

type FunctionCallResponse

type FunctionCallResponse struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}

FunctionCallResponse represents an OpenAI-style function call from API response.

type GetCallChainOutput

type GetCallChainOutput struct {
	// FunctionName is the function that was traced.
	FunctionName string `json:"function_name"`

	// Direction is the traversal direction.
	Direction string `json:"direction"`

	// Depth is the actual depth reached.
	Depth int `json:"depth"`

	// Truncated indicates if traversal was cut short.
	Truncated bool `json:"truncated"`

	// NodeCount is the number of nodes visited.
	NodeCount int `json:"node_count"`

	// EdgeCount is the number of edges traversed.
	EdgeCount int `json:"edge_count"`

	// Nodes is the list of nodes in the call chain.
	Nodes []CallChainNode `json:"nodes"`

	// Message contains optional status message.
	Message string `json:"message,omitempty"`

	// DestinationFound indicates whether the destination (from "from X to Y" queries)
	// was found in the traversal result. Only set when DestinationName was provided.
	DestinationFound bool `json:"destination_found,omitempty"`

	// PathToDestination contains only the nodes on the path from source to destination.
	// Only populated when DestinationName was provided and found in the traversal.
	PathToDestination []CallChainNode `json:"path_to_destination,omitempty"`

	// ExternalDependencies lists external library boundaries encountered during traversal.
	// IT-05a: Populated when the call chain reaches nodes outside the indexed project.
	ExternalDependencies []string `json:"external_dependencies,omitempty"`
}

GetCallChainOutput contains the structured result.

type GetCallChainParams

type GetCallChainParams struct {
	// FunctionName is the name of the function to trace.
	FunctionName string

	// Direction is either "downstream" (callees) or "upstream" (callers).
	Direction string

	// MaxDepth is the maximum traversal depth (1-10).
	MaxDepth int

	// DestinationName is an optional endpoint for "from X to Y" queries.
	// IT-05 R5: When set, provides the resolved destination symbol ID for
	// dual-endpoint resolution. Used to enhance output messaging.
	DestinationName string

	// PackageHint is an optional package/module context extracted from the query.
	// IT-06c: Used to disambiguate when multiple symbols share the same name.
	PackageHint string
}

GetCallChainParams contains the validated input parameters.

func (GetCallChainParams) ToMap

func (p GetCallChainParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (GetCallChainParams) ToolName

func (p GetCallChainParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type GetSignatureOutput

type GetSignatureOutput struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// Matches contains signature info for each matching symbol.
	Matches []SignatureMatch `json:"matches"`

	// MatchCount is the number of matching symbols.
	MatchCount int `json:"match_count"`
}

GetSignatureOutput contains the structured result.

type GetSignatureParams

type GetSignatureParams struct {
	// Name is the name of the symbol to get the signature for.
	Name string
}

GetSignatureParams contains the validated input parameters.

func (GetSignatureParams) ToMap

func (p GetSignatureParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (GetSignatureParams) ToolName

func (p GetSignatureParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type GraphOverviewParams

type GraphOverviewParams struct {
	// Depth controls traversal depth (1-3).
	Depth int

	// IncludeDependencies includes inter-package dependency graph.
	IncludeDependencies bool

	// IncludeMetrics includes symbol counts and file metrics.
	IncludeMetrics bool
}

GraphOverviewParams contains parameters for the graph_overview tool.

Thread Safety: Safe for concurrent use (value type).

func (GraphOverviewParams) ToMap

func (p GraphOverviewParams) ToMap() map[string]any

ToMap converts GraphOverviewParams to the map consumed by graph_overview.Execute().

func (GraphOverviewParams) ToolName

func (p GraphOverviewParams) ToolName() string

ToolName returns "graph_overview".

type GraphOverviewResult

type GraphOverviewResult struct {
	Project         string              `json:"project"`
	Packages        []PackageOverview   `json:"packages"`
	DependencyGraph []PackageDependency `json:"dependency_graph,omitempty"`
	TotalPackages   int                 `json:"total_packages"`
	TotalFiles      int                 `json:"total_files"`
	TotalSymbols    int                 `json:"total_symbols"`
	Languages       []string            `json:"languages"`
}

GraphOverviewResult is the output of the graph_overview tool.

type GrepToolParams

type GrepToolParams struct {
	// Pattern is the search pattern.
	Pattern string

	// OutputMode controls output format ("content", "files_with_matches", "count").
	OutputMode string
}

GrepToolParams contains parameters for the Grep tool when invoked via the forced-tool path.

Description:

The Grep tool is an external (non-graph) tool with its own parameter
contract. This struct provides type safety for the forced-tool extraction
path in extractToolParameters.

Thread Safety: Safe for concurrent use (value type).

func (GrepToolParams) ToMap

func (p GrepToolParams) ToMap() map[string]any

ToMap converts GrepToolParams to the map consumed by Grep.Execute().

func (GrepToolParams) ToolName

func (p GrepToolParams) ToolName() string

ToolName returns "Grep".

type HotspotInfo

type HotspotInfo struct {
	// Rank is the position in the ranking (1-based).
	Rank int `json:"rank"`

	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind (function, type, etc.).
	Kind string `json:"kind"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Package is the package name.
	Package string `json:"package"`

	// Score is the connectivity score.
	Score int `json:"score"`

	// InDegree is the number of incoming edges.
	InDegree int `json:"in_degree"`

	// OutDegree is the number of outgoing edges.
	OutDegree int `json:"out_degree"`
}

HotspotInfo holds information about a hotspot symbol.

type ImplementationInfo

type ImplementationInfo struct {
	// Name is the implementing type name.
	Name string `json:"name"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Package is the package name.
	Package string `json:"package"`

	// Kind is the symbol kind (struct, type, etc.).
	Kind string `json:"kind"`
}

ImplementationInfo holds information about an implementation.

type ImplementationResult

type ImplementationResult struct {
	// InterfaceID is the interface symbol ID.
	InterfaceID string `json:"interface_id"`

	// ImplCount is the number of implementations.
	ImplCount int `json:"impl_count"`

	// Implementations is the list of implementing types.
	Implementations []ImplementationInfo `json:"implementations"`
}

ImplementationResult represents implementations for a specific interface.

type ImportantSymbol

type ImportantSymbol struct {
	// Rank is the position in the ranking (1-based).
	Rank int `json:"rank"`

	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind (function, type, etc.).
	Kind string `json:"kind"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Package is the package name.
	Package string `json:"package"`

	// PageRank is the PageRank score.
	PageRank float64 `json:"pagerank"`

	// DegreeScore is the degree-based score for comparison.
	DegreeScore int `json:"degree_score"`
}

ImportantSymbol holds information about an important symbol.

type Invocation

type Invocation struct {
	// ID is a unique identifier for this invocation.
	ID string `json:"id"`

	// ToolName is the tool to invoke.
	ToolName string `json:"tool_name"`

	// Parameters are the input parameters.
	Parameters map[string]any `json:"parameters"`

	// Reason explains why the agent chose this tool.
	Reason string `json:"reason,omitempty"`

	// StepNumber is the agent step when this was invoked.
	StepNumber int `json:"step_number"`

	// StartedAt is when execution started (Unix milliseconds UTC).
	StartedAt int64 `json:"started_at,omitempty"`

	// CompletedAt is when execution completed (Unix milliseconds UTC).
	CompletedAt int64 `json:"completed_at,omitempty"`

	// Result contains the execution result (after completion).
	Result *Result `json:"result,omitempty"`
}

Invocation represents a pending or completed tool call.

type IrreducibleRegionInfo

type IrreducibleRegionInfo struct {
	// ID is the region identifier.
	ID int `json:"id"`

	// EntryNodes are the multiple entry points.
	EntryNodes []string `json:"entry_nodes"`

	// Size is the number of nodes in the region.
	Size int `json:"size"`

	// CrossEdgeCount is the number of cross edges creating this region.
	CrossEdgeCount int `json:"cross_edge_count"`

	// Reason explains why this region is irreducible.
	Reason string `json:"reason,omitempty"`
}

IrreducibleRegionInfo holds information about an irreducible region.

type KindFilter

type KindFilter int

KindFilter controls which symbol kinds are accepted during resolution.

Description:

Used as an option to ResolveFunctionWithFuzzy to configure which symbol
kinds are accepted on both the exact match and fuzzy search paths.
Default is KindFilterCallable, which preserves the original behavior of
filtering to Function, Method, and Property symbols.

Thread Safety: This type is safe for concurrent use (immutable after creation).

const (
	// KindFilterCallable accepts Function, Method, and Property symbols.
	// This is the default, preserving the original behavior of ResolveFunctionWithFuzzy.
	KindFilterCallable KindFilter = iota

	// KindFilterType accepts Interface, Class, Struct, and Type symbols.
	// Used by find_implementations and similar type-focused tools.
	KindFilterType

	// KindFilterAny accepts all symbol kinds without filtering.
	// Used by find_references and tools that operate on any symbol.
	KindFilterAny
)

func (KindFilter) String

func (kf KindFilter) String() string

String returns the string representation of the KindFilter.

Outputs:

  • string: Human-readable filter name for logging ("callable", "type", "any").

Thread Safety: This method is safe for concurrent use.

type LCDInfo

type LCDInfo struct {
	// ID is the full node ID of the LCD.
	ID string `json:"id"`

	// Name is the function name of the LCD.
	Name string `json:"name"`

	// Depth is the depth of the LCD in the dominator tree.
	Depth int `json:"depth,omitempty"`
}

LCDInfo contains information about the lowest common dominator.

type ListPackagesResult

type ListPackagesResult struct {
	Packages   []PackageInfo `json:"packages"`
	TotalCount int           `json:"total_count"`
}

ListPackagesResult is the output of the list_packages tool.

type ListSymbolsInFileOutput

type ListSymbolsInFileOutput struct {
	// Path is the file path.
	Path string `json:"path"`

	// SymbolCount is the number of symbols found.
	SymbolCount int `json:"symbol_count"`

	// Symbols contains the symbols in the file.
	Symbols []FileSymbolInfo `json:"symbols"`
}

ListSymbolsInFileOutput contains the structured result.

type ListSymbolsInFileParams

type ListSymbolsInFileParams struct {
	// Path is the file path relative to the project root.
	Path string
}

ListSymbolsInFileParams contains the validated input parameters.

func (ListSymbolsInFileParams) ToMap

func (p ListSymbolsInFileParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (ListSymbolsInFileParams) ToolName

func (p ListSymbolsInFileParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type LoopInfo

type LoopInfo struct {
	// Header is the full node ID of the loop header.
	Header string `json:"header"`

	// HeaderName is the function name of the loop header.
	HeaderName string `json:"header_name"`

	// BodySize is the number of nodes in the loop body.
	BodySize int `json:"body_size"`

	// RecursionType describes the type of recursion (direct, mutual, complex).
	RecursionType string `json:"recursion_type"`

	// Body is the list of node IDs in the loop body.
	Body []string `json:"body"`

	// BackEdges are the edges that form this loop.
	BackEdges []BackEdgeInfo `json:"back_edges,omitempty"`

	// Depth is the nesting depth of this loop.
	Depth int `json:"depth,omitempty"`

	// ParentHeader is the header of the enclosing loop (if any).
	ParentHeader string `json:"parent_header,omitempty"`

	// NestedLoops lists headers of loops nested within this one.
	NestedLoops []string `json:"nested_loops,omitempty"`
}

LoopInfo holds information about a single natural loop.

type LoopsSummary

type LoopsSummary struct {
	// TotalLoops is the total number of loops detected.
	TotalLoops int `json:"total_loops"`

	// Returned is the number of loops returned in this result.
	Returned int `json:"returned"`

	// DirectRecursion is the count of self-calling functions.
	DirectRecursion int `json:"direct_recursion"`

	// MutualRecursion is the count of two-function cycles.
	MutualRecursion int `json:"mutual_recursion"`

	// ComplexCycles is the count of larger cycles (3+ nodes).
	ComplexCycles int `json:"complex_cycles"`

	// MaxNesting is the maximum nesting depth.
	MaxNesting int `json:"max_nesting"`

	// DeepestLoop is the header of the deepest nested loop.
	DeepestLoop string `json:"deepest_loop,omitempty"`
}

LoopsSummary contains aggregate statistics about loops.

type MapParams

type MapParams struct {
	// Tool is the name of the tool these parameters belong to.
	Tool string

	// Params is the raw parameter map from JSON unmarshaling.
	Params map[string]any
}

MapParams wraps a raw map[string]any (from LLM tool calls) as a TypedParams.

Description:

When the LLM produces tool calls, the parameters arrive as map[string]any
from JSON unmarshaling. MapParams wraps these raw maps to satisfy the
TypedParams interface, allowing a single Execute(ctx, TypedParams) signature
for both the forced-tool path (which produces concrete typed params) and
the LLM/executor path (which produces raw maps).

Thread Safety: Safe for concurrent use (value type, map is not mutated).

func (MapParams) ToMap

func (p MapParams) ToMap() map[string]any

ToMap returns the underlying parameter map.

func (MapParams) ToolName

func (p MapParams) ToolName() string

ToolName returns the tool name.

type MergePointInfo

type MergePointInfo struct {
	// ID is the full node ID of the merge point.
	ID string `json:"id"`

	// Name is the function name of the merge point.
	Name string `json:"name"`

	// File is the source file containing this merge point.
	File string `json:"file,omitempty"`

	// Line is the line number in the source file.
	Line int `json:"line,omitempty"`

	// ConvergingPaths is the number of code paths that converge at this point.
	ConvergingPaths int `json:"converging_paths"`

	// SourceNodes lists the nodes whose dominance frontier includes this merge point.
	SourceNodes []string `json:"source_nodes,omitempty"`

	// HasMoreSources indicates if there are more source nodes than shown.
	HasMoreSources bool `json:"has_more_sources,omitempty"`
}

MergePointInfo holds information about a single merge point.

type MergePointsSummary

type MergePointsSummary struct {
	// TotalMergePoints is the total number of merge points detected.
	TotalMergePoints int `json:"total_merge_points"`

	// Returned is the number of merge points returned in this result.
	Returned int `json:"returned"`

	// MaxConvergence is the maximum convergence count among returned merge points.
	MaxConvergence int `json:"max_convergence"`

	// AvgConvergence is the average convergence count among returned merge points.
	AvgConvergence float64 `json:"avg_convergence"`
}

MergePointsSummary contains aggregate statistics about merge points.

type MockTool

type MockTool struct {
	ExecuteFunc func(ctx context.Context, params TypedParams) (*Result, error)
	// contains filtered or unexported fields
}

MockTool is a simple tool implementation for testing.

func NewMockTool

func NewMockTool(name string, category ToolCategory) *MockTool

NewMockTool creates a mock tool for testing.

func (*MockTool) Category

func (t *MockTool) Category() ToolCategory

func (*MockTool) Definition

func (t *MockTool) Definition() ToolDefinition

func (*MockTool) Execute

func (t *MockTool) Execute(ctx context.Context, params TypedParams) (*Result, error)

func (*MockTool) Name

func (t *MockTool) Name() string

func (*MockTool) WithDefinition

func (t *MockTool) WithDefinition(d ToolDefinition) *MockTool

type ModuleAPI

type ModuleAPI struct {
	// CommunityID is the community identifier.
	CommunityID int `json:"community_id"`

	// Name is a human-readable module name.
	Name string `json:"name"`

	// DominantPackage is the package containing most nodes.
	DominantPackage string `json:"dominant_package"`

	// Size is the number of nodes in this community.
	Size int `json:"size"`

	// APISurface is the list of entry point functions.
	APISurface []APIFunction `json:"api_surface"`

	// InternalOnly is the list of internal-only functions (not externally callable).
	InternalOnly []string `json:"internal_only,omitempty"`

	// Note is an optional message about this module.
	Note string `json:"note,omitempty"`
}

ModuleAPI represents a single code module (community) with its API surface.

type ModuleAPISummary

type ModuleAPISummary struct {
	// CommunitiesAnalyzed is the number of communities analyzed.
	CommunitiesAnalyzed int `json:"communities_analyzed"`

	// CommunitiesFiltered is the number filtered by min_size.
	CommunitiesFiltered int `json:"communities_filtered"`

	// TotalAPIFunctions is the total count of API functions across all modules.
	TotalAPIFunctions int `json:"total_api_functions"`

	// AvgAPISize is the average number of API functions per module.
	AvgAPISize float64 `json:"avg_api_size"`
}

ModuleAPISummary contains aggregate statistics.

type PackageAPI

type PackageAPI struct {
	Types      []SymbolSummary `json:"types,omitempty"`
	Functions  []SymbolSummary `json:"functions,omitempty"`
	Interfaces []SymbolSummary `json:"interfaces,omitempty"`
	Constants  []SymbolSummary `json:"constants,omitempty"`
	Variables  []SymbolSummary `json:"variables,omitempty"`
}

PackageAPI represents the public API of a package.

type PackageDependency

type PackageDependency struct {
	From string `json:"from"`
	To   string `json:"to"`
	Type string `json:"type"` // "import"
}

PackageDependency represents a dependency edge between packages.

type PackageInfo

type PackageInfo struct {
	Name        string   `json:"name"`
	Path        string   `json:"path"`
	Files       []string `json:"files"`
	FileCount   int      `json:"file_count"`
	SymbolCount int      `json:"symbol_count"`
	Types       int      `json:"types"`
	Functions   int      `json:"functions"`
	IsTest      bool     `json:"is_test,omitempty"`
}

PackageInfo contains information about a discovered package.

type PackageOverview

type PackageOverview struct {
	Name        string   `json:"name"`
	Path        string   `json:"path"`
	FileCount   int      `json:"file_count"`
	SymbolCount int      `json:"symbol_count"`
	TypeCount   int      `json:"type_count"`
	FuncCount   int      `json:"func_count"`
	IsMain      bool     `json:"is_main,omitempty"`
	IsTest      bool     `json:"is_test,omitempty"`
	TopFiles    []string `json:"top_files,omitempty"`
	DependsOn   []string `json:"depends_on,omitempty"`
	DependedBy  []string `json:"depended_by,omitempty"`
}

PackageOverview contains summary information about a package.

type ParamDef

type ParamDef struct {
	// Type is the parameter type.
	Type ParamType `json:"type"`

	// Description explains what the parameter is for.
	Description string `json:"description"`

	// Required indicates if the parameter must be provided.
	Required bool `json:"required"`

	// Default is the default value if not provided.
	// Uses `any` for JSON schema flexibility - can be string, number, boolean, etc.
	Default any `json:"default,omitempty"`

	// Enum restricts values to a set of options.
	// Uses `[]any` for JSON schema flexibility - enum values match the param type.
	Enum []any `json:"enum,omitempty"`

	// MinLength is the minimum string length (for string type).
	MinLength int `json:"minLength,omitempty"`

	// MaxLength is the maximum string length (for string type).
	MaxLength int `json:"maxLength,omitempty"`

	// Minimum is the minimum value (for numeric types).
	Minimum *float64 `json:"minimum,omitempty"`

	// Maximum is the maximum value (for numeric types).
	Maximum *float64 `json:"maximum,omitempty"`

	// Items defines array item type (for array type).
	Items *ParamDef `json:"items,omitempty"`

	// Properties defines object properties (for object type).
	Properties map[string]ParamDef `json:"properties,omitempty"`
}

ParamDef defines a single parameter for a tool.

NOTE: This struct uses `any` types for Default and Enum to support JSON schema flexibility. The default value and enum options can be any JSON-compatible type (string, number, boolean, object, array). This is an intentional exception to CLAUDE.md Section 4.5 ("no map[string]any") because tool definitions require schema flexibility for LLM tool calling. All values are validated at runtime when the tool is invoked.

type ParamType

type ParamType string

ParamType represents the type of a tool parameter.

const (
	// ParamTypeString is a string parameter.
	ParamTypeString ParamType = "string"

	// ParamTypeInt is an integer parameter.
	ParamTypeInt ParamType = "integer"

	// ParamTypeFloat is a floating-point parameter.
	ParamTypeFloat ParamType = "number"

	// ParamTypeBool is a boolean parameter.
	ParamTypeBool ParamType = "boolean"

	// ParamTypeArray is an array parameter.
	ParamTypeArray ParamType = "array"

	// ParamTypeObject is an object parameter.
	ParamTypeObject ParamType = "object"
)

type ParseFormat

type ParseFormat string

ParseFormat represents the format of tool calls in LLM output.

const (
	// FormatXML parses <tool_call><name>...</name><params>...</params></tool_call>
	FormatXML ParseFormat = "xml"

	// FormatJSON parses {"tool": "...", "params": {...}}
	FormatJSON ParseFormat = "json"

	// FormatFunctionCall parses OpenAI function calling format.
	FormatFunctionCall ParseFormat = "function_call"

	// FormatAnthropicXML parses Anthropic's function call XML format.
	FormatAnthropicXML ParseFormat = "anthropic_xml"
)

type ParseResult

type ParseResult struct {
	// ToolCalls contains extracted tool calls.
	ToolCalls []ToolCall

	// CleanedText is the text with tool calls removed.
	CleanedText string

	// Fallback indicates no format matched.
	Fallback bool

	// Partial indicates format partially matched (malformed).
	Partial bool

	// Error is non-nil if parse error occurred.
	Error error
}

ParseResult contains the result of parsing with full metadata.

type Parser

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

Parser extracts tool calls from LLM output text.

Description:

Parses LLM output to extract tool calls in various formats.
The parser tries each enabled format in order until it finds matches.

Thread Safety: Parser is safe for concurrent use.

func NewParser

func NewParser(formats ...ParseFormat) *Parser

NewParser creates a new tool call parser.

Description:

Creates a parser that will try the specified formats in order.
If no formats are specified, defaults to trying all formats.

Inputs:

formats - Formats to try, in order of preference

Outputs:

*Parser - The configured parser

func (*Parser) ExtractTextBetweenToolCalls

func (p *Parser) ExtractTextBetweenToolCalls(text string) string

ExtractTextBetweenToolCalls returns text segments not part of tool calls.

Description:

Useful for getting the LLM's explanatory text separate from tool calls.

Inputs:

text - The full LLM output

Outputs:

string - Text with all tool call markup removed

func (*Parser) Parse

func (p *Parser) Parse(text string) ([]ToolCall, string, error)

Parse extracts tool calls from text.

Description:

Parses the input text trying each configured format in order.
Returns all found tool calls, the remaining text (without tool calls),
and any error encountered.

Inputs:

text - The LLM output text to parse

Outputs:

[]ToolCall - Extracted tool calls
string - Remaining text after removing tool calls
error - Non-nil if parsing failed completely

Thread Safety: This method is safe for concurrent use.

func (*Parser) ParseFunctionCalls

func (p *Parser) ParseFunctionCalls(toolCalls []FunctionCallResponse) ([]ToolCall, error)

ParseFunctionCalls parses OpenAI-style function calls from a structured response.

Description:

Parses function calls from an OpenAI-compatible chat completion response.
This handles the structured tool_calls array from the API response.

Inputs:

toolCalls - Array of tool calls from API response

Outputs:

[]ToolCall - Parsed tool calls
error - Non-nil if parsing fails

Thread Safety: This method is safe for concurrent use.

type PathNode

type PathNode struct {
	// Hop is the position in the path (0-indexed).
	Hop int `json:"hop"`

	// ID is the node ID.
	ID string `json:"id"`

	// Name is the symbol name.
	Name string `json:"name,omitempty"`

	// File is the source file path.
	File string `json:"file,omitempty"`

	// Line is the line number.
	Line int `json:"line,omitempty"`

	// Kind is the symbol kind.
	Kind string `json:"kind,omitempty"`
}

PathNode represents a node in the path.

type ReadFileOutput

type ReadFileOutput struct {
	// Path is the file path.
	Path string `json:"path"`

	// Language is the detected language.
	Language string `json:"language"`

	// TotalLines is the total number of lines in the file.
	TotalLines int `json:"total_lines"`

	// StartLine is the first line returned (1-indexed).
	StartLine int `json:"start_line"`

	// EndLine is the last line returned (1-indexed).
	EndLine int `json:"end_line"`

	// Source is the file content.
	Source string `json:"source"`

	// Truncated indicates if the response was limited by max lines (500).
	Truncated bool `json:"truncated"`
}

ReadFileOutput contains the structured result.

type ReadFileParams

type ReadFileParams struct {
	// Path is the file path relative to the project root.
	Path string

	// StartLine is the first line to read (1-indexed, inclusive). Default: 1.
	StartLine int

	// EndLine is the last line to read (1-indexed, inclusive). Default: 200.
	EndLine int

	// Truncated is true when the requested range exceeded 500 lines and was clamped.
	Truncated bool
}

ReadFileParams contains the validated input parameters.

func (ReadFileParams) ToMap

func (p ReadFileParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (ReadFileParams) ToolName

func (p ReadFileParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type ReadSymbolMatch

type ReadSymbolMatch struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// FilePath is the file containing the symbol.
	FilePath string `json:"file_path"`

	// StartLine is the first line of the symbol (1-indexed).
	StartLine int `json:"start_line"`

	// EndLine is the last line of the symbol (1-indexed).
	EndLine int `json:"end_line"`

	// Language is the source language.
	Language string `json:"language"`

	// Kind is the symbol kind.
	Kind string `json:"kind"`

	// Source is the source code of the symbol.
	Source string `json:"source"`

	// Truncated indicates if the source was truncated (over 500 lines).
	Truncated bool `json:"truncated"`

	// LineCount is the total number of lines in the symbol.
	LineCount int `json:"line_count"`
}

ReadSymbolMatch contains source code for a single symbol.

type ReadSymbolOutput

type ReadSymbolOutput struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// Matches contains the source code for each matching symbol.
	Matches []ReadSymbolMatch `json:"matches"`

	// MatchCount is the number of matching symbols.
	MatchCount int `json:"match_count"`
}

ReadSymbolOutput contains the structured result.

type ReadSymbolParams

type ReadSymbolParams struct {
	// Name is the name of the symbol to read source code for.
	Name string

	// Kind is an optional filter for the symbol kind (function, class, etc.).
	Kind string

	// PackageHint is an optional package/module context for disambiguation.
	PackageHint string
}

ReadSymbolParams contains the validated input parameters.

func (ReadSymbolParams) ToMap

func (p ReadSymbolParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (ReadSymbolParams) ToolName

func (p ReadSymbolParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type RecoveryResult

type RecoveryResult struct {
	// OriginalError is the error that was analyzed.
	OriginalError string `json:"original_error"`

	// Category is the type of error (e.g., "file_not_found", "timeout").
	Category string `json:"category"`

	// Suggestion is the recovery suggestion.
	Suggestion string `json:"suggestion"`

	// Retryable indicates if the operation might succeed on retry.
	Retryable bool `json:"retryable"`
}

RecoveryResult contains analysis of an error with suggestions.

type ReferenceInfo

type ReferenceInfo struct {
	// SymbolID is the symbol ID being referenced.
	SymbolID string `json:"symbol_id"`

	// Package is the package containing the reference.
	Package string `json:"package"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Column is the column number.
	Column int `json:"column"`
}

ReferenceInfo holds information about a reference location.

type Registry

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

Registry manages tool registration and lookup.

The registry follows the same pattern as ast.ParserRegistry, providing thread-safe registration and lookup of tools by name and category.

Thread Safety:

Registry is fully thread-safe. All methods can be called concurrently.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new empty tool registry.

Outputs:

*Registry - Empty registry ready for tool registration

func (*Registry) Categories

func (r *Registry) Categories() []ToolCategory

Categories returns all categories that have registered tools.

Description:

Returns all categories that have at least one registered tool,
sorted alphabetically for deterministic ordering.

Outputs:

[]ToolCategory - Categories with at least one tool, sorted alphabetically

Thread Safety: This method is safe for concurrent use.

func (*Registry) Count

func (r *Registry) Count() int

Count returns the number of registered tools.

Outputs:

int - Total number of tools

Thread Safety: This method is safe for concurrent use.

func (*Registry) CountByCategory

func (r *Registry) CountByCategory(category ToolCategory) int

CountByCategory returns the number of tools in a category.

Inputs:

category - The category to count

Outputs:

int - Number of tools in the category

Thread Safety: This method is safe for concurrent use.

func (*Registry) Get

func (r *Registry) Get(name string) (Tool, bool)

Get returns a tool by name.

Inputs:

name - The tool name

Outputs:

Tool - The registered tool, or nil if not found
bool - True if the tool was found

Thread Safety: This method is safe for concurrent use.

func (*Registry) GetAll

func (r *Registry) GetAll() []Tool

GetAll returns all registered tools.

Description:

Returns all registered tools sorted by name for deterministic ordering.
The returned slice is a copy and can be safely modified by the caller.

Outputs:

[]Tool - All registered tools, sorted by name

Thread Safety: This method is safe for concurrent use.

func (*Registry) GetByCategories

func (r *Registry) GetByCategories(categories ...ToolCategory) []Tool

GetByCategories returns tools from multiple categories.

Inputs:

categories - Categories to include

Outputs:

[]Tool - Tools in any of the specified categories

Thread Safety: This method is safe for concurrent use.

func (*Registry) GetByCategory

func (r *Registry) GetByCategory(category ToolCategory) []Tool

GetByCategory returns all tools in a category.

Inputs:

category - The category to filter by

Outputs:

[]Tool - Tools in the category (may be empty)

Thread Safety: This method is safe for concurrent use.

func (*Registry) GetDefinitions

func (r *Registry) GetDefinitions() []ToolDefinition

GetDefinitions returns definitions for all registered tools.

Outputs:

[]ToolDefinition - Definitions for all tools

Thread Safety: This method is safe for concurrent use.

func (*Registry) GetDefinitionsFiltered

func (r *Registry) GetDefinitionsFiltered(enabledCategories []string, disabledTools []string) []ToolDefinition

GetDefinitionsFiltered returns definitions for enabled tools.

Inputs:

enabledCategories - Categories to include (empty = all)
disabledTools - Specific tool names to exclude

Outputs:

[]ToolDefinition - Definitions for enabled tools

Thread Safety: This method is safe for concurrent use.

func (*Registry) GetEnabled

func (r *Registry) GetEnabled(enabledCategories []string, disabledTools []string) []Tool

GetEnabled returns tools that match the enabled criteria.

Inputs:

enabledCategories - Categories to include (empty = all)
disabledTools - Specific tool names to exclude

Outputs:

[]Tool - Enabled tools sorted by priority

Thread Safety: This method is safe for concurrent use.

func (*Registry) Names

func (r *Registry) Names() []string

Names returns all registered tool names.

Outputs:

[]string - All tool names

Thread Safety: This method is safe for concurrent use.

func (*Registry) Register

func (r *Registry) Register(tool Tool)

Register adds a tool to the registry.

Description:

Registers a tool under its Name() and Category(). If a tool with
the same name is already registered, it will be replaced.

Inputs:

tool - The tool to register. Must not be nil.

Thread Safety: This method is safe for concurrent use.

Example:

registry := NewRegistry()
registry.Register(NewFindEntryPointsTool(graph, index))
registry.Register(NewTraceDataFlowTool(graph, index))

func (*Registry) Unregister

func (r *Registry) Unregister(name string) bool

Unregister removes a tool from the registry.

Inputs:

name - The tool name to remove

Outputs:

bool - True if the tool was found and removed

Thread Safety: This method is safe for concurrent use.

type ResolveFuzzyOpt

type ResolveFuzzyOpt func(*resolveFuzzyConfig)

ResolveFuzzyOpt configures optional behavior for ResolveFunctionWithFuzzy.

Thread Safety: Option functions are safe for concurrent use.

func WithBareMethodFallback

func WithBareMethodFallback() ResolveFuzzyOpt

WithBareMethodFallback enables the bare method name fallback for dot-notation queries.

Description:

IT-02 C-1: When dot-notation resolution fails (e.g., "DB.Open" where Open is
a package-level function, not a method on DB), the resolver will try resolving
just the method part ("Open") alone via exact match and kind filtering.

Example:

sym, _, err := ResolveFunctionWithFuzzy(ctx, idx, "DB.Open", logger,
    WithBareMethodFallback())

Thread Safety: This function is safe for concurrent use.

func WithKindFilter

func WithKindFilter(kf KindFilter) ResolveFuzzyOpt

WithKindFilter sets which symbol kinds to accept during resolution.

Description:

Overrides the default KindFilterCallable behavior. Use KindFilterType for
type-focused tools (find_implementations) or KindFilterAny for tools that
operate on any symbol kind (find_references).

Inputs:

  • kf: The kind filter to apply to both exact match and fuzzy search paths.

Example:

sym, _, err := ResolveFunctionWithFuzzy(ctx, idx, "Router", logger,
    WithKindFilter(KindFilterType))

Thread Safety: This function is safe for concurrent use.

type ResolvedTarget

type ResolvedTarget struct {
	Name string
	ID   string
}

ResolvedTarget holds a resolved target with its ID and name.

type Result

type Result struct {
	// Success indicates if the tool succeeded.
	Success bool `json:"success"`

	// Output is the tool's output data.
	Output any `json:"output"`

	// OutputText is a text representation of the output.
	OutputText string `json:"output_text"`

	// Error contains any error message.
	Error string `json:"error,omitempty"`

	// Duration is how long execution took.
	Duration time.Duration `json:"duration"`

	// TokensUsed estimates the output token count.
	TokensUsed int `json:"tokens_used"`

	// Cached indicates if result came from cache.
	Cached bool `json:"cached"`

	// Truncated indicates if output was truncated.
	Truncated bool `json:"truncated"`

	// ModifiedFiles lists files written or modified by this tool.
	// Used by DirtyTracker to trigger incremental graph refresh.
	// Tools that write to the file system should populate this.
	ModifiedFiles []string `json:"modified_files,omitempty"`

	// Metadata contains additional result metadata.
	Metadata map[string]any `json:"metadata,omitempty"`

	// TraceStep is the CRS trace step for this tool execution.
	// Tools that want full CRS integration should populate this.
	// The dispatcher/execute phase will record it to the session.
	TraceStep *crs.TraceStep `json:"trace_step,omitempty"`

	// ResultCount is the number of discrete results the tool produced.
	// Used by CRS Layer 2 to detect empty-result conditions for CDCL clause generation.
	// Tools should set this; if 0, the phase will attempt extraction from TraceStep metadata.
	ResultCount int `json:"result_count,omitempty"`

	// ScopeApplied is the package/directory scope filter that was applied to this result.
	// CRS-SCOPE-01: Used by scope relaxation to detect empty scoped results
	// that should be retried with a wider scope.
	ScopeApplied string `json:"scope_applied,omitempty"`

	// PreScopeCount is the number of results before scope filtering was applied.
	// CRS-SCOPE-01: When ResultCount==0 and PreScopeCount>0, scope relaxation
	// knows that results exist but were filtered out by the scope.
	PreScopeCount int `json:"pre_scope_count,omitempty"`

	// ProofDelta overrides the default proof number delta (1) when non-zero.
	// IT_CRS_03 AC-8: Higher values = stronger signal. Example: exact match = 2, fuzzy = 1.
	ProofDelta int `json:"proof_delta,omitempty"`
}

Result contains the outcome of a tool execution.

type SanitizeResult

type SanitizeResult struct {
	// Content is the sanitized output safe for context injection.
	Content string

	// OriginalLength is the byte length before sanitization.
	OriginalLength int

	// WasTruncated indicates if output was cut short.
	WasTruncated bool

	// TruncatedBytes is how many bytes were removed.
	TruncatedBytes int

	// EscapedPatterns lists which patterns were escaped.
	EscapedPatterns []string

	// SuspiciousPatterns lists concerning patterns found (for logging).
	SuspiciousPatterns []string

	// Modified indicates if any changes were made.
	Modified bool
}

SanitizeResult contains the outcome of sanitization.

type SanitizerConfig

type SanitizerConfig struct {
	// MaxOutputBytes is hard limit on output size (default: 100KB).
	MaxOutputBytes int

	// MaxOutputTokens is soft limit for context budget (default: 30k).
	MaxOutputTokens int

	// CustomDangerousPatterns adds additional patterns to escape.
	CustomDangerousPatterns []string

	// CustomSuspiciousPatterns adds additional suspicious patterns.
	CustomSuspiciousPatterns []string

	// EnableSuspiciousLogging logs when suspicious content detected.
	EnableSuspiciousLogging bool

	// Logger for warnings (optional).
	Logger *slog.Logger
}

SanitizerConfig configures the sanitizer.

func DefaultSanitizerConfig

func DefaultSanitizerConfig() SanitizerConfig

DefaultSanitizerConfig returns sensible defaults.

type SemanticSearchOutput

type SemanticSearchOutput struct {
	// Query is the search query that was executed.
	Query string `json:"query"`

	// ResultCount is the number of results found.
	ResultCount int `json:"result_count"`

	// Results contains the ranked search results.
	Results []SemanticSearchResult `json:"results"`
}

SemanticSearchOutput contains the structured result.

type SemanticSearchParams

type SemanticSearchParams struct {
	// Query is the natural language search query.
	Query string

	// Limit is the maximum number of results to return.
	// Default: 10, Max: 50
	Limit int

	// MinScore is the minimum similarity threshold (0.0-1.0).
	// Default: 0.5
	MinScore float64
}

SemanticSearchParams contains the validated input parameters.

func (SemanticSearchParams) ToMap

func (p SemanticSearchParams) ToMap() map[string]any

ToMap converts typed parameters to the map consumed by Tool.Execute().

func (SemanticSearchParams) ToolName

func (p SemanticSearchParams) ToolName() string

ToolName returns the tool name for TypedParams interface.

type SemanticSearchResult

type SemanticSearchResult struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind (function, method, class, etc.).
	Kind string `json:"kind"`

	// PackagePath is the package/module path.
	PackagePath string `json:"package_path"`

	// FilePath is the source file path.
	FilePath string `json:"file_path"`

	// Score is the similarity score (0.0-1.0, higher is more similar).
	Score float64 `json:"score"`
}

SemanticSearchResult represents a single semantic search result.

type SignatureMatch

type SignatureMatch struct {
	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind (function, method, class, etc.).
	Kind string `json:"kind"`

	// FilePath is the file containing the symbol.
	FilePath string `json:"file_path"`

	// StartLine is the first line of the symbol (1-indexed).
	StartLine int `json:"start_line"`

	// Signature is the type signature or declaration.
	Signature string `json:"signature"`

	// DocComment is the extracted documentation comment.
	DocComment string `json:"doc_comment"`

	// Exported indicates if the symbol is publicly visible.
	Exported bool `json:"exported"`

	// Package is the package or module name.
	Package string `json:"package"`

	// Receiver is the receiver type (for Go methods).
	Receiver string `json:"receiver,omitempty"`
}

SignatureMatch contains signature info for a single symbol.

type SymbolInfo

type SymbolInfo struct {
	// ID is the symbol's unique identifier.
	ID string `json:"id"`

	// Name is the symbol name.
	Name string `json:"name"`

	// Kind is the symbol kind.
	Kind string `json:"kind"`

	// File is the source file path.
	File string `json:"file"`

	// Line is the line number.
	Line int `json:"line"`

	// Package is the package name.
	Package string `json:"package"`

	// Signature is the function/method signature.
	Signature string `json:"signature,omitempty"`

	// Exported indicates if the symbol is exported.
	Exported bool `json:"exported"`
}

SymbolInfo holds information about a symbol.

type SymbolSummary

type SymbolSummary struct {
	Name      string `json:"name"`
	Kind      string `json:"kind"`
	Signature string `json:"signature,omitempty"`
	File      string `json:"file"`
	Line      int    `json:"line"`
	Exported  bool   `json:"exported"`
}

SymbolSummary contains summary information about a symbol.

type Tool

type Tool interface {
	// Name returns the unique tool name.
	Name() string

	// Category returns the tool category.
	Category() ToolCategory

	// Definition returns the tool's parameter schema.
	Definition() ToolDefinition

	// Execute runs the tool with the given parameters.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout
	//   params - Typed parameters (use params.ToMap() to access raw map)
	//
	// Outputs:
	//   *Result - Execution result
	//   error - Non-nil if execution failed
	Execute(ctx context.Context, params TypedParams) (*Result, error)
}

Tool defines the interface for executable tools.

Implementations must be safe for concurrent use.

func NewBuildMinimalContextTool

func NewBuildMinimalContextTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewBuildMinimalContextTool creates the build_minimal_context tool.

func NewCheckReducibilityTool

func NewCheckReducibilityTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewCheckReducibilityTool creates a new check_reducibility tool.

Description:

Creates a tool for checking graph reducibility - whether the call graph
is well-structured with clean loop structures. Non-reducible regions
indicate complex or potentially problematic code.

Inputs:

  • analytics: GraphAnalytics instance for reducibility checking. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured check_reducibility tool.

Limitations:

  • Requires dominator tree computation
  • Maximum 100 irreducible regions enumerated

Thread Safety: Safe for concurrent use after construction.

func NewExplorePackageTool

func NewExplorePackageTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewExplorePackageTool creates the explore_package tool.

Description:

Creates a tool for exploring a specific package, showing its files,
public API, dependencies, and inferred purpose. This is the mid-level
navigation tool for understanding package responsibilities.

Thread Safety: Safe for concurrent use.

func NewFindArticulationPointsTool

func NewFindArticulationPointsTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindArticulationPointsTool creates the find_articulation_points tool.

Description:

Creates a tool that finds single points of failure in the call graph
using Tarjan's articulation point algorithm. These are functions whose
removal would disconnect parts of the codebase.

Inputs:

  • analytics: The GraphAnalytics instance. Must not be nil.
  • idx: Symbol index for name lookups. May be nil for degraded operation.

Outputs:

  • Tool: The find_articulation_points tool implementation.

Limitations:

  • Treats directed call graph as undirected for connectivity
  • Maximum 100 articulation points reported
  • Impact scoring is approximate (based on degree, not actual removal)

Assumptions:

  • Graph is frozen and indexed before tool creation
  • Analytics wraps a HierarchicalGraph

func NewFindCalleesTool

func NewFindCalleesTool(g *graph.Graph, idx *index.SymbolIndex, analytics *graph.GraphAnalytics) Tool

NewFindCalleesTool creates the find_callees tool.

Description:

Creates a tool that finds all functions called by a given function.
Separates in-codebase callees from external/stdlib callees.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The find_callees tool implementation.

Limitations:

  • Symbol names must match exactly (no fuzzy matching)
  • External callees have no file location
  • Maximum 1000 callees per query

Assumptions:

  • Graph is frozen before tool creation
  • Index is populated with all symbols

func NewFindCallersTool

func NewFindCallersTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindCallersTool creates the find_callers tool.

Description:

Creates a tool that finds all functions that call a given function.
Uses O(1) index lookup when available, falls back to O(V) graph scan.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The find_callers tool implementation.

Limitations:

  • Symbol names must match exactly (no fuzzy matching)
  • When multiple symbols share a name, limit applies per symbol
  • Maximum 1000 callers per query

Assumptions:

  • Graph is frozen before tool creation
  • Index is populated with all symbols

func NewFindCommonDependencyTool

func NewFindCommonDependencyTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindCommonDependencyTool creates a new find_common_dependency tool instance.

Description:

Creates a tool that finds the lowest common dominator (LCD) of multiple
target functions. The LCD is the deepest function that must be called
to reach all specified targets - their shared mandatory dependency.

Inputs:

  • analytics: Graph analytics engine. Must not be nil for meaningful results.
  • idx: Symbol index for name resolution. Must not be nil for meaningful results.

Outputs:

  • Tool: The tool implementation.

Thread Safety: Safe for concurrent use after construction.

func NewFindCommunitiesTool

func NewFindCommunitiesTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindCommunitiesTool creates the find_communities tool.

Description:

Creates a tool that discovers natural code communities using the
Leiden algorithm. Unlike package boundaries which are organizational
choices, communities reflect actual code coupling patterns.

Inputs:

  • analytics: The GraphAnalytics instance. Must not be nil.
  • idx: Symbol index for name lookups. Must not be nil.

Outputs:

  • Tool: The find_communities tool implementation.

Limitations:

  • Leiden is more expensive than simple queries: O(V+E) per iteration
  • Maximum 50 communities reported to prevent excessive output
  • Large codebases (>100K nodes) may take several seconds

Assumptions:

  • Graph is frozen and indexed before tool creation
  • Analytics wraps a HierarchicalGraph

func NewFindConfigUsageTool

func NewFindConfigUsageTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindConfigUsageTool creates the find_config_usage tool.

func NewFindControlDependenciesTool

func NewFindControlDependenciesTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindControlDependenciesTool creates a new find_control_dependencies tool.

Description:

Creates a tool for finding control dependencies - which conditional
nodes (branch points) determine whether a target function executes.

Inputs:

  • analytics: GraphAnalytics instance for control dependence computation. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured find_control_dependencies tool.

Limitations:

  • Requires post-dominator tree computation
  • May not detect all control flow patterns in highly dynamic code

Thread Safety: Safe for concurrent use after construction.

func NewFindCriticalPathTool

func NewFindCriticalPathTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindCriticalPathTool creates a new find_critical_path tool.

Description:

Creates a tool for finding the mandatory call sequence (critical path)
to reach a target function using dominator tree analysis.

Inputs:

  • analytics: GraphAnalytics instance for dominator computation. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured find_critical_path tool.

Thread Safety: Safe for concurrent use after construction.

Limitations:

  • Requires dominator tree computation which needs an entry point
  • Only shows dominator-based critical path, not all possible paths
  • Target must be reachable from entry point

func NewFindCyclesTool

func NewFindCyclesTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindCyclesTool creates the find_cycles tool.

Description:

Creates a tool that finds circular dependencies in the codebase using
Tarjan's SCC algorithm. Cycles indicate tight coupling that can make
code harder to maintain, test, and understand.

Inputs:

  • analytics: The GraphAnalytics instance for cycle detection. Must not be nil.
  • idx: The symbol index for resolving node IDs to symbol names. Must not be nil.

Outputs:

  • Tool: The find_cycles tool implementation.

Limitations:

  • Only detects call-graph cycles, not import cycles or data flow cycles
  • Maximum 100 cycles per query to prevent excessive output
  • Large cycles (many nodes) may be harder to visualize in text output

Assumptions:

  • Graph is frozen before tool creation
  • Tarjan's algorithm runs in O(V+E) time

func NewFindDeadCodeTool

func NewFindDeadCodeTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindDeadCodeTool creates the find_dead_code tool.

Description:

Creates a tool that finds potentially unused code (symbols with no callers).
Automatically excludes entry points (main, init, Test*) and interface methods.

Inputs:

  • analytics: The GraphAnalytics instance for dead code detection. Must not be nil.
  • idx: The symbol index for name lookups. Must not be nil.

Outputs:

  • Tool: The find_dead_code tool implementation.

Limitations:

  • Cannot detect usage via reflection or dynamic calls
  • Exported symbols may be used by external packages (use include_exported=true carefully)
  • Maximum 500 results per query
  • Package filter matches exact package name or file path substring

Assumptions:

  • Graph is frozen before tool creation
  • Entry points (main, init, Test*) are pre-filtered by analytics

func NewFindDominatorsTool

func NewFindDominatorsTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindDominatorsTool creates the find_dominators tool.

Description:

Creates a tool that finds all functions that must be called to reach a
target function. Uses dominator tree analysis to identify mandatory
call sequences from entry points to the target.

Inputs:

  • analytics: Graph analytics instance for dominator computation. Must not be nil.
  • idx: Symbol index for name resolution. May be nil.

Outputs:

  • Tool: The find_dominators tool. Never nil if analytics is valid.

Limitations:

  • Requires a designated entry point (auto-detected or specified)
  • May return empty result if target is unreachable from entry

Assumptions:

  • Graph is frozen and indexed before tool creation
  • Analytics wraps a HierarchicalGraph

func NewFindEntryPointsTool

func NewFindEntryPointsTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindEntryPointsTool creates the find_entry_points tool.

func NewFindExtractableRegionsTool

func NewFindExtractableRegionsTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindExtractableRegionsTool creates a new find_extractable_regions tool.

Description:

Creates a tool for finding Single-Entry Single-Exit (SESE) regions
that are suitable for extraction into separate functions. These regions
have exactly one entry and one exit point, making them safe to refactor.

Inputs:

  • analytics: GraphAnalytics instance for SESE detection. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured find_extractable_regions tool.

Limitations:

  • Requires both dominator and post-dominator tree computation
  • May produce many regions in large codebases; use size filters

Thread Safety: Safe for concurrent use after construction.

func NewFindHotspotsTool

func NewFindHotspotsTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindHotspotsTool creates the find_hotspots tool.

Description:

Creates a tool that finds the most-connected symbols in the codebase
(hotspots). Hotspots are nodes with high connectivity scores, indicating
central points in the code that many other components depend on.

Inputs:

  • analytics: The GraphAnalytics instance for hotspot detection. Must not be nil.
  • idx: The symbol index for name lookups. Must not be nil.

Outputs:

  • Tool: The find_hotspots tool implementation.

Limitations:

  • Connectivity score uses formula: inDegree*2 + outDegree (favors callee-heavy nodes)
  • Maximum 100 results per query to prevent excessive output
  • When filtering by kind, results may be fewer than requested if not enough match

Assumptions:

  • Graph is frozen and indexed before tool creation
  • Analytics wraps a HierarchicalGraph for O(V log k) complexity

func NewFindImplementationsTool

func NewFindImplementationsTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindImplementationsTool creates the find_implementations tool.

Description:

Creates a tool that finds all types implementing a given interface,
extending a given class, or embedding a given struct. Accepts
SymbolKindInterface, SymbolKindClass, and SymbolKindStruct as targets.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The find_implementations tool implementation.

Limitations:

  • Only searches for type symbols (functions, variables filtered out)
  • Maximum 1000 implementations per query

Assumptions:

  • Graph is frozen before tool creation
  • Implements and Embeds edges are properly indexed

func NewFindImportantTool

func NewFindImportantTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindImportantTool creates the find_important tool.

Description:

Creates a tool that finds the most important symbols using PageRank
algorithm. PageRank provides better importance ranking than simple
degree counting by considering the importance of callers transitively.

Inputs:

  • analytics: The GraphAnalytics instance for PageRank computation. Must not be nil.
  • idx: The symbol index for name lookups. Must not be nil.

Outputs:

  • Tool: The find_important tool implementation.

Limitations:

  • PageRank is more expensive than degree counting O(k × E) vs O(V)
  • Maximum 100 results per query to prevent excessive output
  • When filtering by kind, results may be fewer than requested

Assumptions:

  • Graph is frozen and indexed before tool creation
  • Analytics wraps a HierarchicalGraph

func NewFindLoopsTool

func NewFindLoopsTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindLoopsTool creates a new find_loops tool.

Description:

Creates a tool for detecting natural loops (recursion and cyclic call patterns)
in the call graph using dominator-based back edge analysis.

Inputs:

  • analytics: GraphAnalytics instance for loop detection. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured find_loops tool.

Thread Safety: Safe for concurrent use after construction.

Limitations:

  • Requires dominator tree computation which needs an entry point
  • May not detect all mutual recursion patterns in highly disconnected graphs

func NewFindMergePointsTool

func NewFindMergePointsTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindMergePointsTool creates a new find_merge_points tool.

Description:

Creates a tool for finding merge points - nodes where multiple code paths
converge. These are identified via dominance frontier analysis.

Inputs:

  • analytics: GraphAnalytics instance for frontier computation. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured find_merge_points tool.

Thread Safety: Safe for concurrent use after construction.

Limitations:

  • Requires dominator tree and dominance frontier computation
  • May not detect all merge points in highly disconnected graphs

func NewFindModuleAPITool

func NewFindModuleAPITool(analytics *graph.GraphAnalytics, g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindModuleAPITool creates a new find_module_api tool.

Description:

Creates a tool for finding the public API surface of code modules by combining
community detection with dominator analysis. Identifies mandatory entry points
to each detected module.

Inputs:

  • analytics: GraphAnalytics instance for community detection and dominators. Must not be nil.
  • g: Graph for edge traversal. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured find_module_api tool.

Thread Safety: Safe for concurrent use after construction.

Limitations:

  • Requires community detection and dominator computation (can be expensive)
  • Coverage calculation limited to dominator-reachable nodes
  • Module names are heuristic-based (dominant package)

func NewFindPathTool

func NewFindPathTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindPathTool creates the find_path tool.

Description:

Creates a tool that finds the shortest path between two symbols in the
code graph. Uses BFS to find the minimum-hop path considering all edge types.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for name-to-ID resolution. Must not be nil.

Outputs:

  • Tool: The find_path tool implementation.

Limitations:

  • Returns only one path even if multiple shortest paths exist
  • Path length is measured in hops, not weighted by call frequency

Assumptions:

  • Graph is frozen before tool creation
  • BFS runs in O(V+E) time
  • Caller handles disambiguation via package filter if needed

func NewFindReferencesTool

func NewFindReferencesTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindReferencesTool creates the find_references tool.

Description:

Creates a tool that finds all references to a symbol.
Useful for refactoring and understanding symbol usage.
Supports exact match, dot-notation (Type.Method), and fuzzy resolution
via the shared ResolveFunctionWithFuzzy pipeline.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The find_references tool implementation.

Limitations:

  • Resolves to a single best-match symbol (not all symbols of the same name)
  • References are code locations based on graph edges, not semantic relationships

Assumptions:

  • Graph is frozen before tool creation
  • Reference locations are indexed

func NewFindSimilarCodeTool

func NewFindSimilarCodeTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindSimilarCodeTool creates the find_similar_code tool.

func NewFindSimilarSymbolsTool

func NewFindSimilarSymbolsTool(wvClient *weaviate.Client, dataSpace string, embedClient *rag.EmbedClient, idx *index.SymbolIndex) Tool

NewFindSimilarSymbolsTool creates the find_similar_symbols tool.

Description:

CRS-26m: Creates a tool for finding symbols with similar purpose/behavior.
Gracefully degrades if any dependency is nil.

Inputs:

  • wvClient: Weaviate client. May be nil (graceful degradation).
  • dataSpace: Project isolation key for Weaviate.
  • embedClient: Embedding client. May be nil (graceful degradation).
  • idx: Symbol index for O(1) lookups. May be nil (graceful degradation).

Outputs:

  • Tool: The find_similar_symbols tool implementation.

Thread Safety: Safe for concurrent use after construction.

func NewFindSymbolTool

func NewFindSymbolTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewFindSymbolTool creates the find_symbol tool.

Description:

Creates a tool that looks up symbols by name with optional filters.
Useful for resolving ambiguous names or finding definitions.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The find_symbol tool implementation.

Limitations:

  • Symbol names must match exactly (no fuzzy matching)
  • Returns all matching symbols (may be multiple with same name)

Assumptions:

  • Graph is frozen before tool creation
  • Index is populated with all symbols

func NewFindWeightedCriticalityTool

func NewFindWeightedCriticalityTool(analytics *graph.GraphAnalytics, idx *index.SymbolIndex) Tool

NewFindWeightedCriticalityTool creates a new find_weighted_criticality tool.

Description:

Creates a tool for finding the most critical functions by combining dominator
analysis with PageRank. A function scores high if it's both a mandatory
dependency (high dominator score) AND architecturally important (high PageRank).
Criticality = normalize(DominatorScore) × normalize(PageRank).

Inputs:

  • analytics: GraphAnalytics instance for dominators and PageRank. Must not be nil.
  • idx: SymbolIndex for symbol lookups (can be nil for basic operation).

Outputs:

  • Tool: The configured find_weighted_criticality tool.

Thread Safety: Safe for concurrent use after construction.

Limitations:

  • Requires both dominator tree and PageRank computation (can be expensive)
  • Results are sensitive to entry point selection for dominators
  • Quadrant classification uses fixed threshold (0.5) for high/low

Assumptions:

  • Graph is frozen and immutable
  • PageRank converges (or uses last iteration on timeout)
  • Dominator tree exists (entry point is reachable)

func NewGetCallChainTool

func NewGetCallChainTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewGetCallChainTool creates the get_call_chain tool.

Description:

Creates a tool that traces transitive call chains from a function.
Can trace both upstream (callers) and downstream (callees).

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The get_call_chain tool implementation.

Limitations:

  • Maximum depth of 10 to prevent excessive traversal
  • May truncate large graphs

Assumptions:

  • Graph is frozen before tool creation
  • BFS traversal for call chain

func NewGetSignatureTool

func NewGetSignatureTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewGetSignatureTool creates the get_signature tool.

Description:

Creates a tool that returns signatures and doc comments for symbols.
Uses O(1) index lookup — no filesystem access needed.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The get_signature tool implementation.

Limitations:

  • Returns empty signature/doc if the parser didn't extract them

Assumptions:

  • Index is populated with all symbols

func NewGraphOverviewTool

func NewGraphOverviewTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewGraphOverviewTool creates the graph_overview tool.

Description:

Creates a tool for showing high-level project structure including
packages, their relationships, and metrics. This is the top-level
navigation tool for understanding a codebase.

Thread Safety: Safe for concurrent use.

func NewListPackagesTool

func NewListPackagesTool(idx *index.SymbolIndex) Tool

NewListPackagesTool creates the list_packages tool.

Description:

Creates a tool that lists all Go packages in the codebase by extracting
unique package names from the symbol index. This directly answers questions
like "What packages exist?" without requiring the model to be creative.

Inputs:

idx - The symbol index containing parsed symbols.

Outputs:

Tool - The list_packages tool.

func NewListSymbolsInFileTool

func NewListSymbolsInFileTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewListSymbolsInFileTool creates the list_symbols_in_file tool.

Description:

Creates a tool that lists all symbols defined in a given file.
Uses the symbol index's GetByFile for O(1) file-based lookup.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The list_symbols_in_file tool implementation.

Limitations:

  • Only shows symbols the parser extracted (may miss some constructs)

Assumptions:

  • Index is populated with all symbols

func NewReadFileTool

func NewReadFileTool(g *graph.Graph) Tool

NewReadFileTool creates the read_file tool.

Description:

Creates a tool that reads files or line ranges from the project.
Validates all paths against the project root for security.

Inputs:

  • g: The code graph (used for ProjectRoot). Must not be nil.

Outputs:

  • Tool: The read_file tool implementation.

Limitations:

  • Maximum 500 lines per request
  • Path must be under the project root

Assumptions:

  • Project files are accessible at graph.ProjectRoot

func NewReadSymbolTool

func NewReadSymbolTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewReadSymbolTool creates the read_symbol tool.

Description:

Creates a tool that reads source code for a named symbol.
Uses O(1) index lookup to find the symbol, then reads from filesystem.

Inputs:

  • g: The code graph. Must not be nil.
  • idx: The symbol index for O(1) lookups. Must not be nil.

Outputs:

  • Tool: The read_symbol tool implementation.

Limitations:

  • Symbol names must match exactly (no fuzzy matching initially)
  • Source files must be accessible on the filesystem
  • Maximum 500 lines before truncation flag is set

Assumptions:

  • Graph is frozen before tool creation
  • Index is populated with all symbols
  • Project files are accessible at graph.ProjectRoot

func NewSemanticSearchTool

func NewSemanticSearchTool(wvClient *weaviate.Client, dataSpace string, embedClient *rag.EmbedClient) Tool

NewSemanticSearchTool creates the semantic_search tool.

Description:

CRS-26m: Creates a tool for semantic code search using vector similarity.
Gracefully degrades if wvClient or embedClient is nil.

Inputs:

  • wvClient: Weaviate client. May be nil (graceful degradation).
  • dataSpace: Project isolation key for Weaviate.
  • embedClient: Embedding client. May be nil (graceful degradation).

Outputs:

  • Tool: The semantic_search tool implementation.

Thread Safety: Safe for concurrent use after construction.

func NewSummarizeFileTool

func NewSummarizeFileTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewSummarizeFileTool creates the summarize_file tool.

func NewTraceDataFlowTool

func NewTraceDataFlowTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewTraceDataFlowTool creates the trace_data_flow tool.

func NewTraceErrorFlowTool

func NewTraceErrorFlowTool(g *graph.Graph, idx *index.SymbolIndex) Tool

NewTraceErrorFlowTool creates the trace_error_flow tool.

type ToolCall

type ToolCall struct {
	// ID is a unique identifier for this call.
	ID string `json:"id"`

	// Name is the tool name to invoke.
	Name string `json:"name"`

	// Params contains the parsed parameters.
	Params json.RawMessage `json:"params"`

	// Raw is the original text for debugging.
	Raw string `json:"raw"`
}

ToolCall represents a parsed tool invocation from LLM output.

func FilterToolCalls

func FilterToolCalls(calls []ToolCall, filter func(ToolCall) bool) []ToolCall

FilterToolCalls filters tool calls by name prefix or category.

Description:

Useful for routing different types of tool calls to different handlers.

Inputs:

calls - Tool calls to filter
filter - Function that returns true for calls to keep

Outputs:

[]ToolCall - Filtered tool calls (may be empty)

Thread Safety: This function is safe for concurrent use.

func ToolCallFromInvocation

func ToolCallFromInvocation(inv *Invocation) (ToolCall, error)

ToolCallFromInvocation converts an Invocation to a ToolCall.

Description:

Converts the internal Invocation type to a ToolCall suitable for
use with the dispatcher.

Inputs:

inv - The invocation to convert. Must not be nil.

Outputs:

ToolCall - The converted tool call
error - Non-nil if parameter marshaling fails

Thread Safety: This function is safe for concurrent use.

func (*ToolCall) ParamsMap

func (tc *ToolCall) ParamsMap() (map[string]any, error)

ParamsMap returns the parameters as a map.

Description:

Deserializes the JSON parameters into a map for easier access.
Returns an empty map if Params is empty or nil.

Outputs:

map[string]any - Parameters as a map
error - Non-nil if JSON parsing fails

Thread Safety: This method is safe for concurrent use.

type ToolCategory

type ToolCategory string

ToolCategory represents the category a tool belongs to.

const (
	// CategoryExploration includes tools for exploring and understanding code.
	CategoryExploration ToolCategory = "exploration"

	// CategoryReasoning includes tools for reasoning about code.
	CategoryReasoning ToolCategory = "reasoning"

	// CategorySafety includes tools for security analysis.
	CategorySafety ToolCategory = "safety"

	// CategoryFile includes tools for file operations.
	CategoryFile ToolCategory = "file"

	// CategorySemantic includes tools for vector/semantic search.
	CategorySemantic ToolCategory = "semantic"
)

func (ToolCategory) String

func (c ToolCategory) String() string

String returns the string representation of the category.

type ToolDefinition

type ToolDefinition struct {
	// Name is the unique identifier for the tool.
	Name string `json:"name"`

	// Description explains what the tool does.
	Description string `json:"description"`

	// Parameters defines the input parameters.
	Parameters map[string]ParamDef `json:"parameters"`

	// Category is the tool category (exploration, reasoning, safety, file).
	Category ToolCategory `json:"category"`

	// Priority influences tool selection (higher = prefer).
	Priority int `json:"priority"`

	// Requires lists dependencies (e.g., "graph_initialized").
	Requires []string `json:"requires,omitempty"`

	// SideEffects indicates if the tool modifies state.
	SideEffects bool `json:"side_effects"`

	// Timeout is the default execution timeout.
	Timeout time.Duration `json:"timeout,omitempty"`

	// Examples provides usage examples.
	Examples []ToolExample `json:"examples,omitempty"`

	// WhenToUse provides structured routing guidance for the tool router.
	// CB-31e: Part of the tool contract - every new tool should define this.
	WhenToUse WhenToUse `json:"when_to_use,omitempty" yaml:"when_to_use,omitempty"`
}

ToolDefinition describes a tool's interface for the LLM.

This structure is designed to be serializable to JSON Schema format for use with LLM tool calling APIs.

func StaticToolDefinitions

func StaticToolDefinitions() []ToolDefinition

StaticToolDefinitions returns tool definitions without needing a graph.

Description:

Returns the definitions for all exploration tools. These can be used
for query classification without initializing the full tool system.
The definitions include tool names, descriptions, and parameter schemas.

Outputs:

[]ToolDefinition - The static tool definitions.

Example:

defs := tools.StaticToolDefinitions()
classifier, _ := classifier.NewLLMClassifier(client, defs, config)

Thread Safety: This function is safe for concurrent use.

func (*ToolDefinition) RequiredParams

func (d *ToolDefinition) RequiredParams() []string

RequiredParams returns a list of required parameter names.

type ToolExample

type ToolExample struct {
	// Description explains what the example demonstrates.
	Description string `json:"description"`

	// Parameters are the example input parameters.
	Parameters map[string]any `json:"parameters"`

	// ExpectedOutput describes what output to expect.
	ExpectedOutput string `json:"expected_output,omitempty"`
}

ToolExample provides an example invocation for a tool.

type ToolOutputSanitizer

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

ToolOutputSanitizer sanitizes tool results before context injection.

Thread Safety:

Safe for concurrent use after construction. All fields are read-only
after NewToolOutputSanitizer returns. The Sanitize method can be called
from multiple goroutines simultaneously.

func NewToolOutputSanitizer

func NewToolOutputSanitizer(config SanitizerConfig) (*ToolOutputSanitizer, error)

NewToolOutputSanitizer creates a new sanitizer with the given configuration.

Description:

Creates a ToolOutputSanitizer with pre-compiled patterns. All patterns
are compiled during construction for optimal runtime performance.

Inputs:

config - Configuration options. Uses defaults if zero values.

Outputs:

*ToolOutputSanitizer - The configured sanitizer.
error - Non-nil if pattern compilation fails.

Example:

sanitizer, err := NewToolOutputSanitizer(DefaultSanitizerConfig())
if err != nil {
    return err
}

func (*ToolOutputSanitizer) Sanitize

func (s *ToolOutputSanitizer) Sanitize(content string) SanitizeResult

Sanitize processes tool output for safe context injection.

Description:

Sanitizes the content by:
1. Validating UTF-8 encoding
2. Escaping dangerous patterns (tool tags, system tags)
3. Detecting suspicious prompt injection patterns
4. Truncating if over size limits

Inputs:

content - Raw tool output content.

Outputs:

SanitizeResult - The sanitization result with metadata.

Thread Safety: This method is safe for concurrent use.

func (*ToolOutputSanitizer) SanitizeString

func (s *ToolOutputSanitizer) SanitizeString(content string) string

SanitizeString is a convenience method for simple string sanitization.

Description:

Returns only the sanitized content string, discarding metadata.
Use Sanitize() when you need detailed information about what was changed.

Thread Safety: This method is safe for concurrent use.

func (*ToolOutputSanitizer) SanitizeWithContext

func (s *ToolOutputSanitizer) SanitizeWithContext(ctx context.Context, toolName string, content string) SanitizeResult

SanitizeWithContext sanitizes content and records metrics.

Description:

Sanitizes content while recording observability data via tracing
and metrics. Use this in production code paths.

Thread Safety: This method is safe for concurrent use.

func (*ToolOutputSanitizer) WrapWithBoundary

func (s *ToolOutputSanitizer) WrapWithBoundary(toolName string, args map[string]string, content string) string

WrapWithBoundary wraps sanitized content with boundary markers.

Description:

Wraps the content with clear boundary markers to help the LLM
distinguish tool output from instructions.

Inputs:

toolName - The name of the tool that produced the output.
args - Key argument values for context (e.g., file path).
content - The sanitized content to wrap.

Outputs:

string - Content wrapped with boundary markers.

Thread Safety: This method is safe for concurrent use.

type ToolSubstitution

type ToolSubstitution struct {
	// Tool is the name of the tool to replace.
	Tool string `json:"tool" yaml:"tool"`

	// When describes the scenario where substitution applies.
	When string `json:"when" yaml:"when"`
}

ToolSubstitution describes when one tool should be used instead of another.

Description:

Captures tool substitution patterns to help the router learn that
specialized tools (like find_callers) should be preferred over
generic tools (like Grep) for specific query types.

Example:

{Tool: "Grep", When: "searching for function call patterns"}

type TypedParams

type TypedParams interface {
	// ToMap converts the typed parameters to the untyped map consumed
	// by Tool.Execute(). This is the ONLY place where typed params
	// become untyped — all upstream code works with concrete types.
	ToMap() map[string]any

	// ToolName returns the name of the tool these parameters belong to.
	// Used for validation and logging.
	ToolName() string
}

TypedParams is the interface for strongly-typed tool parameter structs.

Description:

Each tool's Params struct (e.g., FindCallersParams) implements this
interface to provide type-safe parameter construction with a single
conversion point to the map[string]any required by Tool.Execute().

Thread Safety: Implementations must be safe to call ToMap() concurrently.

type ValidationError

type ValidationError struct {
	// Parameter is the parameter name that failed validation.
	Parameter string `json:"parameter"`

	// Message describes the validation failure.
	Message string `json:"message"`

	// Expected describes what was expected.
	Expected string `json:"expected,omitempty"`

	// Actual describes what was received.
	Actual string `json:"actual,omitempty"`
}

ValidationError represents a parameter validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type WeightedCriticalityOutput

type WeightedCriticalityOutput struct {
	CriticalFunctions []CriticalFunction `json:"critical_functions"`
	QuadrantSummary   map[string]int     `json:"quadrant_summary"`
	Summary           CriticalitySummary `json:"summary"`
}

WeightedCriticalityOutput contains the structured result.

type WhenToUse

type WhenToUse struct {
	// Keywords are query terms that should trigger this tool.
	// Router matches these against the user's query for fast selection.
	// Example: ["callers", "who calls", "upstream", "incoming calls"]
	Keywords []string `json:"keywords" yaml:"keywords"`

	// UseWhen describes scenarios where this tool is the right choice.
	// Example: "User asks who or what calls a specific function"
	UseWhen string `json:"use_when" yaml:"use_when"`

	// AvoidWhen describes scenarios where this tool should NOT be used.
	// Example: "User asks what a function calls (use find_callees instead)"
	AvoidWhen string `json:"avoid_when,omitempty" yaml:"avoid_when,omitempty"`

	// InsteadOf lists tools this tool should replace in specific scenarios.
	// This helps the router learn substitution patterns.
	InsteadOf []ToolSubstitution `json:"instead_of,omitempty" yaml:"instead_of,omitempty"`
}

WhenToUse provides structured guidance for tool selection.

Description:

This is part of the tool contract - every new tool must define this
to enable accurate routing by the tool router. Keywords are matched
against user queries for fast O(1) lookup.

Thread Safety: WhenToUse is immutable after initialization.

CB-31e: This struct addresses the router inefficiency where BestFor was never populated, leading to poor tool selection.

Directories

Path Synopsis
Package file provides file operation tools for the Aleutian Trace CLI.
Package file provides file operation tools for the Aleutian Trace CLI.
Package validate provides validation tools for the CB-56 Multi-Step Change Execution Framework.
Package validate provides validation tools for the CB-56 Multi-Step Change Execution Framework.

Jump to

Keyboard shortcuts

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