Documentation
¶
Overview ¶
Package trace provides the Trace HTTP service for code analysis.
The service exposes endpoints for:
- Initializing and caching code graphs
- Querying symbols and relationships
- Assembling context for LLM prompts
- Seeding library documentation
Index ¶
- Constants
- Variables
- func IsWarmupComplete() bool
- func MarkWarmupComplete()
- func RegisterAgentRoutes(rg *gin.RouterGroup, handlers *AgentHandlers)
- func RegisterAgentRoutesWithMiddleware(rg *gin.RouterGroup, handlers *AgentHandlers, middleware gin.HandlerFunc)
- func RegisterRoutes(rg *gin.RouterGroup, handlers *Handlers)
- func ResetWarmupStatus()
- type AgentAbortRequest
- type AgentContinueRequest
- type AgentHandlers
- func (h *AgentHandlers) HandleAgentAbort(c *gin.Context)
- func (h *AgentHandlers) HandleAgentContinue(c *gin.Context)
- func (h *AgentHandlers) HandleAgentRun(c *gin.Context)
- func (h *AgentHandlers) HandleAgentState(c *gin.Context)
- func (h *AgentHandlers) HandleCRSStream(c *gin.Context)
- func (h *AgentHandlers) HandleDebugCRS(c *gin.Context)
- func (h *AgentHandlers) HandleDebugHistory(c *gin.Context)
- func (h *AgentHandlers) HandleGetCRSExport(c *gin.Context)
- func (h *AgentHandlers) HandleGetReasoningTrace(c *gin.Context)
- type AgentHandlersOption
- type AgentRunRequest
- type AgentRunResponse
- type AgentStateResponse
- type AgenticResponse
- type AnalyzeChangeImpactRequest
- type BuildMinimalContextRequest
- type CRSExportResponse
- type CRSIndexesResponse
- type CachedGraph
- type CachedPlan
- type CallChainRequest
- type CallChainResponse
- type CalleesRequest
- type CalleesResponse
- type CallersRequest
- type CallersResponse
- type CheckBreakingChangesRequest
- type ConstraintEntryResponse
- type ContextRequest
- type ContextResponse
- type DebugCRSCircuitBreaker
- type DebugCRSMetrics
- type DebugCRSResponse
- type DebugCRSSessionDetail
- type DebugCRSSessionSummary
- type DebugCRSTraceStep
- type DebugHistoryEntry
- type DebugHistoryResponse
- type DefaultDependenciesFactory
- type DependenciesFactoryOption
- func WithContextEnabled(enabled bool) DependenciesFactoryOption
- func WithCoordinatorEnabled(enabled bool) DependenciesFactoryOption
- func WithEmbedClient(client *rag.EmbedClient) DependenciesFactoryOption
- func WithEventEmitter(emitter *events.Emitter) DependenciesFactoryOption
- func WithGraphProvider(provider phases.GraphProvider) DependenciesFactoryOption
- func WithIndexingCoordinator(coord *SymbolIndexingCoordinator) DependenciesFactoryOption
- func WithLLMClient(client llm.Client) DependenciesFactoryOption
- func WithNATSJetStream(js nats.JetStreamContext, streamName string) DependenciesFactoryOption
- func WithPersistenceBaseDir(dir string) DependenciesFactoryOption
- func WithResponseGrounder(grounder grounding.Grounder) DependenciesFactoryOption
- func WithSafetyGate(gate safety.Gate) DependenciesFactoryOption
- func WithService(svc *Service) DependenciesFactoryOption
- func WithSessionRestoreEnabled(enabled bool) DependenciesFactoryOption
- func WithToolExecutor(executor *tools.Executor) DependenciesFactoryOption
- func WithToolRegistry(registry *tools.Registry) DependenciesFactoryOption
- func WithToolsEnabled(enabled bool) DependenciesFactoryOption
- func WithWeaviateClient(client *weaviate.Client, dataSpace string) DependenciesFactoryOption
- type DetectPatternsRequest
- type DetectSideEffectsRequest
- type ErrorResponse
- type ExtractConventionsRequest
- type FindCircularDepsRequest
- type FindCodeSmellsRequest
- type FindCommunitiesRequest
- type FindConfigUsageRequest
- type FindCyclesRequest
- type FindDeadCodeRequest
- type FindDuplicationRequest
- type FindEntryPointsRequest
- type FindHotspotsRequest
- type FindImportantRequest
- type FindPathRequest
- type FindSimilarCodeRequest
- type FindTestCoverageRequest
- type GraphStatsResponse
- type Handlers
- func (h *Handlers) HandleAnalyzeChangeImpact(c *gin.Context)
- func (h *Handlers) HandleBuildMinimalContext(c *gin.Context)
- func (h *Handlers) HandleCallers(c *gin.Context)
- func (h *Handlers) HandleCheckBreakingChanges(c *gin.Context)
- func (h *Handlers) HandleContext(c *gin.Context)
- func (h *Handlers) HandleContradictMemory(c *gin.Context)
- func (h *Handlers) HandleDeleteMemory(c *gin.Context)
- func (h *Handlers) HandleDeleteSnapshot(c *gin.Context)
- func (h *Handlers) HandleDetectPatterns(c *gin.Context)
- func (h *Handlers) HandleDetectSideEffects(c *gin.Context)
- func (h *Handlers) HandleDiffSnapshots(c *gin.Context)
- func (h *Handlers) HandleExportGraph(c *gin.Context)
- func (h *Handlers) HandleExtractConventions(c *gin.Context)
- func (h *Handlers) HandleFindCallees(c *gin.Context)
- func (h *Handlers) HandleFindCircularDeps(c *gin.Context)
- func (h *Handlers) HandleFindCodeSmells(c *gin.Context)
- func (h *Handlers) HandleFindCommunities(c *gin.Context)
- func (h *Handlers) HandleFindConfigUsage(c *gin.Context)
- func (h *Handlers) HandleFindCycles(c *gin.Context)
- func (h *Handlers) HandleFindDeadCode(c *gin.Context)
- func (h *Handlers) HandleFindDuplication(c *gin.Context)
- func (h *Handlers) HandleFindEntryPoints(c *gin.Context)
- func (h *Handlers) HandleFindHotspots(c *gin.Context)
- func (h *Handlers) HandleFindImportant(c *gin.Context)
- func (h *Handlers) HandleFindPath(c *gin.Context)
- func (h *Handlers) HandleFindReferences(c *gin.Context)
- func (h *Handlers) HandleFindSimilarCode(c *gin.Context)
- func (h *Handlers) HandleFindTestCoverage(c *gin.Context)
- func (h *Handlers) HandleGetCacheStats(c *gin.Context)
- func (h *Handlers) HandleGetCallChain(c *gin.Context)
- func (h *Handlers) HandleGetGraphStats(c *gin.Context)
- func (h *Handlers) HandleGetTools(c *gin.Context)
- func (h *Handlers) HandleHealth(c *gin.Context)
- func (h *Handlers) HandleImplementations(c *gin.Context)
- func (h *Handlers) HandleIndexingStatus(c *gin.Context)
- func (h *Handlers) HandleInit(c *gin.Context)
- func (h *Handlers) HandleInspectNode(c *gin.Context)
- func (h *Handlers) HandleListMemories(c *gin.Context)
- func (h *Handlers) HandleListSnapshots(c *gin.Context)
- func (h *Handlers) HandleLoadSnapshot(c *gin.Context)
- func (h *Handlers) HandlePlanMultiFileChange(c *gin.Context)
- func (h *Handlers) HandlePreviewChanges(c *gin.Context)
- func (h *Handlers) HandleReady(c *gin.Context)
- func (h *Handlers) HandleRetrieveMemories(c *gin.Context)
- func (h *Handlers) HandleSaveSnapshot(c *gin.Context)
- func (h *Handlers) HandleSeed(c *gin.Context)
- func (h *Handlers) HandleSimulateChange(c *gin.Context)
- func (h *Handlers) HandleStoreMemory(c *gin.Context)
- func (h *Handlers) HandleSuggestRefactor(c *gin.Context)
- func (h *Handlers) HandleSummarizeFile(c *gin.Context)
- func (h *Handlers) HandleSummarizePackage(c *gin.Context)
- func (h *Handlers) HandleSymbol(c *gin.Context)
- func (h *Handlers) HandleTraceDataFlow(c *gin.Context)
- func (h *Handlers) HandleTraceErrorFlow(c *gin.Context)
- func (h *Handlers) HandleValidateChange(c *gin.Context)
- func (h *Handlers) HandleValidateMemory(c *gin.Context)
- func (h *Handlers) HandleValidatePlan(c *gin.Context)
- func (h *Handlers) WithIndexingCoordinator(coord *SymbolIndexingCoordinator) *Handlers
- func (h *Handlers) WithMemory(dataSpace string) *Handlers
- func (h *Handlers) WithNATS(client NATSHealthChecker) *Handlers
- func (h *Handlers) WithWeaviate(client *weaviate.Client) *Handlers
- type HealthResponse
- type HistoryEntryResponse
- type ImplementationsRequest
- type ImplementationsResponse
- type IndexingStatusResponse
- type InitRequest
- type InitResponse
- type InspectEdge
- type InspectNodeMatch
- type InspectNodeRequest
- type InspectNodeResponse
- type LSPDefinitionRequest
- type LSPDefinitionResponse
- type LSPHealthStatus
- type LSPHoverRequest
- type LSPHoverResponse
- type LSPLanguageStatus
- type LSPLocation
- type LSPReferencesRequest
- type LSPReferencesResponse
- type LSPRenameRequest
- type LSPRenameResponse
- type LSPStatusResponse
- type LSPSymbolInfo
- type LSPTextEdit
- type LSPWorkspaceSymbolRequest
- type LSPWorkspaceSymbolResponse
- type ListSnapshotsResponse
- type LoadSnapshotResponse
- type NATSHealthChecker
- type NATSSSEProvider
- type PhaseAdapter
- type PlanMultiFileChangeRequest
- type PreviewChangesRequest
- type ProofEntryResponse
- type ProofUpdateResponse
- type ReadyResponse
- type ReasoningStep
- type ReasoningSummaryResponse
- type ReasoningTraceResponse
- type ReferenceInfo
- type ReferencesRequest
- type ReferencesResponse
- type SaveSnapshotRequest
- type SaveSnapshotResponse
- type SeedRequest
- type SeedResponse
- type Service
- func (s *Service) Close(ctx context.Context) error
- func (s *Service) FindCallees(ctx context.Context, graphID, functionName string, limit int) ([]*SymbolInfo, error)
- func (s *Service) FindCallers(ctx context.Context, graphID, functionName string, limit int) ([]*SymbolInfo, error)
- func (s *Service) FindCommunities(ctx context.Context, graphID string) (*graph.CommunityResult, error)
- func (s *Service) FindCycles(ctx context.Context, graphID string) ([]graph.CyclicDependency, error)
- func (s *Service) FindHotspots(ctx context.Context, graphID string, limit int) ([]graph.HotspotNode, error)
- func (s *Service) FindImplementations(ctx context.Context, graphID, interfaceName string, limit int) ([]*SymbolInfo, error)
- func (s *Service) FindImportant(ctx context.Context, graphID string, limit int) ([]graph.PageRankNode, error)
- func (s *Service) FindPath(ctx context.Context, graphID, from, to string) (*CallChainResponse, error)
- func (s *Service) FindReferences(ctx context.Context, graphID, symbolName string, limit int) ([]ReferenceInfo, error)
- func (s *Service) GetCallChain(ctx context.Context, graphID, from, to string) ([]*SymbolInfo, int, error)
- func (s *Service) GetContext(ctx context.Context, graphID, query string, budget int) (*ContextResponse, error)
- func (s *Service) GetGraph(graphID string) (*CachedGraph, error)
- func (s *Service) GetGraphForPlan(plan interface{}) (*CachedGraph, error)
- func (s *Service) GetPlan(planID string) (interface{}, error)
- func (s *Service) GetSymbol(ctx context.Context, graphID, symbolID string) (*SymbolInfo, error)
- func (s *Service) GraphCount() int
- func (s *Service) Init(ctx context.Context, projectRoot string, languages, excludes []string, ...) (*InitResponse, error)
- func (s *Service) LSPDefinition(ctx context.Context, graphID, filePath string, line, col int) (*LSPDefinitionResponse, error)
- func (s *Service) LSPEnrichmentStatus() (bool, map[string]bool)
- func (s *Service) LSPHover(ctx context.Context, graphID, filePath string, line, col int) (*LSPHoverResponse, error)
- func (s *Service) LSPReferences(ctx context.Context, graphID, filePath string, line, col int, includeDecl bool) (*LSPReferencesResponse, error)
- func (s *Service) LSPRename(ctx context.Context, graphID, filePath string, line, col int, newName string) (*LSPRenameResponse, error)
- func (s *Service) LSPStatus(graphID string) (*LSPStatusResponse, error)
- func (s *Service) LSPWorkspaceSymbol(ctx context.Context, graphID, language, query string) (*LSPWorkspaceSymbolResponse, error)
- func (s *Service) SetLSPEnabled(enabled bool, languages map[string]bool)
- func (s *Service) SetLibraryDocProvider(p cbcontext.LibraryDocProvider)
- func (s *Service) SetSnapshotManager(mgr *graph.SnapshotManager)
- func (s *Service) StorePlan(plan interface{})
- type ServiceAdapter
- func (a *ServiceAdapter) EnrichmentTraceStep(graphID string) *crs.TraceStep
- func (a *ServiceAdapter) InitGraph(ctx context.Context, projectRoot string) (string, error)
- func (a *ServiceAdapter) WithExcludes(excludes []string) *ServiceAdapter
- func (a *ServiceAdapter) WithLanguages(languages []string) *ServiceAdapter
- type ServiceConfig
- type SimulateChangeRequest
- type SnapshotDiffRequest
- type SnapshotDiffResponse
- type SuggestRefactorRequest
- type SummarizeFileRequest
- type SummarizePackageRequest
- type SymbolIndexingCoordinator
- func (c *SymbolIndexingCoordinator) CancelIndexing()
- func (c *SymbolIndexingCoordinator) GetProgress() IndexingStatusResponse
- func (c *SymbolIndexingCoordinator) GetSymbolStore() *rag.SymbolStore
- func (c *SymbolIndexingCoordinator) ResetState()
- func (c *SymbolIndexingCoordinator) TriggerIndexing(graphID string, cached *CachedGraph)
- type SymbolInfo
- type SymbolRequest
- type SymbolResponse
- type ToolDefinition
- type ToolParam
- type ToolRegistry
- type ToolsResponse
- type TraceDataFlowRequest
- type TraceErrorFlowRequest
- type ValidateChangeRequest
- type ValidatePlanRequest
Constants ¶
const ServiceVersion = "0.1.0"
ServiceVersion is the Trace service version.
Variables ¶
var ( // ErrGraphNotInitialized indicates no graph has been built for the project. ErrGraphNotInitialized = errors.New("graph not initialized") // ErrGraphExpired indicates the cached graph has been evicted. ErrGraphExpired = errors.New("graph expired") // ErrRelativePath indicates the project root was a relative path. ErrRelativePath = errors.New("project root must be absolute path") // ErrPathTraversal indicates path contains .. traversal sequences. ErrPathTraversal = errors.New("path contains traversal sequences") // ErrProjectTooLarge indicates the project exceeds size limits. ErrProjectTooLarge = errors.New("project exceeds size limits") // ErrInitInProgress indicates another init is already running for this project. ErrInitInProgress = errors.New("initialization in progress") // ErrInitTimeout indicates the init operation timed out. ErrInitTimeout = errors.New("initialization timed out") )
Sentinel errors for the Trace service.
Functions ¶
func IsWarmupComplete ¶
func IsWarmupComplete() bool
IsWarmupComplete returns true if the main model warmup has finished.
Description:
Checks the global warmup status. This is used by the /ready endpoint to return 503 Service Unavailable until warmup completes.
Thread Safety: This function is safe for concurrent use.
func MarkWarmupComplete ¶
func MarkWarmupComplete()
MarkWarmupComplete marks the warmup as complete.
Description:
Called from cmd/trace/main.go after model warmup completes (success or failure). After this is called, the /ready endpoint will return 200 OK.
Thread Safety: This function is safe for concurrent use.
func RegisterAgentRoutes ¶
func RegisterAgentRoutes(rg *gin.RouterGroup, handlers *AgentHandlers)
RegisterAgentRoutes registers the Trace agent routes with the router.
Description:
Registers all /v1/trace/agent/* endpoints with the given Gin router group. These endpoints provide the agent loop functionality for AI-driven code assistance with multi-step reasoning, tool execution, and clarification.
Inputs:
rg - Gin router group (typically /v1) handlers - The agent handlers instance
Endpoints:
POST /v1/trace/agent/run - Start a new agent session POST /v1/trace/agent/continue - Continue from CLARIFY state POST /v1/trace/agent/abort - Abort an active session GET /v1/trace/agent/:id - Get session state GET /v1/trace/agent/:id/reasoning - Get reasoning trace GET /v1/trace/agent/:id/crs - Get CRS state export
Example:
loop := agent.NewDefaultAgentLoop()
service := trace.NewService(config)
agentHandlers := trace.NewAgentHandlers(loop, service)
v1 := router.Group("/v1")
trace.RegisterAgentRoutes(v1, agentHandlers)
func RegisterAgentRoutesWithMiddleware ¶
func RegisterAgentRoutesWithMiddleware(rg *gin.RouterGroup, handlers *AgentHandlers, middleware gin.HandlerFunc)
RegisterAgentRoutesWithMiddleware registers agent routes with optional middleware.
Description:
Same as RegisterAgentRoutes but allows applying middleware (e.g., warmup guard) to all agent endpoints. If middleware is nil, no additional middleware is applied.
Inputs:
rg - The router group to register routes under. handlers - The agent handlers. middleware - Optional middleware to apply to all agent routes. Can be nil.
Thread Safety: This function is safe for concurrent use.
func RegisterRoutes ¶
func RegisterRoutes(rg *gin.RouterGroup, handlers *Handlers)
RegisterRoutes registers all Trace routes with the router.
Description:
Registers all /v1/trace/* endpoints with the given Gin router group. The router group should already have any required middleware applied.
Inputs:
rg - Gin router group (typically /v1) handlers - The handlers instance
Core Endpoints:
POST /v1/trace/init - Initialize a code graph POST /v1/trace/context - Assemble context for LLM prompt GET /v1/trace/symbol/:id - Get symbol by ID GET /v1/trace/callers - Find function callers GET /v1/trace/implementations - Find interface implementations GET /v1/trace/callees - Find function callees GET /v1/trace/call-chain - Find shortest call chain between two functions GET /v1/trace/references - Find symbol references POST /v1/trace/analytics/hotspots - Find most-connected nodes POST /v1/trace/analytics/cycles - Find cyclic dependencies POST /v1/trace/analytics/important - Find most important nodes (PageRank) POST /v1/trace/analytics/communities - Detect code communities POST /v1/trace/analytics/path - Find shortest path between functions POST /v1/trace/seed - Seed library documentation
Memory Endpoints:
GET /v1/trace/memories - List memories POST /v1/trace/memories - Store a new memory POST /v1/trace/memories/retrieve - Semantic memory retrieval DELETE /v1/trace/memories/:id - Delete a memory POST /v1/trace/memories/:id/validate - Validate a memory POST /v1/trace/memories/:id/contradict - Contradict a memory
Agentic Tool Endpoints (24 tools):
GET /v1/trace/tools - Discover available tools POST /v1/trace/explore/entry_points - Find entry points POST /v1/trace/explore/data_flow - Trace data flow POST /v1/trace/explore/error_flow - Trace error flow POST /v1/trace/explore/config_usage - Find config usages POST /v1/trace/explore/similar_code - Find similar code POST /v1/trace/explore/minimal_context - Build minimal context POST /v1/trace/explore/summarize_file - Summarize a file POST /v1/trace/explore/summarize_package - Summarize a package POST /v1/trace/explore/change_impact - Analyze change impact POST /v1/trace/reason/breaking_changes - Check breaking changes POST /v1/trace/reason/simulate_change - Simulate a change POST /v1/trace/reason/validate_change - Validate code syntax POST /v1/trace/reason/test_coverage - Find test coverage POST /v1/trace/reason/side_effects - Detect side effects POST /v1/trace/reason/suggest_refactor - Suggest refactoring POST /v1/trace/coordinate/plan_changes - Plan multi-file changes POST /v1/trace/coordinate/validate_plan - Validate a change plan POST /v1/trace/coordinate/preview_changes - Preview changes as diffs POST /v1/trace/patterns/detect - Detect design patterns POST /v1/trace/patterns/code_smells - Find code smells POST /v1/trace/patterns/duplication - Find duplicate code POST /v1/trace/patterns/circular_deps - Find circular dependencies POST /v1/trace/patterns/conventions - Extract conventions POST /v1/trace/patterns/dead_code - Find dead code
Metrics Endpoints:
GET /v1/metrics - Prometheus metrics (served via OTel exporter)
Health Endpoints:
GET /v1/trace/health - Health check GET /v1/trace/ready - Readiness check
Example:
service := trace.NewService(trace.DefaultServiceConfig())
handlers := trace.NewHandlers(service)
v1 := router.Group("/v1")
trace.RegisterRoutes(v1, handlers)
func ResetWarmupStatus ¶
func ResetWarmupStatus()
ResetWarmupStatus resets the warmup status to incomplete.
Description:
Used for testing to reset the warmup state between tests.
Thread Safety: This function is safe for concurrent use.
Types ¶
type AgentAbortRequest ¶
type AgentAbortRequest struct {
// SessionID is the session to abort. Required.
SessionID string `json:"session_id" binding:"required"`
}
AgentAbortRequest is the request body for POST /v1/trace/agent/abort.
type AgentContinueRequest ¶
type AgentContinueRequest struct {
// SessionID is the session to continue. Required.
SessionID string `json:"session_id" binding:"required"`
// Clarification is the user's response to the clarification request. Required.
Clarification string `json:"clarification" binding:"required"`
}
AgentContinueRequest is the request body for POST /v1/trace/agent/continue.
type AgentHandlers ¶
type AgentHandlers struct {
// contains filtered or unexported fields
}
AgentHandlers contains the HTTP handlers for the Trace agent.
Thread Safety: AgentHandlers is safe for concurrent use.
func NewAgentHandlers ¶
func NewAgentHandlers(loop agent.AgentLoop, svc *Service, opts ...AgentHandlersOption) *AgentHandlers
NewAgentHandlers creates handlers for the Trace agent.
Description:
Creates HTTP handlers that wrap the AgentLoop interface. The handlers provide REST endpoints for starting, continuing, and aborting agent sessions. Accepts optional functional options to inject shared dependencies (ProviderFactory, MultiModelManager, RoleConfig). When no options are provided, creates its own dependencies for backward compatibility.
Inputs:
loop - The agent loop implementation. Must not be nil. svc - The Trace service for graph initialization. Must not be nil. opts - Optional functional options for dependency injection.
Outputs:
*AgentHandlers - The configured handlers.
Example:
// With injected dependencies (production path):
handlers := trace.NewAgentHandlers(agentLoop, svc,
trace.WithProviderFactory(factory),
trace.WithModelManager(ollamaModelManager),
trace.WithRoleConfig(roleConfig),
)
// Without options (backward compat, tests, error paths):
handlers := trace.NewAgentHandlers(agentLoop, svc)
func (*AgentHandlers) HandleAgentAbort ¶
func (h *AgentHandlers) HandleAgentAbort(c *gin.Context)
HandleAgentAbort handles POST /v1/trace/agent/abort.
Description:
Aborts an active agent session. The session will transition to the ERROR state and any in-progress operations will be cancelled.
Request Body:
AgentAbortRequest
Response:
200 OK: Success message 404 Not Found: Session not found 500 Internal Server Error: Processing error
Thread Safety: This method is safe for concurrent use.
func (*AgentHandlers) HandleAgentContinue ¶
func (h *AgentHandlers) HandleAgentContinue(c *gin.Context)
HandleAgentContinue handles POST /v1/trace/agent/continue.
Description:
Continues an existing agent session that is waiting for clarification. The session must be in the CLARIFY state to accept continuation.
Request Body:
AgentContinueRequest
Response:
200 OK: AgentRunResponse 400 Bad Request: Session not in CLARIFY state 404 Not Found: Session not found 500 Internal Server Error: Processing error
Thread Safety: This method is safe for concurrent use.
func (*AgentHandlers) HandleAgentRun ¶
func (h *AgentHandlers) HandleAgentRun(c *gin.Context)
HandleAgentRun handles POST /v1/trace/agent/run.
Description:
Starts a new agent session with the given query. The session initializes the code graph (if not already initialized), assembles context, and executes the agent loop until completion or clarification.
Request Body:
AgentRunRequest
Response:
200 OK: AgentRunResponse (session completed or needs clarification) 400 Bad Request: Validation error 409 Conflict: Session already in progress 500 Internal Server Error: Processing error
Thread Safety: This method is safe for concurrent use.
func (*AgentHandlers) HandleAgentState ¶
func (h *AgentHandlers) HandleAgentState(c *gin.Context)
HandleAgentState handles GET /v1/trace/agent/:id.
Description:
Retrieves the current state of an agent session including metrics, history, and any pending clarification prompts.
Path Parameters:
id: Session ID (required)
Response:
200 OK: AgentStateResponse 404 Not Found: Session not found
Thread Safety: This method is safe for concurrent use.
func (*AgentHandlers) HandleCRSStream ¶
func (h *AgentHandlers) HandleCRSStream(c *gin.Context)
HandleCRSStream handles GET /v1/trace/agent/:id/crs/stream.
Description:
Server-Sent Events endpoint for live CRS delta streaming. Subscribes to NATS JetStream for new deltas on the specified session and streams them to the client as SSE events. Includes heartbeats every 15 seconds.
Inputs:
- id (path param): The agent session ID.
Outputs:
- SSE stream with "delta" events and periodic "heartbeat" events.
- 503 if NATS is unavailable.
- 404 if session not found.
Thread Safety: Safe for concurrent use.
func (*AgentHandlers) HandleDebugCRS ¶
func (h *AgentHandlers) HandleDebugCRS(c *gin.Context)
HandleDebugCRS handles GET /v1/trace/agent/debug/crs.
Description:
Returns CRS debug information for all sessions or a specific session. Used by integration tests to verify CRS state and circuit breaker behavior. GR-Phase1 Issue 5: Debug endpoint for CRS observability.
Query Parameters:
session_id: Optional session ID for detailed view
Response:
200 OK: DebugCRSResponse (summary or detail depending on session_id) 404 Not Found: Session not found (when session_id provided)
Thread Safety: This method is safe for concurrent use.
func (*AgentHandlers) HandleDebugHistory ¶
func (h *AgentHandlers) HandleDebugHistory(c *gin.Context)
HandleDebugHistory handles GET /v1/trace/agent/debug/history.
Description:
Returns query history across all sessions or for a specific session. Used by integration tests to verify reasoning history and query flow. GR-Phase1 Issue 5b: Debug endpoint for query history.
Query Parameters:
session_id: Optional session ID for filtering to one session limit: Optional max entries to return (default 100)
Response:
200 OK: DebugHistoryResponse 404 Not Found: Session not found (when session_id provided)
Thread Safety: This method is safe for concurrent use.
func (*AgentHandlers) HandleGetCRSExport ¶
func (h *AgentHandlers) HandleGetCRSExport(c *gin.Context)
HandleGetCRSExport handles GET /v1/trace/agent/:id/crs.
Description:
Retrieves the full CRS (Code Reasoning State) export for a session. This includes all six indexes and summary metrics for debugging and analysis of the reasoning process.
Path Parameters:
id: Session ID (required)
Response:
200 OK: CRSExportResponse 404 Not Found: Session not found 204 No Content: Session exists but CRS not enabled
Thread Safety: This method is safe for concurrent use.
func (*AgentHandlers) HandleGetReasoningTrace ¶
func (h *AgentHandlers) HandleGetReasoningTrace(c *gin.Context)
HandleGetReasoningTrace handles GET /v1/trace/agent/:id/reasoning.
Description:
Retrieves the step-by-step reasoning trace for a session. The trace shows what actions were taken, what was found, and how the CRS was updated during reasoning.
Path Parameters:
id: Session ID (required)
Response:
200 OK: ReasoningTraceResponse 404 Not Found: Session not found 204 No Content: Session exists but trace recording not enabled
Thread Safety: This method is safe for concurrent use.
type AgentHandlersOption ¶
type AgentHandlersOption func(*AgentHandlers)
AgentHandlersOption is a functional option for NewAgentHandlers.
func WithModelManager ¶
func WithModelManager(m *llm.MultiModelManager) AgentHandlersOption
WithModelManager injects a shared MultiModelManager into AgentHandlers.
Description:
When provided, NewAgentHandlers uses this manager instead of creating its own. This prevents the double-MMM bug where two independent managers track VRAM state independently.
func WithNATSSSE ¶
func WithNATSSSE(client NATSSSEProvider) AgentHandlersOption
WithNATSSSE injects a NATS client for CRS SSE streaming into AgentHandlers. CRS-27: Enables the GET /:id/crs/stream SSE endpoint.
func WithProviderFactory ¶
func WithProviderFactory(f *providers.ProviderFactory) AgentHandlersOption
WithProviderFactory injects a shared ProviderFactory into AgentHandlers.
Description:
When provided, NewAgentHandlers uses this factory instead of creating its own. This ensures the same ProviderFactory (and thus the same MultiModelManager) is used throughout the application.
func WithRoleConfig ¶
func WithRoleConfig(rc *providers.RoleConfig) AgentHandlersOption
WithRoleConfig injects the startup-loaded RoleConfig into AgentHandlers.
Description:
When provided, initializeToolRouter uses this config (with per-session overrides via MergeSessionOverrides) instead of calling LoadRoleConfig again. This prevents the double-LoadRoleConfig bug.
type AgentRunRequest ¶
type AgentRunRequest struct {
// ProjectRoot is the absolute path to the project root directory.
// Required.
ProjectRoot string `json:"project_root" binding:"required"`
// Query is the user's question or task description. Required.
Query string `json:"query" binding:"required"`
// Config is optional session configuration overrides.
Config *agent.SessionConfig `json:"config,omitempty"`
}
AgentRunRequest is the request body for POST /v1/trace/agent/run.
type AgentRunResponse ¶
type AgentRunResponse struct {
// SessionID is the unique identifier for this session.
SessionID string `json:"session_id"`
// State is the current session state (IDLE, INIT, PLAN, EXECUTE, etc.).
State string `json:"state"`
// StepsTaken is the number of agent steps completed.
StepsTaken int `json:"steps_taken"`
// TokensUsed is the total tokens consumed.
TokensUsed int `json:"tokens_used"`
// Response is the agent's final response (if complete).
Response string `json:"response,omitempty"`
// NeedsClarify contains clarification details if state is CLARIFY.
NeedsClarify *agent.ClarifyRequest `json:"needs_clarify,omitempty"`
// Error is the error message if state is ERROR.
Error string `json:"error,omitempty"`
// DegradedMode indicates if the session is running with limited capabilities.
DegradedMode bool `json:"degraded_mode"`
}
AgentRunResponse is the response for POST /v1/trace/agent/run.
type AgentStateResponse ¶
type AgentStateResponse struct {
// SessionID is the unique session identifier.
SessionID string `json:"session_id"`
// ProjectRoot is the project root path.
ProjectRoot string `json:"project_root"`
// GraphID is the code graph ID (if initialized).
GraphID string `json:"graph_id,omitempty"`
// State is the current session state.
State string `json:"state"`
// StepCount is the number of steps completed.
StepCount int `json:"step_count"`
// TokensUsed is the total tokens consumed.
TokensUsed int `json:"tokens_used"`
// CreatedAt is the Unix timestamp of session creation.
CreatedAt int64 `json:"created_at"`
// LastActiveAt is the Unix timestamp of last activity.
LastActiveAt int64 `json:"last_active_at"`
// DegradedMode indicates if running with limited capabilities.
DegradedMode bool `json:"degraded_mode"`
}
AgentStateResponse is the response for GET /v1/trace/agent/:id.
type AgenticResponse ¶
type AgenticResponse struct {
// Result contains the actual response data.
Result interface{} `json:"result"`
// LatencyMs is the time taken to process the request in milliseconds.
LatencyMs int64 `json:"latency_ms"`
// Warnings contains non-fatal warnings if any.
Warnings []string `json:"warnings,omitempty"`
// Limitations documents what couldn't be analyzed.
Limitations []string `json:"limitations,omitempty"`
}
AgenticResponse wraps all agentic tool responses with latency tracking.
type AnalyzeChangeImpactRequest ¶
type AnalyzeChangeImpactRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
ChangeType string `json:"change_type"`
}
AnalyzeChangeImpactRequest is the request for POST /v1/trace/explore/change_impact.
type BuildMinimalContextRequest ¶
type BuildMinimalContextRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
TokenBudget int `json:"token_budget"`
IncludeCallees bool `json:"include_callees"`
}
BuildMinimalContextRequest is the request for POST /v1/trace/explore/minimal_context.
type CRSExportResponse ¶
type CRSExportResponse struct {
// SessionID is the unique session identifier.
SessionID string `json:"session_id"`
// Generation is the CRS snapshot generation number.
Generation int64 `json:"generation"`
// Timestamp is when this snapshot was taken (RFC3339).
Timestamp string `json:"timestamp"`
// Indexes contains exports of all six CRS indexes.
Indexes CRSIndexesResponse `json:"indexes"`
// Summary provides high-level reasoning metrics.
Summary ReasoningSummaryResponse `json:"summary"`
}
CRSExportResponse is the response for GET /v1/trace/agent/:id/crs.
type CRSIndexesResponse ¶
type CRSIndexesResponse struct {
// Proof contains proof status entries.
Proof []ProofEntryResponse `json:"proof"`
// Constraints contains constraint entries.
Constraints []ConstraintEntryResponse `json:"constraints"`
// SimilarityCount is the number of similarity pairs stored.
// Full similarity matrix export is deferred for performance.
SimilarityCount int `json:"similarity_count"`
// DependencyCount is the number of dependency edges.
// Full dependency graph export is deferred for performance.
DependencyCount int `json:"dependency_count"`
// History contains recent exploration history entries.
History []HistoryEntryResponse `json:"history"`
// StreamingCardinality is the estimated unique item count in streaming index.
StreamingCardinality uint64 `json:"streaming_cardinality"`
// StreamingBytes is the approximate memory usage of streaming index.
StreamingBytes int `json:"streaming_bytes"`
}
CRSIndexesResponse contains exports of all six CRS indexes.
Note: Some indexes only provide aggregate counts for performance reasons. Full data export for similarity and dependency indexes is deferred.
type CachedGraph ¶
type CachedGraph struct {
// Graph is the code graph.
Graph *graph.Graph
// Index is the symbol index.
Index *index.SymbolIndex
// Assembler is the context assembler.
Assembler *cbcontext.Assembler
// Adapter is the CRS-enabled graph adapter with query caching.
// Created lazily on first use. Provides cache statistics via QueryCacheStats().
Adapter *graph.CRSGraphAdapter
// BuiltAtMilli is when the graph was built.
BuiltAtMilli int64
// ProjectRoot is the project root path.
ProjectRoot string
// ExpiresAtMilli is when the graph expires (0 = never).
ExpiresAtMilli int64
// EnrichmentStats contains LSP enrichment statistics from the build
// that produced this graph. Zero-valued if enrichment was not configured.
// GR-76: Used by CRS to emit a TraceStep on session start.
EnrichmentStats graph.EnrichmentStats
}
CachedGraph holds a graph and its associated data.
type CachedPlan ¶
type CachedPlan struct {
// GraphID is the graph this plan was created for.
GraphID string
// Plan is the change plan.
Plan interface{} // *coordinate.ChangePlan
// CreatedAt is when the plan was created.
CreatedAt time.Time
}
CachedPlan holds a change plan and its associated graph ID.
type CallChainRequest ¶
type CallChainRequest struct {
// GraphID is the graph to query. Required.
GraphID string `form:"graph_id" binding:"required"`
// From is the source function name. Required.
From string `form:"from" binding:"required"`
// To is the target function name. Required.
To string `form:"to" binding:"required"`
}
CallChainRequest is the query params for GET /v1/trace/call-chain.
type CallChainResponse ¶
type CallChainResponse struct {
// From is the source function name.
From string `json:"from"`
// To is the target function name.
To string `json:"to"`
// Path is the list of symbols in the shortest path.
Path []*SymbolInfo `json:"path"`
// Length is the number of hops in the path (-1 if no path found).
Length int `json:"length"`
}
CallChainResponse is the response for GET /v1/trace/call-chain.
type CalleesRequest ¶
type CalleesRequest struct {
// GraphID is the graph to query. Required.
GraphID string `form:"graph_id" binding:"required"`
// Function is the function name to find callees for. Required.
Function string `form:"function" binding:"required"`
// Limit is the maximum number of results. Default: 50.
Limit int `form:"limit"`
}
CalleesRequest is the query params for GET /v1/trace/callees.
type CalleesResponse ¶
type CalleesResponse struct {
// Function is the function name that was searched.
Function string `json:"function"`
// Callees is the list of symbols that the function calls.
Callees []*SymbolInfo `json:"callees"`
}
CalleesResponse is the response for GET /v1/trace/callees.
type CallersRequest ¶
type CallersRequest struct {
// GraphID is the graph to query. Required.
GraphID string `form:"graph_id" binding:"required"`
// Function is the function name to find callers for. Required.
Function string `form:"function" binding:"required"`
// Limit is the maximum number of results. Default: 50.
Limit int `form:"limit"`
}
CallersRequest is the query params for GET /v1/trace/callers.
type CallersResponse ¶
type CallersResponse struct {
// Function is the function name that was searched.
Function string `json:"function"`
// Callers is the list of symbols that call the function.
Callers []*SymbolInfo `json:"callers"`
}
CallersResponse is the response for GET /v1/trace/callers.
type CheckBreakingChangesRequest ¶
type CheckBreakingChangesRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
ProposedSignature string `json:"proposed_signature" binding:"required"`
}
CheckBreakingChangesRequest is the request for POST /v1/trace/reason/breaking_changes.
type ConstraintEntryResponse ¶
type ConstraintEntryResponse struct {
// ID is the constraint identifier.
ID string `json:"id"`
// Type is the constraint type.
Type string `json:"type"`
// Nodes are the affected nodes.
Nodes []string `json:"nodes"`
// Strength is the constraint weight (0.0-1.0).
Strength float64 `json:"strength"`
}
ConstraintEntryResponse represents a constraint in API responses.
type ContextRequest ¶
type ContextRequest struct {
// GraphID is the graph to query. Required.
GraphID string `json:"graph_id" binding:"required"`
// Query is the search query or task description. Required.
Query string `json:"query" binding:"required"`
// TokenBudget is the maximum tokens to use. Default: 8000.
TokenBudget int `json:"token_budget"`
// IncludeLibraryDocs enables library documentation lookup. Default: true.
IncludeLibraryDocs *bool `json:"include_library_docs"`
}
ContextRequest is the request body for POST /v1/trace/context.
type ContextResponse ¶
type ContextResponse struct {
// Context is the formatted markdown context for LLM consumption.
Context string `json:"context"`
// TokensUsed is the estimated number of tokens used.
TokensUsed int `json:"tokens_used"`
// SymbolsIncluded lists the IDs of symbols included in context.
SymbolsIncluded []string `json:"symbols_included"`
// LibraryDocsIncluded lists the IDs of library docs included.
LibraryDocsIncluded []string `json:"library_docs_included"`
// Suggestions provides "also consider" hints.
Suggestions []string `json:"suggestions"`
}
ContextResponse is the response for POST /v1/trace/context.
type DebugCRSCircuitBreaker ¶
type DebugCRSCircuitBreaker struct {
// Active indicates if the circuit breaker has fired.
Active bool `json:"active"`
// Tool is the tool that triggered the circuit breaker.
Tool string `json:"tool,omitempty"`
// Count is the call count when circuit breaker fired.
Count int `json:"count,omitempty"`
// Threshold is the configured threshold.
Threshold int `json:"threshold"`
}
DebugCRSCircuitBreaker contains circuit breaker state.
type DebugCRSMetrics ¶
type DebugCRSMetrics struct {
// ToolCalls is the total number of tool calls.
ToolCalls int `json:"tool_calls"`
// TokensUsed is the estimated token count.
TokensUsed int `json:"tokens_used"`
// Steps is the number of agent steps.
Steps int `json:"steps"`
}
DebugCRSMetrics contains session metrics for debug output.
type DebugCRSResponse ¶
type DebugCRSResponse struct {
// ActiveSessions is the count of sessions with CRS state.
ActiveSessions int `json:"active_sessions"`
// TotalTraceSteps is the total trace steps across all sessions.
TotalTraceSteps int `json:"total_trace_steps"`
// CircuitBreakersActive is the count of sessions with active circuit breakers.
CircuitBreakersActive int `json:"circuit_breakers_active"`
// Sessions is a summary of each session (only in summary mode).
Sessions []DebugCRSSessionSummary `json:"sessions,omitempty"`
// Session is the detailed session state (only when session_id provided).
Session *DebugCRSSessionDetail `json:"session,omitempty"`
}
DebugCRSResponse is the response for GET /v1/trace/debug/crs.
Description:
Returns CRS (Code Reasoning State) debug information. When session_id is provided, returns detailed state for that session. Otherwise returns a summary of all active sessions.
type DebugCRSSessionDetail ¶
type DebugCRSSessionDetail struct {
// SessionID is the session identifier.
SessionID string `json:"session_id"`
// State is the current agent state.
State string `json:"state"`
// TraceSteps is the list of recorded trace steps.
TraceSteps []DebugCRSTraceStep `json:"trace_steps"`
// CircuitBreaker contains circuit breaker state.
CircuitBreaker *DebugCRSCircuitBreaker `json:"circuit_breaker,omitempty"`
// Metrics contains session metrics.
Metrics DebugCRSMetrics `json:"metrics"`
// ToolCounts maps tool name to call count.
ToolCounts map[string]int `json:"tool_counts"`
}
DebugCRSSessionDetail is the detailed CRS state for a single session.
type DebugCRSSessionSummary ¶
type DebugCRSSessionSummary struct {
// ID is the session identifier.
ID string `json:"id"`
// State is the current agent state (e.g., "EXECUTE", "COMPLETE").
State string `json:"state"`
// TraceSteps is the number of trace steps recorded.
TraceSteps int `json:"trace_steps"`
// CircuitBreakerActive indicates if circuit breaker has fired.
CircuitBreakerActive bool `json:"circuit_breaker_active"`
// CreatedAtMilli is the session creation time (Unix milliseconds).
CreatedAtMilli int64 `json:"created_at_milli"`
}
DebugCRSSessionSummary is a brief summary of a session's CRS state.
type DebugCRSTraceStep ¶
type DebugCRSTraceStep struct {
// Action is the step action (e.g., "tool_call", "semantic_correction").
Action string `json:"action"`
// Tool is the tool name if applicable.
Tool string `json:"tool,omitempty"`
// Target is the target of the action.
Target string `json:"target,omitempty"`
// DurationMs is the duration in milliseconds.
DurationMs int64 `json:"duration_ms"`
// Error is the error message if the step failed.
Error string `json:"error,omitempty"`
// Metadata contains additional step metadata.
Metadata map[string]string `json:"metadata,omitempty"`
}
DebugCRSTraceStep is a trace step for debug output.
type DebugHistoryEntry ¶
type DebugHistoryEntry struct {
// SessionID is the session that processed this query.
SessionID string `json:"session_id"`
// Timestamp is when the query was received (Unix milliseconds).
Timestamp int64 `json:"timestamp"`
// Query is the user's question or task.
Query string `json:"query"`
// State is the final state of the query (e.g., "COMPLETE", "ERROR").
State string `json:"state"`
// ToolsUsed is the list of tools invoked for this query.
ToolsUsed []string `json:"tools_used"`
// DurationMs is how long the query took to process.
DurationMs int64 `json:"duration_ms"`
}
DebugHistoryEntry represents a single query in the history.
type DebugHistoryResponse ¶
type DebugHistoryResponse struct {
// Count is the total number of history entries returned.
Count int `json:"count"`
// Sessions is the list of unique session IDs with history.
Sessions []string `json:"sessions"`
// History is the list of query history entries.
History []DebugHistoryEntry `json:"history"`
// Limit is the maximum entries that can be returned.
Limit int `json:"limit"`
}
DebugHistoryResponse is the response for GET /v1/trace/agent/debug/history.
Description:
Returns query history across all sessions or for a specific session. Used by integration tests to verify reasoning history and query flow.
type DefaultDependenciesFactory ¶
type DefaultDependenciesFactory struct {
// contains filtered or unexported fields
}
DefaultDependenciesFactory creates phase Dependencies for agent sessions.
Description:
DefaultDependenciesFactory holds shared components (LLM client, tool registry, etc.) and creates per-session Dependencies structs when Create is called. When enableContext or enableTools are set, it creates ContextManager and ToolRegistry dynamically using the graph from the Service.
Thread Safety: DefaultDependenciesFactory is safe for concurrent use.
func NewDependenciesFactory ¶
func NewDependenciesFactory(opts ...DependenciesFactoryOption) *DefaultDependenciesFactory
NewDependenciesFactory creates a new dependencies factory.
Description:
Creates a factory with the provided options. Use the With* functions to configure the shared components.
Inputs:
opts - Configuration options.
Outputs:
*DefaultDependenciesFactory - The configured factory.
func (*DefaultDependenciesFactory) Create ¶
Create implements agent.DependenciesFactory.
Description:
Creates a Dependencies struct for the given session and query. Uses the pre-configured shared components. Retrieves existing context from the session if available (for cross-phase context sharing). When enableContext or enableTools are set, creates ContextManager and ToolRegistry using the graph from the Service.
Inputs:
session - The current session. query - The user's query.
Outputs:
any - The Dependencies struct (as *phases.Dependencies). error - Non-nil if creation failed.
Thread Safety: This method is safe for concurrent use.
type DependenciesFactoryOption ¶
type DependenciesFactoryOption func(*DefaultDependenciesFactory)
DependenciesFactoryOption configures a DefaultDependenciesFactory.
func WithContextEnabled ¶
func WithContextEnabled(enabled bool) DependenciesFactoryOption
WithContextEnabled enables ContextManager creation.
func WithCoordinatorEnabled ¶
func WithCoordinatorEnabled(enabled bool) DependenciesFactoryOption
WithCoordinatorEnabled enables MCTS activity coordination.
Description:
When enabled, Creates a Coordinator for each session that orchestrates MCTS activities (Search, Learning, Constraint, Planning, Awareness, Similarity, Streaming, Memory) in response to agent events.
Inputs:
enabled - Whether to enable the coordinator.
Outputs:
DependenciesFactoryOption - The configuration function.
func WithEmbedClient ¶
func WithEmbedClient(client *rag.EmbedClient) DependenciesFactoryOption
WithEmbedClient sets the embedding client for pre-computing vectors.
Description:
CRS-26i: When set, SymbolStore pre-computes vectors via the orchestrator's /v1/embed endpoint before inserting into Weaviate. SemanticResolver uses the same client to embed query tokens for nearVector search.
Inputs:
client - Embedding client. May be nil (graceful degradation — no vectors).
func WithEventEmitter ¶
func WithEventEmitter(emitter *events.Emitter) DependenciesFactoryOption
WithEventEmitter sets the event emitter.
func WithGraphProvider ¶
func WithGraphProvider(provider phases.GraphProvider) DependenciesFactoryOption
WithGraphProvider sets the graph provider.
func WithIndexingCoordinator ¶
func WithIndexingCoordinator(coord *SymbolIndexingCoordinator) DependenciesFactoryOption
WithIndexingCoordinator sets the shared symbol indexing coordinator.
Description:
CRS-26l: When set, the factory delegates symbol indexing to the coordinator instead of running an inline goroutine. This enables eager indexing at graph init time via HandleInit.
Inputs:
coord - The indexing coordinator. May be nil (falls back to inline goroutine).
func WithLLMClient ¶
func WithLLMClient(client llm.Client) DependenciesFactoryOption
WithLLMClient sets the LLM client.
func WithNATSJetStream ¶
func WithNATSJetStream(js nats.JetStreamContext, streamName string) DependenciesFactoryOption
WithNATSJetStream sets the NATS JetStream context for CRS delta persistence.
Description:
CRS-27: When set, sessions use NATS JetStream for CRS delta persistence instead of embedded BadgerDB. Falls back to in-memory BadgerJournal when NATS is unavailable at session creation time.
Inputs:
js - JetStream context from a connected NATS client. streamName - JetStream stream name (e.g., "CRS_DELTAS").
Thread Safety: Safe for concurrent use.
func WithPersistenceBaseDir ¶
func WithPersistenceBaseDir(dir string) DependenciesFactoryOption
WithPersistenceBaseDir sets the base directory for CRS persistence.
Description:
Sets the directory where CRS checkpoints and journals are stored. If not set, defaults to ~/.aleutian/crs.
Inputs:
dir - The base directory path.
Outputs:
DependenciesFactoryOption - The configuration function.
GR-36: Added for session restore integration.
func WithResponseGrounder ¶
func WithResponseGrounder(grounder grounding.Grounder) DependenciesFactoryOption
WithResponseGrounder sets the response grounding validator.
func WithSafetyGate ¶
func WithSafetyGate(gate safety.Gate) DependenciesFactoryOption
WithSafetyGate sets the safety gate.
func WithService ¶
func WithService(svc *Service) DependenciesFactoryOption
WithService sets the service for accessing cached graphs.
func WithSessionRestoreEnabled ¶
func WithSessionRestoreEnabled(enabled bool) DependenciesFactoryOption
WithSessionRestoreEnabled enables CRS session restore from checkpoints.
Description:
When enabled, attempts to restore CRS state from a previous session checkpoint. This preserves learned clauses, proof numbers, and other CRS state across agent sessions.
Inputs:
enabled - Whether to enable session restore.
Outputs:
DependenciesFactoryOption - The configuration function.
GR-36: Added for session restore integration.
func WithToolExecutor ¶
func WithToolExecutor(executor *tools.Executor) DependenciesFactoryOption
WithToolExecutor sets the tool executor.
func WithToolRegistry ¶
func WithToolRegistry(registry *tools.Registry) DependenciesFactoryOption
WithToolRegistry sets the tool registry.
func WithToolsEnabled ¶
func WithToolsEnabled(enabled bool) DependenciesFactoryOption
WithToolsEnabled enables ToolRegistry creation.
func WithWeaviateClient ¶
func WithWeaviateClient(client *weaviate.Client, dataSpace string) DependenciesFactoryOption
WithWeaviateClient sets the Weaviate client for semantic RAG resolution.
Description:
CRS-25: When set, the factory creates a CombinedResolver (structural + semantic) instead of a StructuralResolver-only. The dataSpace is used for project isolation.
Inputs:
client - Weaviate client. May be nil (degrades to structural-only). dataSpace - Project isolation key.
type DetectPatternsRequest ¶
type DetectPatternsRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Scope string `json:"scope"`
Patterns []string `json:"patterns"`
MinConfidence float64 `json:"min_confidence"`
}
DetectPatternsRequest is the request for POST /v1/trace/patterns/detect.
type DetectSideEffectsRequest ¶
type DetectSideEffectsRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
Transitive bool `json:"transitive"`
}
DetectSideEffectsRequest is the request for POST /v1/trace/reason/side_effects.
type ErrorResponse ¶
type ErrorResponse struct {
// Error is the error message.
Error string `json:"error"`
// Code is the error code (optional).
Code string `json:"code,omitempty"`
// Details provides additional error context (optional).
Details string `json:"details,omitempty"`
}
ErrorResponse is the standard error response format.
type ExtractConventionsRequest ¶
type ExtractConventionsRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Scope string `json:"scope"`
Types []string `json:"types"`
IncludeTests bool `json:"include_tests"`
}
ExtractConventionsRequest is the request for POST /v1/trace/patterns/conventions.
type FindCircularDepsRequest ¶
type FindCircularDepsRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Scope string `json:"scope"`
Level string `json:"level"`
}
FindCircularDepsRequest is the request for POST /v1/trace/patterns/circular_deps.
type FindCodeSmellsRequest ¶
type FindCodeSmellsRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Scope string `json:"scope"`
MinSeverity string `json:"min_severity"`
ContextLines int `json:"context_lines"`
IncludeTests bool `json:"include_tests"`
}
FindCodeSmellsRequest is the request for POST /v1/trace/patterns/code_smells.
type FindCommunitiesRequest ¶
type FindCommunitiesRequest struct {
// GraphID is the graph to query. Required.
GraphID string `json:"graph_id" binding:"required"`
}
FindCommunitiesRequest is the request body for POST /v1/trace/analytics/communities.
type FindConfigUsageRequest ¶
type FindConfigUsageRequest struct {
GraphID string `json:"graph_id" binding:"required"`
ConfigKey string `json:"config_key" binding:"required"`
IncludeDefaults bool `json:"include_defaults"`
}
FindConfigUsageRequest is the request for POST /v1/trace/explore/config_usage.
type FindCyclesRequest ¶
type FindCyclesRequest struct {
// GraphID is the graph to query. Required.
GraphID string `json:"graph_id" binding:"required"`
}
FindCyclesRequest is the request body for POST /v1/trace/analytics/cycles.
type FindDeadCodeRequest ¶
type FindDeadCodeRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Scope string `json:"scope"`
IncludeExported bool `json:"include_exported"`
}
FindDeadCodeRequest is the request for POST /v1/trace/patterns/dead_code.
type FindDuplicationRequest ¶
type FindDuplicationRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Scope string `json:"scope"`
MinSimilarity float64 `json:"min_similarity"`
Type string `json:"type"`
IncludeTests bool `json:"include_tests"`
}
FindDuplicationRequest is the request for POST /v1/trace/patterns/duplication.
type FindEntryPointsRequest ¶
type FindEntryPointsRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Type string `json:"type"`
Package string `json:"package"`
Limit int `json:"limit"`
IncludeTests bool `json:"include_tests"`
}
FindEntryPointsRequest is the request for POST /v1/trace/explore/entry_points.
type FindHotspotsRequest ¶
type FindHotspotsRequest struct {
// GraphID is the graph to query. Required.
GraphID string `json:"graph_id" binding:"required"`
// Limit is the maximum number of results. Default: 10.
Limit int `json:"limit"`
}
FindHotspotsRequest is the request body for POST /v1/trace/analytics/hotspots.
type FindImportantRequest ¶
type FindImportantRequest struct {
// GraphID is the graph to query. Required.
GraphID string `json:"graph_id" binding:"required"`
// Limit is the maximum number of results. Default: 10.
Limit int `json:"limit"`
}
FindImportantRequest is the request body for POST /v1/trace/analytics/important.
type FindPathRequest ¶
type FindPathRequest struct {
// GraphID is the graph to query. Required.
GraphID string `json:"graph_id" binding:"required"`
// From is the source function name. Required.
From string `json:"from" binding:"required"`
// To is the target function name. Required.
To string `json:"to" binding:"required"`
}
FindPathRequest is the request body for POST /v1/trace/analytics/path.
type FindSimilarCodeRequest ¶
type FindSimilarCodeRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
MinSimilarity float64 `json:"min_similarity"`
Limit int `json:"limit"`
}
FindSimilarCodeRequest is the request for POST /v1/trace/explore/similar_code.
type FindTestCoverageRequest ¶
type FindTestCoverageRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
IncludeIndirect bool `json:"include_indirect"`
}
FindTestCoverageRequest is the request for POST /v1/trace/reason/test_coverage.
type GraphStatsResponse ¶
type GraphStatsResponse struct {
// GraphID is the unique identifier for this graph.
GraphID string `json:"graph_id"`
// ProjectRoot is the absolute path to the project root.
ProjectRoot string `json:"project_root"`
// State is the graph state ("building" or "readonly").
State string `json:"state"`
// 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"`
// MaxNodes is the configured maximum node capacity.
MaxNodes int `json:"max_nodes"`
// MaxEdges is the configured maximum edge capacity.
MaxEdges int `json:"max_edges"`
// BuiltAtMilli is the Unix timestamp in milliseconds when graph was frozen.
BuiltAtMilli int64 `json:"built_at_milli"`
// EdgesByType maps edge type name to count.
EdgesByType map[string]int `json:"edges_by_type"`
// NodesByKind maps symbol kind name to count.
NodesByKind map[string]int `json:"nodes_by_kind"`
}
GraphStatsResponse is the response for GET /v1/trace/debug/graph/stats.
Description:
Returns detailed statistics about a cached graph including node/edge counts broken down by type and kind. Used for debugging and integration tests.
type Handlers ¶
type Handlers struct {
// contains filtered or unexported fields
}
Handlers contains the HTTP handlers for Trace.
func NewHandlers ¶
NewHandlers creates handlers for the given service.
func (*Handlers) HandleAnalyzeChangeImpact ¶
HandleAnalyzeChangeImpact analyzes the blast radius of a change.
func (*Handlers) HandleBuildMinimalContext ¶
HandleBuildMinimalContext builds token-efficient context for a symbol.
func (*Handlers) HandleCallers ¶
HandleCallers handles GET /v1/trace/callers.
Description:
Finds all functions that call the given function.
Query Parameters:
graph_id: ID of the graph to query (required) function: Name of the function to find callers for (required) limit: Maximum number of results (optional, default 50)
Response:
200 OK: CallersResponse (may be empty array) 400 Bad Request: Missing parameters or graph not initialized
func (*Handlers) HandleCheckBreakingChanges ¶
HandleCheckBreakingChanges checks if a proposed change would break callers.
func (*Handlers) HandleContext ¶
HandleContext handles POST /v1/trace/context.
Description:
Assembles relevant context for an LLM prompt using the code graph.
Request Body:
ContextRequest
Response:
200 OK: ContextResponse 400 Bad Request: Validation error or graph not initialized 500 Internal Server Error: Processing error
func (*Handlers) HandleContradictMemory ¶
HandleContradictMemory handles POST /v1/trace/memories/:id/contradict.
Description:
Marks a memory as contradicted, reducing its confidence or deleting it.
Path Parameters:
id: Memory ID (required)
Request Body:
{ "reason": "Why this memory is contradicted" }
Response:
200 OK: Success message 404 Not Found: Memory not found 503 Service Unavailable: Memory system not configured
func (*Handlers) HandleDeleteMemory ¶
HandleDeleteMemory handles DELETE /v1/trace/memories/:id.
Description:
Permanently deletes a memory by its ID.
Path Parameters:
id: Memory ID (required)
Response:
204 No Content: Successfully deleted 404 Not Found: Memory not found 503 Service Unavailable: Memory system not configured
func (*Handlers) HandleDeleteSnapshot ¶
HandleDeleteSnapshot handles DELETE /v1/trace/debug/graph/snapshot/:id.
Description:
Deletes a specific snapshot from BadgerDB.
Path Parameters:
id: Snapshot ID (required)
Response:
200 OK: {"deleted": true}
404 Not Found: Snapshot not found
503 Service Unavailable: Snapshot manager not configured
Thread Safety: This method is safe for concurrent use.
func (*Handlers) HandleDetectPatterns ¶
HandleDetectPatterns detects design patterns in the codebase.
func (*Handlers) HandleDetectSideEffects ¶
HandleDetectSideEffects detects side effects of a function.
func (*Handlers) HandleDiffSnapshots ¶
HandleDiffSnapshots handles GET /v1/trace/debug/graph/snapshot/diff.
Description:
Compares two snapshots and returns the differences.
Query Parameters:
base: Base snapshot ID (required) target: Target snapshot ID (required)
Response:
200 OK: SnapshotDiffResponse 400 Bad Request: Missing required parameters 404 Not Found: Snapshot not found 503 Service Unavailable: Snapshot manager not configured
Thread Safety: This method is safe for concurrent use.
func (*Handlers) HandleExportGraph ¶
HandleExportGraph handles GET /v1/trace/debug/graph/export.
Description:
Exports the full graph as a SerializableGraph JSON stream. Sets Content-Disposition header for download. Uses streaming encoder to avoid buffering the entire JSON in memory.
Query Parameters:
graph_id: ID of the graph to query (optional, uses first cached if not specified)
Response:
200 OK: SerializableGraph (JSON stream with Content-Disposition: attachment) 404 Not Found: No graphs cached or graph not found
Thread Safety: This method is safe for concurrent use. Read-only access to graph.
func (*Handlers) HandleExtractConventions ¶
HandleExtractConventions extracts coding conventions.
func (*Handlers) HandleFindCallees ¶
HandleFindCallees handles GET /v1/trace/callees.
Description:
Finds all functions that the given function calls.
Query Parameters:
graph_id: ID of the graph to query (required) function: Name of the function to find callees for (required) limit: Maximum number of results (optional, default 50)
Response:
200 OK: CalleesResponse (may be empty array) 400 Bad Request: Missing parameters or graph not initialized
func (*Handlers) HandleFindCircularDeps ¶
HandleFindCircularDeps finds circular dependencies.
func (*Handlers) HandleFindCodeSmells ¶
HandleFindCodeSmells finds code quality issues.
func (*Handlers) HandleFindCommunities ¶
HandleFindCommunities handles POST /v1/trace/analytics/communities.
Description:
Detects code communities in the graph using the Leiden algorithm.
Request Body:
graph_id: ID of the graph to query (required)
Response:
200 OK: AgenticResponse wrapping community results 400 Bad Request: Invalid body or graph not initialized
func (*Handlers) HandleFindConfigUsage ¶
HandleFindConfigUsage finds usages of configuration values.
func (*Handlers) HandleFindCycles ¶
HandleFindCycles handles POST /v1/trace/analytics/cycles.
Description:
Finds cyclic dependencies in the graph.
Request Body:
graph_id: ID of the graph to query (required)
Response:
200 OK: AgenticResponse wrapping cycle results 400 Bad Request: Invalid body or graph not initialized
func (*Handlers) HandleFindDeadCode ¶
HandleFindDeadCode finds unreferenced code.
func (*Handlers) HandleFindDuplication ¶
HandleFindDuplication finds duplicate code.
func (*Handlers) HandleFindEntryPoints ¶
HandleFindEntryPoints finds code entry points (main, handlers, commands, tests).
func (*Handlers) HandleFindHotspots ¶
HandleFindHotspots handles POST /v1/trace/analytics/hotspots.
Description:
Finds the most-connected nodes in the graph.
Request Body:
graph_id: ID of the graph to query (required) limit: Maximum number of results (optional, default 10)
Response:
200 OK: AgenticResponse wrapping hotspot results 400 Bad Request: Invalid body or graph not initialized
func (*Handlers) HandleFindImportant ¶
HandleFindImportant handles POST /v1/trace/analytics/important.
Description:
Finds the most important nodes by PageRank.
Request Body:
graph_id: ID of the graph to query (required) limit: Maximum number of results (optional, default 10)
Response:
200 OK: AgenticResponse wrapping PageRank results 400 Bad Request: Invalid body or graph not initialized
func (*Handlers) HandleFindPath ¶
HandleFindPath handles POST /v1/trace/analytics/path.
Description:
Finds the shortest path between two functions.
Request Body:
graph_id: ID of the graph to query (required) from: Source function name (required) to: Target function name (required)
Response:
200 OK: AgenticResponse wrapping path result 400 Bad Request: Invalid body, graph not initialized, or function not found
func (*Handlers) HandleFindReferences ¶
HandleFindReferences handles GET /v1/trace/references.
Description:
Finds all locations that reference the given symbol.
Query Parameters:
graph_id: ID of the graph to query (required) symbol: Name of the symbol to find references for (required) limit: Maximum number of results (optional, default 50)
Response:
200 OK: ReferencesResponse (may be empty array) 400 Bad Request: Missing parameters or graph not initialized
func (*Handlers) HandleFindSimilarCode ¶
HandleFindSimilarCode finds structurally similar code.
func (*Handlers) HandleFindTestCoverage ¶
HandleFindTestCoverage finds tests that cover a symbol.
func (*Handlers) HandleGetCacheStats ¶
HandleGetCacheStats handles GET /v1/trace/debug/cache.
Description:
Returns query cache statistics from the CRSGraphAdapter. GR-10: Added to expose LRU cache hit/miss stats for monitoring.
Query Parameters:
graph_id: ID of the graph to query (optional, uses first cached if not specified)
Response:
200 OK: QueryCacheStats (callers/callees/paths cache stats) 404 Not Found: No graphs cached or graph not found 503 Service Unavailable: Graph has no adapter (cache not available)
Thread Safety: This method is safe for concurrent use. Read-only access.
func (*Handlers) HandleGetCallChain ¶
HandleGetCallChain handles GET /v1/trace/call-chain.
Description:
Finds the shortest call chain between two functions.
Query Parameters:
graph_id: ID of the graph to query (required) from: Source function name (required) to: Target function name (required)
Response:
200 OK: CallChainResponse 400 Bad Request: Missing parameters, graph not initialized, or function not found
func (*Handlers) HandleGetGraphStats ¶
HandleGetGraphStats handles GET /v1/trace/debug/graph/stats.
Description:
Returns statistics about a cached graph including node/edge counts broken down by type and kind. Used for debugging and integration tests. GR-43: Added to validate EdgeTypeImplements edges are being created.
Query Parameters:
graph_id: ID of the graph to query (optional, uses first cached if not specified) project_root: Project root to look up graph (alternative to graph_id)
Response:
200 OK: GraphStatsResponse 404 Not Found: No graphs cached or graph not found
Thread Safety: This method is safe for concurrent use. Read-only access to graph.
func (*Handlers) HandleGetTools ¶
HandleGetTools returns all available tool definitions for agent discovery.
func (*Handlers) HandleHealth ¶
HandleHealth handles GET /v1/trace/health.
Description:
Returns the health status of the service. Always returns 200 if running.
Response:
200 OK: HealthResponse
func (*Handlers) HandleImplementations ¶
HandleImplementations handles GET /v1/trace/implementations.
Description:
Finds all types that implement the given interface.
Query Parameters:
graph_id: ID of the graph to query (required) interface: Name of the interface to find implementations for (required) limit: Maximum number of results (optional, default 50)
Response:
200 OK: ImplementationsResponse (may be empty array) 400 Bad Request: Missing parameters or graph not initialized
func (*Handlers) HandleIndexingStatus ¶
HandleIndexingStatus handles GET /v1/trace/indexing/status.
Description:
Returns the current state of background symbol indexing into Weaviate. Polled by the trace-proxy to render live progress in the terminal.
Response:
200 OK: IndexingStatusResponse
Thread Safety: Safe for concurrent use.
func (*Handlers) HandleInit ¶
HandleInit handles POST /v1/trace/init.
Description:
Initializes a code graph for a project. Parses the project files, builds the code graph and symbol index, and caches the result.
Request Body:
InitRequest
Response:
200 OK: InitResponse 400 Bad Request: Validation error 500 Internal Server Error: Processing error
func (*Handlers) HandleInspectNode ¶
HandleInspectNode handles GET /v1/trace/debug/graph/inspect.
Description:
Looks up a symbol by name in the graph and returns its node with incoming and outgoing edges. Used for QA debugging to verify graph topology matches expected code relationships.
Query Parameters:
graph_id: ID of the graph to query (optional, uses first cached if not specified) name: Symbol name to look up (required) kind: Filter results to a specific symbol kind (optional) limit: Maximum edges per direction, default 50 (optional)
Response:
200 OK: InspectNodeResponse 400 Bad Request: Missing required parameter 404 Not Found: No graphs cached or graph not found
Thread Safety: This method is safe for concurrent use. Read-only access to graph.
func (*Handlers) HandleListMemories ¶
HandleListMemories handles GET /v1/trace/memories.
Description:
Lists memories for the configured data space with optional filtering.
Query Parameters:
limit: Maximum number of results (optional, default 10) offset: Number of results to skip for pagination (optional) memory_type: Filter by memory type (optional) include_archived: Include archived memories (optional, default false) min_confidence: Minimum confidence threshold (optional)
Response:
200 OK: MemoriesResponse 503 Service Unavailable: Memory system not configured
func (*Handlers) HandleListSnapshots ¶
HandleListSnapshots handles GET /v1/trace/debug/graph/snapshots.
Description:
Lists saved graph snapshots, optionally filtered by project root.
Query Parameters:
project_root: Optional filter by project root path limit: Maximum results, default 100
Response:
200 OK: ListSnapshotsResponse 503 Service Unavailable: Snapshot manager not configured
Thread Safety: This method is safe for concurrent use.
func (*Handlers) HandleLoadSnapshot ¶
HandleLoadSnapshot handles GET /v1/trace/debug/graph/snapshot/:id.
Description:
Loads a specific snapshot and returns its metadata and basic graph statistics (node count, edge count, hash). The graph is reconstructed to compute these values but is not cached in memory.
Path Parameters:
id: Snapshot ID (required)
Response:
200 OK: LoadSnapshotResponse 404 Not Found: Snapshot not found 503 Service Unavailable: Snapshot manager not configured
Thread Safety: This method is safe for concurrent use.
func (*Handlers) HandlePlanMultiFileChange ¶
HandlePlanMultiFileChange generates a coordinated change plan.
func (*Handlers) HandlePreviewChanges ¶
HandlePreviewChanges generates unified diffs for a plan.
func (*Handlers) HandleReady ¶
HandleReady handles GET /v1/trace/ready.
Description:
Returns the readiness status of the service including dependency checks. Returns 503 Service Unavailable if model warmup has not completed.
Response:
200 OK: ReadyResponse (Ready=true) - Service is fully ready 503 Service Unavailable: ReadyResponse (Ready=false) - Warmup in progress
func (*Handlers) HandleRetrieveMemories ¶
HandleRetrieveMemories handles POST /v1/trace/memories/retrieve.
Description:
Performs semantic retrieval of memories relevant to a query.
Request Body:
RetrieveRequest
Response:
200 OK: RetrieveResponse 400 Bad Request: Validation error 503 Service Unavailable: Memory system not configured
func (*Handlers) HandleSaveSnapshot ¶
HandleSaveSnapshot handles POST /v1/trace/debug/graph/snapshot.
Description:
Saves the current graph as a persistent snapshot in BadgerDB.
Request Body:
SaveSnapshotRequest (graph_id optional, label optional)
Response:
200 OK: SaveSnapshotResponse 404 Not Found: Graph not found 500 Internal Server Error: Snapshot save failed 503 Service Unavailable: Snapshot manager not configured
Thread Safety: This method is safe for concurrent use.
func (*Handlers) HandleSeed ¶
HandleSeed handles POST /v1/trace/seed.
Description:
Seeds library documentation from project dependencies into Weaviate. Parses go.mod, locates cached dependencies, extracts documentation, and indexes into Weaviate for context assembly.
Request Body:
SeedRequest
Response:
200 OK: SeedResponse 400 Bad Request: Validation error 503 Service Unavailable: Weaviate not configured
func (*Handlers) HandleSimulateChange ¶
HandleSimulateChange simulates a change and identifies update locations.
func (*Handlers) HandleStoreMemory ¶
HandleStoreMemory handles POST /v1/trace/memories.
Description:
Stores a new memory in Weaviate.
Request Body:
StoreRequest
Response:
201 Created: MemoryResponse 400 Bad Request: Validation error 503 Service Unavailable: Memory system not configured
func (*Handlers) HandleSuggestRefactor ¶
HandleSuggestRefactor suggests refactoring improvements.
func (*Handlers) HandleSummarizeFile ¶
HandleSummarizeFile generates a structured summary of a file.
func (*Handlers) HandleSummarizePackage ¶
HandleSummarizePackage generates a public API summary of a package.
func (*Handlers) HandleSymbol ¶
HandleSymbol handles GET /v1/trace/symbol/:id.
Description:
Retrieves detailed information about a symbol by its ID.
Query Parameters:
graph_id: ID of the graph to query (required)
Path Parameters:
id: Symbol ID (required)
Response:
200 OK: SymbolResponse 400 Bad Request: Graph not initialized 404 Not Found: Symbol not found
func (*Handlers) HandleTraceDataFlow ¶
HandleTraceDataFlow traces data flow from a source through the codebase.
func (*Handlers) HandleTraceErrorFlow ¶
HandleTraceErrorFlow traces error propagation through the codebase.
func (*Handlers) HandleValidateChange ¶
HandleValidateChange validates proposed code syntactically.
func (*Handlers) HandleValidateMemory ¶
HandleValidateMemory handles POST /v1/trace/memories/:id/validate.
Description:
Validates a memory, boosting its confidence score.
Path Parameters:
id: Memory ID (required)
Response:
200 OK: MemoryResponse 404 Not Found: Memory not found 503 Service Unavailable: Memory system not configured
func (*Handlers) HandleValidatePlan ¶
HandleValidatePlan validates a change plan.
func (*Handlers) WithIndexingCoordinator ¶
func (h *Handlers) WithIndexingCoordinator(coord *SymbolIndexingCoordinator) *Handlers
WithIndexingCoordinator sets the symbol indexing coordinator for eager indexing.
Description:
CRS-26l: When set, HandleInit triggers symbol indexing immediately after a successful graph build, so symbols are ready before any user query.
Inputs:
coord - The indexing coordinator. May be nil (no eager indexing).
Outputs:
*Handlers - The handlers for method chaining.
func (*Handlers) WithMemory ¶
WithMemory sets the data space and initializes memory components.
Description:
Configures the handlers for memory operations. Requires Weaviate to be configured first via WithWeaviate.
Inputs:
dataSpace - Project isolation key for memory operations
Outputs:
*Handlers - The handlers for method chaining
func (*Handlers) WithNATS ¶
func (h *Handlers) WithNATS(client NATSHealthChecker) *Handlers
WithNATS sets the NATS client for CRS delta streaming and health checks. CRS-27: Optional. If nil, NATS-related features are disabled.
type HealthResponse ¶
type HealthResponse struct {
// Status is "healthy" or "degraded".
Status string `json:"status"`
// Version is the service version.
Version string `json:"version"`
// LSP contains LSP enrichment status. Present only when LSP is enabled.
// GR-75: Reports per-language availability for container diagnostics.
LSP *LSPHealthStatus `json:"lsp,omitempty"`
}
HealthResponse is the response for GET /v1/trace/health.
type HistoryEntryResponse ¶
type HistoryEntryResponse struct {
// NodeID is the explored node.
NodeID string `json:"node_id"`
// VisitCount is how many times this node was visited.
VisitCount int `json:"visit_count"`
// LastVisitedAt is when it was last visited (RFC3339).
LastVisitedAt string `json:"last_visited_at,omitempty"`
}
HistoryEntryResponse represents an exploration history entry.
type ImplementationsRequest ¶
type ImplementationsRequest struct {
// GraphID is the graph to query. Required.
GraphID string `form:"graph_id" binding:"required"`
// Interface is the interface name to find implementations for. Required.
Interface string `form:"interface" binding:"required"`
// Limit is the maximum number of results. Default: 50.
Limit int `form:"limit"`
}
ImplementationsRequest is the query params for GET /v1/trace/implementations.
type ImplementationsResponse ¶
type ImplementationsResponse struct {
// Interface is the interface name that was searched.
Interface string `json:"interface"`
// Implementations is the list of types that implement the interface.
Implementations []*SymbolInfo `json:"implementations"`
}
ImplementationsResponse is the response for GET /v1/trace/implementations.
type IndexingStatusResponse ¶
type IndexingStatusResponse struct {
// InProgress is true while indexing is running.
InProgress bool `json:"in_progress"`
// Phase is the current indexing phase: "idle", "collecting", "embedding",
// "inserting", or "complete".
Phase string `json:"phase"`
// SymbolsTotal is the total number of symbols to index.
SymbolsTotal int `json:"symbols_total"`
// BatchesCompleted is the number of Weaviate insert batches completed.
BatchesCompleted int `json:"batches_completed"`
// BatchesTotal is the total number of Weaviate insert batches.
BatchesTotal int `json:"batches_total"`
// SymbolsIndexed is the number of symbols successfully indexed so far.
SymbolsIndexed int `json:"symbols_indexed"`
// Error contains the error message if indexing failed.
Error string `json:"error,omitempty"`
}
IndexingStatusResponse is the response for GET /v1/trace/indexing/status.
Description:
Reports the current state of background symbol indexing into Weaviate. Polled by the trace-proxy to render live progress in the terminal.
Thread Safety: Not safe for concurrent use (returned as a snapshot).
type InitRequest ¶
type InitRequest struct {
// ProjectRoot is the absolute path to the project root directory.
// Required.
ProjectRoot string `json:"project_root" binding:"required"`
// Languages is the list of languages to parse. Default: ["go"].
Languages []string `json:"languages"`
// ExcludePatterns is a list of glob patterns to exclude. Default: ["vendor/*", "*_test.go"].
ExcludePatterns []string `json:"exclude_patterns"`
}
InitRequest is the request body for POST /v1/trace/init.
type InitResponse ¶
type InitResponse struct {
// GraphID is the unique identifier for this graph.
GraphID string `json:"graph_id"`
// IsRefresh indicates if this replaced an existing graph.
IsRefresh bool `json:"is_refresh"`
// PreviousID is the ID of the replaced graph (if IsRefresh is true).
PreviousID string `json:"previous_id,omitempty"`
// FilesParsed is the number of files successfully parsed.
FilesParsed int `json:"files_parsed"`
// SymbolsExtracted is the total number of symbols extracted.
SymbolsExtracted int `json:"symbols_extracted"`
// EdgesBuilt is the total number of edges created.
EdgesBuilt int `json:"edges_built"`
// ParseTimeMs is the total parse time in milliseconds.
ParseTimeMs int64 `json:"parse_time_ms"`
// Errors contains non-fatal errors encountered during parsing.
Errors []string `json:"errors,omitempty"`
}
InitResponse is the response for POST /v1/trace/init.
type InspectEdge ¶
type InspectEdge struct {
// PeerID is the ID of the node on the other end of the edge.
PeerID string `json:"peer_id"`
// PeerName is the name of the peer symbol.
PeerName string `json:"peer_name"`
// PeerKind is the kind of the peer symbol.
PeerKind string `json:"peer_kind"`
// EdgeType is the relationship type (e.g., "calls", "implements").
EdgeType string `json:"edge_type"`
// Location is where the relationship is expressed in code.
Location *ast.Location `json:"location,omitempty"`
}
InspectEdge represents an edge in an inspect response.
type InspectNodeMatch ¶
type InspectNodeMatch struct {
// NodeID is the unique node identifier.
NodeID string `json:"node_id"`
// Symbol is the symbol information.
Symbol *SymbolInfo `json:"symbol"`
// Outgoing contains edges from this node to other nodes.
Outgoing []InspectEdge `json:"outgoing"`
// Incoming contains edges from other nodes to this node.
Incoming []InspectEdge `json:"incoming"`
}
InspectNodeMatch represents a single matching node in an inspect response.
type InspectNodeRequest ¶
type InspectNodeRequest struct {
// GraphID is the graph to query. Optional, uses first cached if not specified.
GraphID string `form:"graph_id"`
// Name is the symbol name to look up. Required.
Name string `form:"name" binding:"required"`
// Kind filters results to a specific symbol kind (e.g., "function", "struct").
// Optional, returns all kinds if not specified.
Kind string `form:"kind"`
// Limit is the maximum number of edges per direction. Default: 50.
Limit int `form:"limit"`
}
InspectNodeRequest is the query params for GET /v1/trace/debug/graph/inspect.
type InspectNodeResponse ¶
type InspectNodeResponse struct {
// Matches contains the matching nodes with their edges.
Matches []InspectNodeMatch `json:"matches"`
// Truncated indicates if any match had its edge list truncated.
Truncated bool `json:"truncated"`
}
InspectNodeResponse is the response for GET /v1/trace/debug/graph/inspect.
type LSPDefinitionRequest ¶
type LSPDefinitionRequest struct {
// GraphID is the graph to use for project context. Required.
GraphID string `json:"graph_id" binding:"required"`
// FilePath is the absolute path to the file. Required.
FilePath string `json:"file_path" binding:"required"`
// Line is the 1-indexed line number. Required.
Line int `json:"line" binding:"required,min=1"`
// Column is the 0-indexed column number. Required.
Column int `json:"column" binding:"required,min=0"`
}
LSPDefinitionRequest is the request for POST /v1/trace/lsp/definition.
type LSPDefinitionResponse ¶
type LSPDefinitionResponse struct {
// Locations contains the definition location(s).
Locations []LSPLocation `json:"locations"`
// LatencyMs is the request latency in milliseconds.
LatencyMs int64 `json:"latency_ms"`
}
LSPDefinitionResponse is the response for POST /v1/trace/lsp/definition.
type LSPHealthStatus ¶
type LSPHealthStatus struct {
// Enabled is true when LSP enrichment is globally active.
Enabled bool `json:"enabled"`
// Python reports Pyright availability.
Python LSPLanguageStatus `json:"python"`
// TypeScript reports typescript-language-server availability.
TypeScript LSPLanguageStatus `json:"typescript"`
// JavaScript reports typescript-language-server availability for JS files.
// Uses the same server binary as TypeScript.
JavaScript LSPLanguageStatus `json:"javascript"`
}
LSPHealthStatus reports language server availability in the health check.
Description:
GR-75: Included in HealthResponse when LSP enrichment is enabled. Language servers are lazy-started (first graph build triggers them), so running=false at startup is expected and healthy.
Thread Safety:
Immutable after construction.
type LSPHoverRequest ¶
type LSPHoverRequest struct {
// GraphID is the graph to use for project context. Required.
GraphID string `json:"graph_id" binding:"required"`
// FilePath is the absolute path to the file. Required.
FilePath string `json:"file_path" binding:"required"`
// Line is the 1-indexed line number. Required.
Line int `json:"line" binding:"required,min=1"`
// Column is the 0-indexed column number. Required.
Column int `json:"column" binding:"required,min=0"`
}
LSPHoverRequest is the request for POST /v1/trace/lsp/hover.
type LSPHoverResponse ¶
type LSPHoverResponse struct {
// Content is the hover content (documentation, type info).
Content string `json:"content"`
// Kind is the content format ("plaintext" or "markdown").
Kind string `json:"kind"`
// Range is the range this hover applies to (optional).
Range *LSPLocation `json:"range,omitempty"`
// LatencyMs is the request latency in milliseconds.
LatencyMs int64 `json:"latency_ms"`
}
LSPHoverResponse is the response for POST /v1/trace/lsp/hover.
type LSPLanguageStatus ¶
type LSPLanguageStatus struct {
// Available is true if the binary was found in PATH at startup.
Available bool `json:"available"`
}
LSPLanguageStatus reports a single language server's status.
type LSPLocation ¶
type LSPLocation struct {
// FilePath is the absolute path to the file.
FilePath string `json:"file_path"`
// StartLine is the 1-indexed start line.
StartLine int `json:"start_line"`
// StartColumn is the 0-indexed start column.
StartColumn int `json:"start_column"`
// EndLine is the 1-indexed end line.
EndLine int `json:"end_line"`
// EndColumn is the 0-indexed end column.
EndColumn int `json:"end_column"`
}
LSPLocation represents a location in a document.
type LSPReferencesRequest ¶
type LSPReferencesRequest struct {
// GraphID is the graph to use for project context. Required.
GraphID string `json:"graph_id" binding:"required"`
// FilePath is the absolute path to the file. Required.
FilePath string `json:"file_path" binding:"required"`
// Line is the 1-indexed line number. Required.
Line int `json:"line" binding:"required,min=1"`
// Column is the 0-indexed column number. Required.
Column int `json:"column" binding:"required,min=0"`
// IncludeDeclaration includes the declaration in results.
IncludeDeclaration bool `json:"include_declaration"`
}
LSPReferencesRequest is the request for POST /v1/trace/lsp/references.
type LSPReferencesResponse ¶
type LSPReferencesResponse struct {
// Locations contains the reference location(s).
Locations []LSPLocation `json:"locations"`
// LatencyMs is the request latency in milliseconds.
LatencyMs int64 `json:"latency_ms"`
}
LSPReferencesResponse is the response for POST /v1/trace/lsp/references.
type LSPRenameRequest ¶
type LSPRenameRequest struct {
// GraphID is the graph to use for project context. Required.
GraphID string `json:"graph_id" binding:"required"`
// FilePath is the absolute path to the file. Required.
FilePath string `json:"file_path" binding:"required"`
// Line is the 1-indexed line number. Required.
Line int `json:"line" binding:"required,min=1"`
// Column is the 0-indexed column number. Required.
Column int `json:"column" binding:"required,min=0"`
// NewName is the new name for the symbol. Required.
NewName string `json:"new_name" binding:"required"`
}
LSPRenameRequest is the request for POST /v1/trace/lsp/rename.
type LSPRenameResponse ¶
type LSPRenameResponse struct {
// Edits is a map from file path to list of text edits.
Edits map[string][]LSPTextEdit `json:"edits"`
// FileCount is the number of files affected.
FileCount int `json:"file_count"`
// EditCount is the total number of edits.
EditCount int `json:"edit_count"`
// LatencyMs is the request latency in milliseconds.
LatencyMs int64 `json:"latency_ms"`
}
LSPRenameResponse is the response for POST /v1/trace/lsp/rename.
type LSPStatusResponse ¶
type LSPStatusResponse struct {
// Available indicates if LSP is available for the project.
Available bool `json:"available"`
// RunningServers lists languages with running servers.
RunningServers []string `json:"running_servers"`
// SupportedLanguages lists all supported languages.
SupportedLanguages []string `json:"supported_languages"`
}
LSPStatusResponse is the response for GET /v1/trace/lsp/status.
type LSPSymbolInfo ¶
type LSPSymbolInfo struct {
// Name is the symbol name.
Name string `json:"name"`
// Kind is the symbol kind (function, class, etc.).
Kind string `json:"kind"`
// Location is where the symbol is defined.
Location LSPLocation `json:"location"`
// ContainerName is the name of the containing symbol.
ContainerName string `json:"container_name,omitempty"`
}
LSPSymbolInfo represents information about a workspace symbol.
type LSPTextEdit ¶
type LSPTextEdit struct {
// Range is the range to replace.
Range LSPLocation `json:"range"`
// NewText is the replacement text.
NewText string `json:"new_text"`
}
LSPTextEdit represents a text edit.
type LSPWorkspaceSymbolRequest ¶
type LSPWorkspaceSymbolRequest struct {
// GraphID is the graph to use for project context. Required.
GraphID string `json:"graph_id" binding:"required"`
// Query is the symbol search query. Required.
Query string `json:"query" binding:"required"`
// Language is the language to search (defaults to project primary language).
Language string `json:"language"`
}
LSPWorkspaceSymbolRequest is the request for POST /v1/trace/lsp/symbols.
type LSPWorkspaceSymbolResponse ¶
type LSPWorkspaceSymbolResponse struct {
// Symbols contains the matching symbols.
Symbols []LSPSymbolInfo `json:"symbols"`
// LatencyMs is the request latency in milliseconds.
LatencyMs int64 `json:"latency_ms"`
}
LSPWorkspaceSymbolResponse is the response for POST /v1/trace/lsp/symbols.
type ListSnapshotsResponse ¶
type ListSnapshotsResponse struct {
// Snapshots contains the snapshot metadata entries.
Snapshots []*graph.SnapshotMetadata `json:"snapshots"`
}
ListSnapshotsResponse is the response for GET /v1/trace/debug/graph/snapshots.
type LoadSnapshotResponse ¶
type LoadSnapshotResponse struct {
// Metadata is the snapshot metadata.
Metadata *graph.SnapshotMetadata `json:"metadata"`
// NodeCount is the number of nodes in the loaded graph.
NodeCount int `json:"node_count"`
// EdgeCount is the number of edges in the loaded graph.
EdgeCount int `json:"edge_count"`
// GraphHash is the hash of the loaded graph (should match metadata).
GraphHash string `json:"graph_hash"`
}
LoadSnapshotResponse is the response for GET /v1/trace/debug/graph/snapshot/:id.
type NATSHealthChecker ¶
NATSHealthChecker is the interface for NATS health checking. CRS-27: Decoupled from concrete nats.Client to avoid import cycle.
type NATSSSEProvider ¶
type NATSSSEProvider interface {
IsConnected() bool
JetStream() nats.JetStreamContext
}
NATSSSEProvider provides NATS subscription capability for SSE streaming. CRS-27: Interface to decouple from concrete nats storage client.
type PhaseAdapter ¶
type PhaseAdapter struct {
// contains filtered or unexported fields
}
PhaseAdapter adapts a phases.Phase to agent.PhaseExecutor.
Description:
PhaseAdapter wraps a phases.Phase to implement the agent.PhaseExecutor interface. It handles the conversion of the untyped deps parameter to *phases.Dependencies.
Thread Safety: PhaseAdapter is safe for concurrent use (delegates to Phase).
func NewPhaseAdapter ¶
func NewPhaseAdapter(phase phases.Phase) *PhaseAdapter
NewPhaseAdapter creates a new phase adapter.
Inputs:
phase - The phase to wrap.
Outputs:
*PhaseAdapter - The adapter.
func (*PhaseAdapter) Execute ¶
func (a *PhaseAdapter) Execute(ctx context.Context, deps any) (agent.AgentState, error)
Execute implements agent.PhaseExecutor.
Description:
Executes the wrapped phase. Converts the deps parameter to *phases.Dependencies. Returns an error if deps is nil or wrong type.
Inputs:
ctx - Context for cancellation and timeout. deps - Dependencies (must be *phases.Dependencies).
Outputs:
agent.AgentState - The next state. error - Non-nil if execution failed or deps is invalid.
Thread Safety: This method is safe for concurrent use.
func (*PhaseAdapter) Name ¶
func (a *PhaseAdapter) Name() string
Name implements agent.PhaseExecutor.
Outputs:
string - The phase name.
type PlanMultiFileChangeRequest ¶
type PlanMultiFileChangeRequest struct {
GraphID string `json:"graph_id" binding:"required"`
TargetID string `json:"target_id" binding:"required"`
ChangeType string `json:"change_type" binding:"required"`
NewSignature string `json:"new_signature"`
NewName string `json:"new_name"`
Description string `json:"description"`
IncludeTests bool `json:"include_tests"`
}
PlanMultiFileChangeRequest is the request for POST /v1/trace/coordinate/plan_changes.
type PreviewChangesRequest ¶
type PreviewChangesRequest struct {
PlanID string `json:"plan_id" binding:"required"`
ContextLines int `json:"context_lines"`
}
PreviewChangesRequest is the request for POST /v1/trace/coordinate/preview_changes.
type ProofEntryResponse ¶
type ProofEntryResponse struct {
// NodeID is the node identifier.
NodeID string `json:"node_id"`
// Status is the proof status: "unknown", "proven", "disproven", "expanded".
Status string `json:"status"`
// Evidence lists reasons for this status.
Evidence []string `json:"evidence,omitempty"`
}
ProofEntryResponse represents a proof entry in API responses.
type ProofUpdateResponse ¶
type ProofUpdateResponse struct {
// NodeID is the node whose proof status changed.
NodeID string `json:"node_id"`
// Status is the new status: "proven", "disproven", "expanded", "unknown".
Status string `json:"status"`
// Reason explains why the status changed.
Reason string `json:"reason,omitempty"`
// Source indicates signal source: "hard", "soft".
Source string `json:"source,omitempty"`
}
ProofUpdateResponse represents a proof status change in API responses.
type ReadyResponse ¶
type ReadyResponse struct {
// Ready is true if the service is ready to accept requests.
Ready bool `json:"ready"`
// GraphCount is the number of cached graphs.
GraphCount int `json:"graph_count"`
// WeaviateOK is true if Weaviate connection is healthy.
WeaviateOK bool `json:"weaviate_ok"`
// NATSOK is true if NATS connection is healthy.
// CRS-27: Added for NATS JetStream observability.
NATSOK bool `json:"nats_ok"`
}
ReadyResponse is the response for GET /v1/trace/ready.
type ReasoningStep ¶
type ReasoningStep struct {
// Step is the 1-indexed step number.
Step int `json:"step"`
// Timestamp is when this step occurred (RFC3339).
Timestamp string `json:"timestamp"`
// Action describes what was done (e.g., "explore", "analyze", "trace_flow").
Action string `json:"action"`
// Target is the file or symbol being operated on.
Target string `json:"target"`
// Tool is the tool that triggered this action (optional).
Tool string `json:"tool,omitempty"`
// DurationMs is how long this step took in milliseconds.
DurationMs int64 `json:"duration_ms"`
// SymbolsFound lists symbols discovered in this step.
SymbolsFound []string `json:"symbols_found,omitempty"`
// ProofUpdates lists proof status changes.
ProofUpdates []ProofUpdateResponse `json:"proof_updates,omitempty"`
// Error contains any error that occurred.
Error string `json:"error,omitempty"`
// Metadata contains additional step context.
Metadata map[string]string `json:"metadata,omitempty"`
}
ReasoningStep represents one step in the reasoning process.
type ReasoningSummaryResponse ¶
type ReasoningSummaryResponse struct {
// NodesExplored is the total code nodes examined.
NodesExplored int `json:"nodes_explored"`
// NodesProven is nodes with verified behavior (tests pass, types check).
NodesProven int `json:"nodes_proven"`
// NodesDisproven is nodes with verified issues (tests fail, type errors).
NodesDisproven int `json:"nodes_disproven"`
// NodesUnknown is nodes without conclusive evidence.
NodesUnknown int `json:"nodes_unknown"`
// ConstraintsApplied is the number of constraints used in reasoning.
ConstraintsApplied int `json:"constraints_applied"`
// ExplorationDepth is the maximum depth reached in call graph traversal.
ExplorationDepth int `json:"exploration_depth"`
// ConfidenceScore is overall confidence in the reasoning (0.0-1.0).
ConfidenceScore float64 `json:"confidence_score"`
}
ReasoningSummaryResponse provides high-level reasoning metrics.
type ReasoningTraceResponse ¶
type ReasoningTraceResponse struct {
// SessionID is the unique session identifier.
SessionID string `json:"session_id"`
// TotalSteps is the number of reasoning steps recorded.
TotalSteps int `json:"total_steps"`
// Duration is the total time from first to last step.
Duration string `json:"total_duration"`
// StartTime is when the first step occurred (RFC3339).
StartTime string `json:"start_time,omitempty"`
// EndTime is when the last step occurred (RFC3339).
EndTime string `json:"end_time,omitempty"`
// Trace contains all recorded reasoning steps.
Trace []ReasoningStep `json:"trace"`
// Summary provides high-level reasoning metrics.
Summary *ReasoningSummaryResponse `json:"summary,omitempty"`
}
ReasoningTraceResponse is the response for GET /v1/trace/agent/:id/reasoning.
type ReferenceInfo ¶
type ReferenceInfo struct {
// FilePath is the path to the file containing the reference.
FilePath string `json:"file_path"`
// Line is the 1-indexed line number.
Line int `json:"line"`
// Column is the 0-indexed column number.
Column int `json:"column"`
}
ReferenceInfo represents a single reference location.
type ReferencesRequest ¶
type ReferencesRequest struct {
// GraphID is the graph to query. Required.
GraphID string `form:"graph_id" binding:"required"`
// Symbol is the symbol name to find references for. Required.
Symbol string `form:"symbol" binding:"required"`
// Limit is the maximum number of results. Default: 50.
Limit int `form:"limit"`
}
ReferencesRequest is the query params for GET /v1/trace/references.
type ReferencesResponse ¶
type ReferencesResponse struct {
// Symbol is the symbol name that was searched.
Symbol string `json:"symbol"`
// References is the list of reference locations.
References []ReferenceInfo `json:"references"`
}
ReferencesResponse is the response for GET /v1/trace/references.
type SaveSnapshotRequest ¶
type SaveSnapshotRequest struct {
// GraphID is the graph to snapshot. Optional, uses first cached if not specified.
GraphID string `json:"graph_id"`
// Label is an optional human-readable label for the snapshot.
Label string `json:"label"`
}
SaveSnapshotRequest is the request body for POST /v1/trace/debug/graph/snapshot.
type SaveSnapshotResponse ¶
type SaveSnapshotResponse struct {
// SnapshotID is the unique identifier for the saved snapshot.
SnapshotID string `json:"snapshot_id"`
// GraphHash is the deterministic hash of the graph structure.
GraphHash string `json:"graph_hash"`
// NodeCount is the number of nodes in the snapshot.
NodeCount int `json:"node_count"`
// EdgeCount is the number of edges in the snapshot.
EdgeCount int `json:"edge_count"`
// CompressedSize is the size of the compressed snapshot in bytes.
CompressedSize int64 `json:"compressed_size"`
}
SaveSnapshotResponse is the response for POST /v1/trace/debug/graph/snapshot.
type SeedRequest ¶
type SeedRequest struct {
// ProjectRoot is the absolute path to the project root. Required.
ProjectRoot string `json:"project_root" binding:"required"`
// DataSpace is the Weaviate data space for isolation. Required.
DataSpace string `json:"data_space" binding:"required"`
}
SeedRequest is the request body for POST /v1/trace/seed.
type SeedResponse ¶
type SeedResponse struct {
// DependenciesFound is the number of dependencies discovered.
DependenciesFound int `json:"dependencies_found"`
// DocsIndexed is the number of documentation entries indexed.
DocsIndexed int `json:"docs_indexed"`
// Errors contains non-fatal errors encountered during seeding.
Errors []string `json:"errors,omitempty"`
}
SeedResponse is the response for POST /v1/trace/seed.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service is the Trace service.
Thread Safety:
Service is safe for concurrent use. Multiple goroutines can call any combination of methods simultaneously.
func NewService ¶
func NewService(config ServiceConfig) *Service
NewService creates a new Trace service.
Description:
Creates a service with the given configuration. The service starts with no cached graphs and a default parser registry.
Inputs:
config - Service configuration
Outputs:
*Service - The configured service
func (*Service) Close ¶
Close shuts down all LSP managers and cleans up resources.
Description:
Gracefully shuts down all running LSP servers. Should be called when the service is being stopped.
Inputs:
ctx - Context for shutdown timeout
Outputs:
error - Non-nil if any shutdown encountered errors
Thread Safety:
Safe for concurrent use.
func (*Service) FindCallees ¶
func (s *Service) FindCallees(ctx context.Context, graphID, functionName string, limit int) ([]*SymbolInfo, error)
FindCallees returns all functions called by the given function.
Description:
Searches the graph for all functions that the named function calls.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query functionName - Name of the function to find callees for limit - Maximum number of results (0 = default)
Outputs:
[]*SymbolInfo - List of callee symbols error - Non-nil if graph not found
func (*Service) FindCallers ¶
func (s *Service) FindCallers(ctx context.Context, graphID, functionName string, limit int) ([]*SymbolInfo, error)
FindCallers returns all symbols that call the given function.
Description:
Searches the graph for functions that call the named function.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query functionName - Name of the function to find callers for limit - Maximum number of results (0 = default)
Outputs:
[]*SymbolInfo - List of caller symbols error - Non-nil if graph not found
func (*Service) FindCommunities ¶
func (s *Service) FindCommunities(ctx context.Context, graphID string) (*graph.CommunityResult, error)
FindCommunities detects code communities in the graph.
Description:
Creates a hierarchical graph and analytics instance, then detects communities.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query
Outputs:
*graph.CommunityResult - Leiden community detection results error - Non-nil if graph not found or analytics fails
func (*Service) FindCycles ¶
FindCycles returns cyclic dependencies in the graph.
Description:
Creates a hierarchical graph and analytics instance, then finds cycles.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query
Outputs:
[]graph.CyclicDependency - Cycles found via Tarjan's SCC algorithm error - Non-nil if graph not found or analytics fails
func (*Service) FindHotspots ¶
func (s *Service) FindHotspots(ctx context.Context, graphID string, limit int) ([]graph.HotspotNode, error)
FindHotspots returns the most-connected nodes in the graph.
Description:
Creates a hierarchical graph and analytics instance, then computes hotspots.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query limit - Maximum number of results (0 = default 10)
Outputs:
[]graph.HotspotNode - Hotspot results sorted by connectivity score error - Non-nil if graph not found or analytics fails
func (*Service) FindImplementations ¶
func (s *Service) FindImplementations(ctx context.Context, graphID, interfaceName string, limit int) ([]*SymbolInfo, error)
FindImplementations returns all types that implement the given interface.
Description:
Searches the graph for types that implement the named interface.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query interfaceName - Name of the interface to find implementations for limit - Maximum number of results (0 = default)
Outputs:
[]*SymbolInfo - List of implementing types error - Non-nil if graph not found
func (*Service) FindImportant ¶
func (s *Service) FindImportant(ctx context.Context, graphID string, limit int) ([]graph.PageRankNode, error)
FindImportant returns the most important nodes by PageRank.
Description:
Creates a hierarchical graph and analytics instance, then computes PageRank.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query limit - Maximum number of results (0 = default 10)
Outputs:
[]graph.PageRankNode - Top-k nodes sorted by PageRank score descending error - Non-nil if graph not found or analytics fails
func (*Service) FindPath ¶
func (s *Service) FindPath(ctx context.Context, graphID, from, to string) (*CallChainResponse, error)
FindPath returns the shortest path between two functions using graph analytics.
Description:
Resolves both function names and finds the shortest path. Uses the same underlying ShortestPath as GetCallChain but wrapped in AgenticResponse.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query from - Source function name to - Target function name
Outputs:
*CallChainResponse - Path result with symbols and length error - Non-nil if graph not found or names unresolved
func (*Service) FindReferences ¶
func (s *Service) FindReferences(ctx context.Context, graphID, symbolName string, limit int) ([]ReferenceInfo, error)
FindReferences returns all locations that reference the given symbol.
Description:
Resolves the symbol name to node IDs and finds all reference locations.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query symbolName - Name of the symbol to find references for limit - Maximum number of results (0 = default)
Outputs:
[]ReferenceInfo - List of reference locations error - Non-nil if graph not found
func (*Service) GetCallChain ¶
func (s *Service) GetCallChain(ctx context.Context, graphID, from, to string) ([]*SymbolInfo, int, error)
GetCallChain returns the shortest path between two functions.
Description:
Resolves both function names to node IDs and finds the shortest path.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query from - Source function name to - Target function name
Outputs:
[]*SymbolInfo - Symbols along the path int - Path length (-1 if no path) error - Non-nil if graph not found or names unresolved
func (*Service) GetContext ¶
func (s *Service) GetContext(ctx context.Context, graphID, query string, budget int) (*ContextResponse, error)
GetContext assembles context for a query.
Description:
Uses the cached graph to assemble relevant context for an LLM prompt.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query query - Search query or task description budget - Maximum tokens to use
Outputs:
*ContextResponse - Assembled context with metadata error - Non-nil if graph not found or assembly fails
func (*Service) GetGraph ¶
func (s *Service) GetGraph(graphID string) (*CachedGraph, error)
GetGraph retrieves a cached graph by ID.
Description:
Returns the cached graph if it exists and hasn't expired.
Inputs:
graphID - ID of the graph to retrieve
Outputs:
*CachedGraph - The cached graph error - ErrGraphNotInitialized if not found, ErrGraphExpired if expired
func (*Service) GetGraphForPlan ¶
func (s *Service) GetGraphForPlan(plan interface{}) (*CachedGraph, error)
GetGraphForPlan returns the graph associated with a plan.
Description:
Finds the graph that was used to create the plan.
Inputs:
plan - The change plan
Outputs:
*CachedGraph - The graph error - Non-nil if graph not found
func (*Service) GetPlan ¶
GetPlan retrieves a stored change plan by ID.
Description:
Returns the plan if found and not expired.
Inputs:
planID - The plan ID
Outputs:
interface{} - The plan (caller casts to *coordinate.ChangePlan)
error - Non-nil if plan not found
func (*Service) GetSymbol ¶
GetSymbol retrieves a symbol by its ID.
Description:
Looks up a symbol in the graph by its unique ID.
Inputs:
ctx - Context for cancellation graphID - ID of the graph to query symbolID - ID of the symbol to retrieve
Outputs:
*SymbolInfo - The symbol if found error - Non-nil if graph not found or symbol not found
func (*Service) GraphCount ¶
GraphCount returns the number of cached graphs.
func (*Service) Init ¶
func (s *Service) Init(ctx context.Context, projectRoot string, languages, excludes []string, forceRebuild ...bool) (*InitResponse, error)
Init initializes a code graph for a project.
Description:
Parses the project, builds the code graph and symbol index, and caches the result. If a graph already exists for the project, it is replaced.
Inputs:
ctx - Context for cancellation projectRoot - Absolute path to the project root languages - Languages to parse (default: ["go"]) excludes - Glob patterns to exclude (default: ["vendor/*", "*_test.go"])
Outputs:
*InitResponse - Graph statistics and metadata error - Non-nil if validation fails or parsing fails
Errors:
ErrRelativePath - Project root is not absolute ErrPathTraversal - Project root contains .. sequences ErrProjectTooLarge - Project exceeds configured limits ErrInitInProgress - Another init is running for this project ErrInitTimeout - Init took too long
func (*Service) LSPDefinition ¶
func (s *Service) LSPDefinition(ctx context.Context, graphID, filePath string, line, col int) (*LSPDefinitionResponse, error)
LSPDefinition returns the definition location(s) for a symbol.
Description:
Uses the LSP server to find the definition of the symbol at the given position. More accurate than graph-based lookup for cross-file and type-based resolution.
Inputs:
ctx - Context for cancellation and timeout graphID - The graph to use for project context filePath - Absolute path to the file line - 1-indexed line number col - 0-indexed column number
Outputs:
*LSPDefinitionResponse - Definition locations with latency error - Non-nil on failure
Thread Safety:
Safe for concurrent use.
func (*Service) LSPEnrichmentStatus ¶
LSPEnrichmentStatus returns the LSP enrichment availability for health checks.
Description:
GR-75: Returns whether LSP enrichment is enabled and which languages have binaries available. Used by the health endpoint to report container-level LSP status.
Outputs:
enabled - Whether LSP enrichment is globally enabled. languages - Map of language name to availability.
Thread Safety:
Safe for concurrent use (reads only immutable state set at startup).
func (*Service) LSPHover ¶
func (s *Service) LSPHover(ctx context.Context, graphID, filePath string, line, col int) (*LSPHoverResponse, error)
LSPHover returns type and documentation info for a symbol.
Description:
Uses the LSP server to get hover information (type, documentation) for the symbol at the given position.
Inputs:
ctx - Context for cancellation and timeout graphID - The graph to use for project context filePath - Absolute path to the file line - 1-indexed line number col - 0-indexed column number
Outputs:
*LSPHoverResponse - Hover content with latency error - Non-nil on failure
Thread Safety:
Safe for concurrent use.
func (*Service) LSPReferences ¶
func (s *Service) LSPReferences(ctx context.Context, graphID, filePath string, line, col int, includeDecl bool) (*LSPReferencesResponse, error)
LSPReferences returns all references to a symbol.
Description:
Uses the LSP server to find all references to the symbol at the given position. More accurate than graph-based lookup.
Inputs:
ctx - Context for cancellation and timeout graphID - The graph to use for project context filePath - Absolute path to the file line - 1-indexed line number col - 0-indexed column number includeDecl - Whether to include the declaration in results
Outputs:
*LSPReferencesResponse - Reference locations with latency error - Non-nil on failure
Thread Safety:
Safe for concurrent use.
func (*Service) LSPRename ¶
func (s *Service) LSPRename(ctx context.Context, graphID, filePath string, line, col int, newName string) (*LSPRenameResponse, error)
LSPRename computes edits for renaming a symbol.
Description:
Uses the LSP server to compute all edits needed to rename the symbol at the given position. Returns the edits but does NOT apply them.
Inputs:
ctx - Context for cancellation and timeout graphID - The graph to use for project context filePath - Absolute path to the file line - 1-indexed line number col - 0-indexed column number newName - The new name for the symbol
Outputs:
*LSPRenameResponse - Edits with file count and latency error - Non-nil on failure
Thread Safety:
Safe for concurrent use.
func (*Service) LSPStatus ¶
func (s *Service) LSPStatus(graphID string) (*LSPStatusResponse, error)
LSPStatus returns the status of LSP for a graph.
Description:
Returns information about LSP availability and running servers for the given graph.
Inputs:
graphID - The graph to check status for
Outputs:
*LSPStatusResponse - Status information error - Non-nil if graph not found
Thread Safety:
Safe for concurrent use.
func (*Service) LSPWorkspaceSymbol ¶
func (s *Service) LSPWorkspaceSymbol(ctx context.Context, graphID, language, query string) (*LSPWorkspaceSymbolResponse, error)
LSPWorkspaceSymbol finds symbols matching a query.
Description:
Uses the LSP server to find symbols matching the query across the workspace.
Inputs:
ctx - Context for cancellation and timeout graphID - The graph to use for project context language - The language to search (required) query - The symbol search query
Outputs:
*LSPWorkspaceSymbolResponse - Matching symbols with latency error - Non-nil on failure
Thread Safety:
Safe for concurrent use.
func (*Service) SetLSPEnabled ¶
SetLSPEnabled configures LSP enrichment availability on the service.
Description:
GR-75: Called during startup to record which languages have LSP enrichment available. Used by the health endpoint to report LSP status.
Inputs:
enabled - Whether LSP enrichment is globally enabled.
languages - Map of language name to availability (e.g. {"python": true, "typescript": false}).
Thread Safety:
Must be called before the service starts serving requests.
func (*Service) SetLibraryDocProvider ¶
func (s *Service) SetLibraryDocProvider(p cbcontext.LibraryDocProvider)
SetLibraryDocProvider sets the library documentation provider.
func (*Service) SetSnapshotManager ¶
func (s *Service) SetSnapshotManager(mgr *graph.SnapshotManager)
SetSnapshotManager sets the graph snapshot manager for persistence (GR-65).
Description:
Configures the service to support graph snapshot persistence via BadgerDB. Must be called before any snapshot-related endpoints are used.
Inputs:
mgr - The snapshot manager. Can be nil to disable snapshots.
func (*Service) StorePlan ¶
func (s *Service) StorePlan(plan interface{})
StorePlan stores a change plan for later validation and preview.
Description:
Stores the plan with its associated graph ID so it can be retrieved for validation and preview. Plans expire after 1 hour.
Inputs:
plan - The change plan (must have ID field)
Thread Safety:
Safe for concurrent use.
type ServiceAdapter ¶
type ServiceAdapter struct {
// contains filtered or unexported fields
}
ServiceAdapter wraps Service to implement agent.GraphInitializer.
Description:
ServiceAdapter provides a simplified interface to Service for use by the agent graph provider. It uses default languages and excludes for graph initialization.
Thread Safety: ServiceAdapter is safe for concurrent use if the underlying Service is safe for concurrent use.
func NewServiceAdapter ¶
func NewServiceAdapter(service *Service) *ServiceAdapter
NewServiceAdapter creates a new adapter.
Description:
Creates an adapter wrapping the provided Service with default languages (go, python, javascript, typescript) and excludes (vendor, tests).
Inputs:
service - The Service to wrap.
Outputs:
*ServiceAdapter - The new adapter.
func (*ServiceAdapter) EnrichmentTraceStep ¶
func (a *ServiceAdapter) EnrichmentTraceStep(graphID string) *crs.TraceStep
EnrichmentTraceStep implements agent.EnrichmentStepProvider.
Description:
GR-76: Returns a TraceStep describing the LSP enrichment quality of the cached graph. The CRS journal uses this to record whether graph edges are backed by LSP type-aware resolution or name heuristics only.
Inputs:
graphID - The graph ID to query.
Outputs:
*crs.TraceStep - The enrichment TraceStep, or nil if no graph is cached.
Thread Safety: This method is safe for concurrent use.
func (*ServiceAdapter) InitGraph ¶
InitGraph implements agent.GraphInitializer.
Description:
Initializes a code graph by calling the underlying Service.Init with the configured languages and excludes.
Inputs:
ctx - Context for cancellation. projectRoot - Path to the project root.
Outputs:
string - The graph ID. error - Non-nil if initialization fails.
Thread Safety: This method is safe for concurrent use.
func (*ServiceAdapter) WithExcludes ¶
func (a *ServiceAdapter) WithExcludes(excludes []string) *ServiceAdapter
WithExcludes sets the exclude patterns.
Inputs:
excludes - Glob patterns to exclude.
Outputs:
*ServiceAdapter - The adapter for chaining.
func (*ServiceAdapter) WithLanguages ¶
func (a *ServiceAdapter) WithLanguages(languages []string) *ServiceAdapter
WithLanguages sets the languages to parse.
Inputs:
languages - Languages to parse.
Outputs:
*ServiceAdapter - The adapter for chaining.
type ServiceConfig ¶
type ServiceConfig struct {
// MaxInitDuration is the maximum time allowed for init operations.
// Default: 30s
MaxInitDuration time.Duration
// MaxProjectFiles is the maximum number of files to parse.
// Default: 10000
MaxProjectFiles int
// MaxProjectSize is the maximum total size of files in bytes.
// Default: 100MB
MaxProjectSize int64
// MaxCachedGraphs is the maximum number of graphs to cache.
// Default: 5
MaxCachedGraphs int
// GraphTTL is how long graphs are cached before expiry.
// Default: 0 (no expiry)
GraphTTL time.Duration
// AllowedRoots is an optional list of allowed project root prefixes.
// If empty, all paths are allowed. Security feature.
AllowedRoots []string
// LSPIdleTimeout is how long an LSP server can be idle before shutdown.
// Default: 10 minutes
LSPIdleTimeout time.Duration
// LSPStartupTimeout is the maximum time to wait for LSP server startup.
// Default: 30 seconds
LSPStartupTimeout time.Duration
// LSPRequestTimeout is the default timeout for LSP requests.
// Default: 10 seconds
LSPRequestTimeout time.Duration
// BboltDir is the directory for bbolt graph files.
// When set, frozen graphs are materialized to bbolt for fast restart.
// If empty, bbolt persistence is disabled (BadgerDB snapshots only).
// GR-77a: Phase 1a bbolt persistence.
BboltDir string
}
ServiceConfig configures the Trace service.
func DefaultServiceConfig ¶
func DefaultServiceConfig() ServiceConfig
DefaultServiceConfig returns sensible defaults.
type SimulateChangeRequest ¶
type SimulateChangeRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
ChangeType string `json:"change_type" binding:"required"`
ChangeDetails map[string]interface{} `json:"change_details" binding:"required"`
}
SimulateChangeRequest is the request for POST /v1/trace/reason/simulate_change.
type SnapshotDiffRequest ¶
type SnapshotDiffRequest struct {
// Base is the base snapshot ID for comparison.
Base string `form:"base" binding:"required"`
// Target is the target snapshot ID for comparison.
Target string `form:"target" binding:"required"`
}
SnapshotDiffRequest is the query params for GET /v1/trace/debug/graph/snapshot/diff.
type SnapshotDiffResponse ¶
type SnapshotDiffResponse struct {
// Diff contains the snapshot comparison results.
Diff *graph.SnapshotDiff `json:"diff"`
}
SnapshotDiffResponse is the response for GET /v1/trace/debug/graph/snapshot/diff. The actual diff data is in graph.SnapshotDiff, embedded directly.
type SuggestRefactorRequest ¶
type SuggestRefactorRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SymbolID string `json:"symbol_id" binding:"required"`
}
SuggestRefactorRequest is the request for POST /v1/trace/reason/suggest_refactor.
type SummarizeFileRequest ¶
type SummarizeFileRequest struct {
GraphID string `json:"graph_id" binding:"required"`
FilePath string `json:"file_path" binding:"required"`
}
SummarizeFileRequest is the request for POST /v1/trace/explore/summarize_file.
type SummarizePackageRequest ¶
type SummarizePackageRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Package string `json:"package" binding:"required"`
}
SummarizePackageRequest is the request for POST /v1/trace/explore/summarize_package.
type SymbolIndexingCoordinator ¶
type SymbolIndexingCoordinator struct {
// contains filtered or unexported fields
}
SymbolIndexingCoordinator manages background symbol indexing into Weaviate.
Description:
CRS-26l: Coordinates eager symbol indexing so that it can be triggered from both HandleInit (graph build time) and the deps factory (session creation time). Uses a content-aware graph hash to skip re-indexing when the graph hasn't changed.
Thread Safety: Safe for concurrent use. Internal mutex guards state.
func NewSymbolIndexingCoordinator ¶
func NewSymbolIndexingCoordinator(client *weaviate.Client, dataSpace string, embedClient *rag.EmbedClient) *SymbolIndexingCoordinator
NewSymbolIndexingCoordinator creates a new coordinator for background symbol indexing.
Description:
CRS-26l: Creates a coordinator that manages the lifecycle of symbol indexing goroutines. The coordinator ensures only one indexing operation runs at a time and caches the resulting SymbolStore for reuse.
Inputs:
client - Weaviate client for symbol storage. Must not be nil. dataSpace - Project isolation key for Weaviate collections. embedClient - Embedding client for vector computation. Must not be nil.
Outputs:
*SymbolIndexingCoordinator - The initialized coordinator.
Thread Safety: The returned coordinator is safe for concurrent use.
func (*SymbolIndexingCoordinator) CancelIndexing ¶
func (c *SymbolIndexingCoordinator) CancelIndexing()
CancelIndexing cancels any in-progress indexing goroutine via context.
Description:
CRS-26n: Called before re-triggering indexing on project switch to stop the old goroutine. The goroutine's context is cancelled, which causes Weaviate batch operations and embedding calls to abort promptly.
Thread Safety: Safe for concurrent use.
func (*SymbolIndexingCoordinator) GetProgress ¶
func (c *SymbolIndexingCoordinator) GetProgress() IndexingStatusResponse
GetProgress returns a snapshot of the current indexing progress.
Description:
Returns the latest IndexingStatusResponse under lock. Used by the HandleIndexingStatus endpoint for the trace-proxy to poll.
Outputs:
IndexingStatusResponse - A copy of the current progress state.
Thread Safety: Safe for concurrent use.
func (*SymbolIndexingCoordinator) GetSymbolStore ¶
func (c *SymbolIndexingCoordinator) GetSymbolStore() *rag.SymbolStore
GetSymbolStore returns the cached SymbolStore from the last successful indexing.
Description:
CRS-26l: Returns the SymbolStore populated by the most recent successful TriggerIndexing call. Returns nil if indexing hasn't completed yet.
Outputs:
*rag.SymbolStore - The cached store, or nil if not yet available.
Thread Safety: Safe for concurrent use.
func (*SymbolIndexingCoordinator) ResetState ¶
func (c *SymbolIndexingCoordinator) ResetState()
ResetState clears lastIndexedHash, lastStore, and progress so the next TriggerIndexing doesn't short-circuit on a stale hash.
Description:
CRS-26n: Called after CancelIndexing when switching projects. Without this, a project with an identical hash to the previous one would be skipped because lastIndexedHash still matches.
Thread Safety: Safe for concurrent use.
func (*SymbolIndexingCoordinator) TriggerIndexing ¶
func (c *SymbolIndexingCoordinator) TriggerIndexing(graphID string, cached *CachedGraph)
TriggerIndexing starts background symbol indexing for the given graph.
Description:
CRS-26l: Fire-and-forget goroutine that indexes symbols from the graph's SymbolIndex into Weaviate. Uses a content-aware hash to skip if already indexed. Only one indexing operation runs at a time — concurrent calls with the same hash are deduplicated.
Inputs:
graphID - The graph identifier (used for hash computation). cached - The cached graph containing the SymbolIndex. Must not be nil.
Thread Safety: Safe for concurrent use. Guards against concurrent indexing.
type SymbolInfo ¶
type SymbolInfo struct {
// ID is the unique symbol identifier.
ID string `json:"id"`
// Name is the symbol name.
Name string `json:"name"`
// Kind is the symbol kind (function, struct, interface, etc.).
Kind string `json:"kind"`
// FilePath is the relative path to the file.
FilePath string `json:"file_path"`
// StartLine is the 1-indexed line where the symbol starts.
StartLine int `json:"start_line"`
// EndLine is the 1-indexed line where the symbol ends.
EndLine int `json:"end_line"`
// Signature is the type signature.
Signature string `json:"signature,omitempty"`
// DocComment is the documentation comment.
DocComment string `json:"doc_comment,omitempty"`
// Package is the package name.
Package string `json:"package,omitempty"`
// Exported indicates if the symbol is publicly visible.
Exported bool `json:"exported"`
}
SymbolInfo is a simplified symbol representation for API responses.
func SymbolInfoFromAST ¶
func SymbolInfoFromAST(s *ast.Symbol) *SymbolInfo
SymbolInfoFromAST converts an ast.Symbol to SymbolInfo.
type SymbolRequest ¶
type SymbolRequest struct {
// GraphID is the graph to query. Required.
GraphID string `form:"graph_id" binding:"required"`
}
SymbolRequest is the query params for GET /v1/trace/symbol/:id.
type SymbolResponse ¶
type SymbolResponse struct {
// Symbol is the detailed symbol information.
Symbol *SymbolInfo `json:"symbol"`
}
SymbolResponse is the response for GET /v1/trace/symbol/:id.
type ToolDefinition ¶
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Category string `json:"category"`
Parameters []ToolParam `json:"parameters"`
Returns string `json:"returns"`
Performance string `json:"performance"`
}
ToolDefinition represents a tool available to the agent.
type ToolParam ¶
type ToolParam struct {
Name string `json:"name"`
Type string `json:"type"`
Description string `json:"description"`
Required bool `json:"required"`
Default string `json:"default,omitempty"`
Enum []string `json:"enum,omitempty"`
}
ToolParam represents a parameter in a tool definition.
type ToolRegistry ¶
type ToolRegistry struct {
// contains filtered or unexported fields
}
ToolRegistry provides tool definitions for agent discovery.
Thread Safety:
ToolRegistry is immutable after initialization and safe for concurrent use.
func NewToolRegistry ¶
func NewToolRegistry() *ToolRegistry
NewToolRegistry creates a registry with all available tools.
func (*ToolRegistry) GetTools ¶
func (r *ToolRegistry) GetTools() []ToolDefinition
GetTools returns all available tool definitions.
func (*ToolRegistry) GetToolsByCategory ¶
func (r *ToolRegistry) GetToolsByCategory(category string) []ToolDefinition
GetToolsByCategory returns tools filtered by category.
type ToolsResponse ¶
type ToolsResponse struct {
Tools []ToolDefinition `json:"tools"`
}
ToolsResponse is the response for GET /v1/trace/tools.
type TraceDataFlowRequest ¶
type TraceDataFlowRequest struct {
GraphID string `json:"graph_id" binding:"required"`
SourceID string `json:"source_id" binding:"required"`
MaxHops int `json:"max_hops"`
IncludeCode bool `json:"include_code"`
}
TraceDataFlowRequest is the request for POST /v1/trace/explore/data_flow.
type TraceErrorFlowRequest ¶
type TraceErrorFlowRequest struct {
GraphID string `json:"graph_id" binding:"required"`
Scope string `json:"scope" binding:"required"`
MaxHops int `json:"max_hops"`
}
TraceErrorFlowRequest is the request for POST /v1/trace/explore/error_flow.
type ValidateChangeRequest ¶
type ValidateChangeRequest struct {
Code string `json:"code" binding:"required"`
Language string `json:"language" binding:"required"`
}
ValidateChangeRequest is the request for POST /v1/trace/reason/validate_change.
type ValidatePlanRequest ¶
type ValidatePlanRequest struct {
PlanID string `json:"plan_id" binding:"required"`
}
ValidatePlanRequest is the request for POST /v1/trace/coordinate/validate_plan.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agent provides a state-machine-driven agent orchestration system.
|
Package agent provides a state-machine-driven agent orchestration system. |
|
classifier
Package classifier provides query classification for tool forcing decisions.
|
Package classifier provides query classification for tool forcing decisions. |
|
context
Package context provides context management for the agent loop.
|
Package context provides context management for the agent loop. |
|
control
Package control provides control flow hardening for the agent loop.
|
Package control provides control flow hardening for the agent loop. |
|
events
Package events provides event types and handling for the agent loop.
|
Package events provides event types and handling for the agent loop. |
|
grounding
Package grounding provides anti-hallucination validation for LLM responses.
|
Package grounding provides anti-hallucination validation for LLM responses. |
|
llm
Package llm provides the LLM client interface for the agent loop.
|
Package llm provides the LLM client interface for the agent loop. |
|
mcts
Package mcts implements Monte Carlo Tree Search-inspired plan tree reasoning.
|
Package mcts implements Monte Carlo Tree Search-inspired plan tree reasoning. |
|
mcts/algorithms
Package algorithms provides pure function implementations for the MCTS system.
|
Package algorithms provides pure function implementations for the MCTS system. |
|
mcts/crs
Package crs provides the Code Reasoning State (CRS) - the central mutable state container for the Aleutian Hybrid MCTS system.
|
Package crs provides the Code Reasoning State (CRS) - the central mutable state container for the Aleutian Hybrid MCTS system. |
|
mcts/crs/indexes
Package indexes provides the 6 index implementations for CRS.
|
Package indexes provides the 6 index implementations for CRS. |
|
phases
Package phases implements the agent state machine phases.
|
Package phases implements the agent state machine phases. |
|
providers
Package providers defines provider-agnostic interfaces and factories for LLM backends used by the Trace agent.
|
Package providers defines provider-agnostic interfaces and factories for LLM backends used by the Trace agent. |
|
providers/egress
Package egress provides data egress control, audit trail, and compliance enforcement for LLM provider calls.
|
Package egress provides data egress control, audit trail, and compliance enforcement for LLM provider calls. |
|
routing
Package routing provides tool selection using a fast micro LLM.
|
Package routing provides tool selection using a fast micro LLM. |
|
safety
Package safety provides safety gate functionality for the agent loop.
|
Package safety provides safety gate functionality for the agent loop. |
|
Package analysis provides code analysis tools for Trace.
|
Package analysis provides code analysis tools for Trace. |
|
Package ast provides types and interfaces for language-agnostic AST parsing.
|
Package ast provides types and interfaces for language-agnostic AST parsing. |
|
Package bridge provides a reusable HTTP client wrapping all trace tool endpoints.
|
Package bridge provides a reusable HTTP client wrapping all trace tool endpoints. |
|
Package cache provides ephemeral graph caching with LRU eviction.
|
Package cache provides ephemeral graph caching with LRU eviction. |
|
Package cancel provides hierarchical cancellation for the CRS algorithm system.
|
Package cancel provides hierarchical cancellation for the CRS algorithm system. |
|
cli
|
|
|
tools
Package tools provides CLI tools for graph queries.
|
Package tools provides CLI tools for graph queries. |
|
tools/file
Package file provides file operation tools for the Aleutian Trace CLI.
|
Package file provides file operation tools for the Aleutian Trace CLI. |
|
tools/validate
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. |
|
Package config provides configuration loading for the trace service.
|
Package config provides configuration loading for the trace service. |
|
Package context provides the Context Assembler for Trace.
|
Package context provides the Context Assembler for Trace. |
|
Package coordinate provides multi-file change coordination for Trace.
|
Package coordinate provides multi-file change coordination for Trace. |
|
Package dag provides a DAG-based execution framework for Trace pipelines.
|
Package dag provides a DAG-based execution framework for Trace pipelines. |
|
nodes
Package nodes provides concrete DAG node implementations for Trace pipelines.
|
Package nodes provides concrete DAG node implementations for Trace pipelines. |
|
Package diff provides diff parsing, rendering, and application for code review.
|
Package diff provides diff parsing, rendering, and application for code review. |
|
Package eval provides the evaluation framework for Trace components.
|
Package eval provides the evaluation framework for Trace components. |
|
ab
Package ab provides A/B testing harness for comparing algorithm implementations.
|
Package ab provides A/B testing harness for comparing algorithm implementations. |
|
benchmark
Package benchmark provides performance benchmarking for evaluable components.
|
Package benchmark provides performance benchmarking for evaluable components. |
|
chaos
Package chaos provides fault injection for resilience testing.
|
Package chaos provides fault injection for resilience testing. |
|
regression
Package regression provides CI/CD regression detection gates.
|
Package regression provides CI/CD regression detection gates. |
|
telemetry
Package telemetry provides observability infrastructure for the evaluation framework.
|
Package telemetry provides observability infrastructure for the evaluation framework. |
|
Package explore provides high-level exploration tools for code analysis.
|
Package explore provides high-level exploration tools for code analysis. |
|
Package git provides git-aware cache invalidation for Trace.
|
Package git provides git-aware cache invalidation for Trace. |
|
Package graph provides code relationship graph types and operations.
|
Package graph provides code relationship graph types and operations. |
|
Package impact provides unified change impact analysis for Trace.
|
Package impact provides unified change impact analysis for Trace. |
|
Package index provides in-memory indexing for code symbols.
|
Package index provides in-memory indexing for code symbols. |
|
Package lint provides integration with external linters for code validation.
|
Package lint provides integration with external linters for code validation. |
|
Package lock provides file locking capabilities for safe concurrent file operations.
|
Package lock provides file locking capabilities for safe concurrent file operations. |
|
Package lsp provides Language Server Protocol integration for Trace.
|
Package lsp provides Language Server Protocol integration for Trace. |
|
Package manifest provides file manifest and hash tracking for cache invalidation.
|
Package manifest provides file manifest and hash tracking for cache invalidation. |
|
Package patterns provides design pattern and anti-pattern detection for Trace.
|
Package patterns provides design pattern and anti-pattern detection for Trace. |
|
Package rag provides graph-backed entity resolution for parameter extraction.
|
Package rag provides graph-backed entity resolution for parameter extraction. |
|
Package reason provides tools for reasoning about code changes.
|
Package reason provides tools for reasoning about code changes. |
|
Package safety provides security analysis tools for Trace.
|
Package safety provides security analysis tools for Trace. |
|
trust
Package trust provides trust boundary analysis for security scanning.
|
Package trust provides trust boundary analysis for security scanning. |
|
trust_flow
Package trust_flow provides trust flow analysis for security scanning.
|
Package trust_flow provides trust flow analysis for security scanning. |
|
Package seeder provides library documentation seeding for Trace.
|
Package seeder provides library documentation seeding for Trace. |
|
storage
|
|
|
badger
Package badger provides factory functions and configuration for BadgerDB.
|
Package badger provides factory functions and configuration for BadgerDB. |
|
nats
Package nats provides a NATS JetStream client wrapper for CRS state persistence.
|
Package nats provides a NATS JetStream client wrapper for CRS state persistence. |
|
Package tdg provides Test-Driven Generation (TDG) for Trace.
|
Package tdg provides Test-Driven Generation (TDG) for Trace. |
|
Package telemetry provides OpenTelemetry-based observability for Trace.
|
Package telemetry provides OpenTelemetry-based observability for Trace. |
|
Package transaction provides atomic file operations with git-based rollback.
|
Package transaction provides atomic file operations with git-based rollback. |
|
Package tui provides terminal user interface components for interactive review.
|
Package tui provides terminal user interface components for interactive review. |
|
Package validation provides input validation for untrusted data.
|
Package validation provides input validation for untrusted data. |
|
Package verify provides hash-verified operations for code graphs.
|
Package verify provides hash-verified operations for code graphs. |
|
Package weaviate provides a resilient Weaviate client with circuit breaker, retry with backoff, and graceful degradation.
|
Package weaviate provides a resilient Weaviate client with circuit breaker, retry with backoff, and graceful degradation. |