agent

package
v1.0.0 Latest Latest
Warning

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

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

Documentation

Overview

Package agent provides a state-machine-driven agent orchestration system.

The agent loop coordinates exploration tools, safety checks, and LLM interactions to answer user queries about codebases. It implements a finite state machine with phases: IDLE, INIT, PLAN, EXECUTE, REFLECT, CLARIFY, DEGRADED, COMPLETE, and ERROR.

Thread Safety:

All exported types in this package are designed for concurrent use.
Sessions are protected by internal synchronization.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidTransition indicates an invalid state transition was attempted.
	ErrInvalidTransition = errors.New("invalid state transition")

	// ErrSessionNotFound indicates the requested session does not exist.
	ErrSessionNotFound = errors.New("session not found")

	// ErrSessionTerminated indicates the session is already in a terminal state.
	ErrSessionTerminated = errors.New("session already terminated")

	// ErrSessionInProgress indicates an operation is already in progress.
	ErrSessionInProgress = errors.New("session operation in progress")

	// ErrMaxStepsExceeded indicates the maximum step limit was reached.
	ErrMaxStepsExceeded = errors.New("maximum steps exceeded")

	// ErrMaxTokensExceeded indicates the token budget was exhausted.
	ErrMaxTokensExceeded = errors.New("token budget exhausted")

	// ErrTimeout indicates an operation timed out.
	ErrTimeout = errors.New("operation timed out")

	// ErrCanceled indicates the operation was canceled via context.
	ErrCanceled = errors.New("operation canceled")

	// ErrInitFailed indicates Trace initialization failed.
	ErrInitFailed = errors.New("code buddy initialization failed")

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

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

	// ErrLLMUnavailable indicates the LLM service is unavailable.
	ErrLLMUnavailable = errors.New("LLM service unavailable")

	// ErrSafetyBlocked indicates a safety check blocked the operation.
	ErrSafetyBlocked = errors.New("operation blocked by safety check")

	// ErrInvalidSession indicates the session configuration is invalid.
	ErrInvalidSession = errors.New("invalid session configuration")

	// ErrEmptyQuery indicates the query is empty.
	ErrEmptyQuery = errors.New("query must not be empty")

	// ErrNotInClarifyState indicates Continue was called but state is not CLARIFY.
	ErrNotInClarifyState = errors.New("session not in CLARIFY state")

	// ErrAwaitingClarification indicates the agent is waiting for user clarification.
	// NOTE: This is used for flow control in the agent loop, not as a true error.
	// The loop returns this when it needs to pause for user input via Continue().
	ErrAwaitingClarification = errors.New("awaiting user clarification")
)

Sentinel errors for the agent package.

View Source
var DefaultStateMachine = NewStateMachine()

DefaultStateMachine is the shared state machine instance.

View Source
var ValidContextEvictionPolicies = []string{"lru", "relevance", "hybrid"}

ValidContextEvictionPolicies contains valid eviction policy values.

View Source
var ValidDegradationModes = []string{"fallback", "fail", "ask"}

ValidDegradationModes contains valid degradation mode values.

View Source
var ValidQueryScopes = []string{"file", "function", "package", "project"}

ValidQueryScopes contains all valid query scopes.

View Source
var ValidQueryTypes = []string{"explore", "modify", "explain", "debug", "refactor"}

ValidQueryTypes contains all valid query intent types.

View Source
var ValidSafetyCheckScopes = []string{"changed_files", "blast_radius", "full"}

ValidSafetyCheckScopes contains valid safety check scope values.

Functions

func CanTransition

func CanTransition(from, to AgentState) bool

CanTransition is a convenience function using the default state machine.

func RegisterSessionCleanupHook

func RegisterSessionCleanupHook(name string, fn SessionCleanupFunc)

RegisterSessionCleanupHook registers a cleanup function to be called when sessions are closed.

Description:

Phases and other components can register cleanup functions that will be
called when CloseSession is invoked. This allows components to clean up
session-specific state without creating import cycles.

Inputs:

name - Unique name for this hook (used for debugging and unregistration).
fn - The cleanup function to call.

Thread Safety: Safe for concurrent use.

func Transition

func Transition(session *Session, to AgentState) error

Transition is a convenience function using the default state machine.

func UnregisterSessionCleanupHook

func UnregisterSessionCleanupHook(name string)

UnregisterSessionCleanupHook removes a cleanup hook.

Inputs:

name - The name of the hook to remove.

Thread Safety: Safe for concurrent use.

Types

type AgentError

type AgentError struct {
	// Code is a machine-readable error code.
	Code string `json:"code"`

	// Message is a human-readable error message.
	Message string `json:"message"`

	// Details contains additional error context.
	Details string `json:"details,omitempty"`

	// Recoverable indicates if the error might be resolved by retry.
	Recoverable bool `json:"recoverable"`

	// Step is the step where the error occurred.
	Step int `json:"step,omitempty"`
}

AgentError contains error information for the ERROR state.

AgentError implements the error interface, allowing it to be used as a standard Go error while providing structured error information.

func (*AgentError) Error

func (e *AgentError) Error() string

Error implements the error interface.

Outputs:

string - The error message, optionally with code prefix

func (*AgentError) Unwrap

func (e *AgentError) Unwrap() error

Unwrap returns nil as AgentError does not wrap another error.

Outputs:

error - Always nil

type AgentLoop

type AgentLoop interface {
	// Run starts a new session and processes a query.
	//
	// Description:
	//   Creates a new session, initializes the graph, assembles context,
	//   and executes the agent loop until completion or clarification needed.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   session - The session to run (must be in IDLE state).
	//   query - The user's query.
	//
	// Outputs:
	//   *RunResult - The execution result.
	//   error - Non-nil if an unrecoverable error occurred.
	//
	// Thread Safety: This method is safe for concurrent use with different sessions.
	Run(ctx context.Context, session *Session, query string) (*RunResult, error)

	// Continue resumes a session from CLARIFY state.
	//
	// Description:
	//   Processes the user's clarification response and continues execution.
	//   Only valid when session is in CLARIFY state.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   sessionID - The session ID to continue.
	//   clarification - The user's clarification response.
	//
	// Outputs:
	//   *RunResult - The execution result.
	//   error - Non-nil if session not found or not in CLARIFY state.
	//
	// Thread Safety: This method is safe for concurrent use.
	Continue(ctx context.Context, sessionID string, clarification string) (*RunResult, error)

	// Abort terminates a running session.
	//
	// Description:
	//   Stops a session that is currently executing. Does not affect
	//   sessions that are already in terminal states.
	//
	// Inputs:
	//   ctx - Context for the abort operation.
	//   sessionID - The session ID to abort.
	//
	// Outputs:
	//   error - Non-nil if session not found.
	//
	// Thread Safety: This method is safe for concurrent use.
	Abort(ctx context.Context, sessionID string) error

	// GetState returns the current state of a session.
	//
	// Inputs:
	//   sessionID - The session ID to query.
	//
	// Outputs:
	//   *SessionState - The session state.
	//   error - Non-nil if session not found.
	//
	// Thread Safety: This method is safe for concurrent use.
	GetState(sessionID string) (*SessionState, error)

	// GetSession returns the full session object.
	//
	// Description:
	//   Returns the complete Session for operations that need access
	//   to CRS, trace recorder, or other internal state not exposed
	//   through SessionState.
	//
	// Inputs:
	//   sessionID - The session ID to retrieve.
	//
	// Outputs:
	//   *Session - The full session object.
	//   error - Non-nil if session not found.
	//
	// Thread Safety: This method is safe for concurrent use.
	GetSession(sessionID string) (*Session, error)

	// ListSessions returns a summary of all active sessions.
	//
	// Description:
	//   Returns basic info about all sessions in the session store.
	//   Used by debug endpoints to show CRS state across sessions.
	//
	// Outputs:
	//   []*SessionSummary - List of session summaries.
	//
	// Thread Safety: This method is safe for concurrent use.
	ListSessions() []*SessionSummary

	// CloseSession permanently closes a session and releases all resources.
	//
	// Description:
	//   Closes a session that will no longer be used. This cleans up all
	//   session-specific state including UCB1 contexts, caches, and removes
	//   the session from the session store. Unlike Abort, this is for
	//   intentional cleanup when a session is definitively finished.
	//
	//   Call this when:
	//   - User explicitly ends the conversation
	//   - Session timeout for inactive sessions
	//   - Application shutdown cleanup
	//
	// Inputs:
	//   sessionID - The session ID to close.
	//
	// Outputs:
	//   error - Non-nil if session not found.
	//
	// Thread Safety: This method is safe for concurrent use.
	CloseSession(sessionID string) error
}

AgentLoop defines the interface for running agent sessions.

The agent loop orchestrates the state machine, phases, tools, and LLM interactions to process user queries about codebases.

type AgentState

type AgentState string

AgentState represents a state in the agent loop state machine.

Valid state transitions are enforced by the state machine. Invalid transitions return ErrInvalidTransition.

const (
	// StateIdle is the initial state before any query is received.
	StateIdle AgentState = "IDLE"

	// StateInit initializes the Trace graph for the project.
	StateInit AgentState = "INIT"

	// StatePlan assembles initial context and classifies the query.
	StatePlan AgentState = "PLAN"

	// StateExecute is the main tool-use loop.
	StateExecute AgentState = "EXECUTE"

	// StateReflect enables self-correction after hitting step limits.
	StateReflect AgentState = "REFLECT"

	// StateClarify requests additional input from the user.
	StateClarify AgentState = "CLARIFY"

	// StateDegraded operates with limited tools when Trace unavailable.
	StateDegraded AgentState = "DEGRADED"

	// StateComplete indicates successful completion.
	StateComplete AgentState = "COMPLETE"

	// StateError indicates an unrecoverable error occurred.
	StateError AgentState = "ERROR"
)

func AllStates

func AllStates() []AgentState

AllStates returns all valid agent states.

Outputs:

[]AgentState - Slice containing all 9 valid states

func (AgentState) IsActive

func (s AgentState) IsActive() bool

IsActive returns true if the state allows continued execution.

Outputs:

bool - True if state is INIT, PLAN, EXECUTE, REFLECT, or DEGRADED

func (AgentState) IsTerminal

func (s AgentState) IsTerminal() bool

IsTerminal returns true if the state is a terminal state (COMPLETE or ERROR).

Outputs:

bool - True if state is COMPLETE or ERROR

func (AgentState) String

func (s AgentState) String() string

String returns the string representation of the state.

Outputs:

string - The state as a string (e.g., "IDLE", "EXECUTE")

type AssembledContext

type AssembledContext struct {
	// SystemPrompt is the system instructions.
	SystemPrompt string `json:"system_prompt"`

	// CodeContext contains code snippets.
	CodeContext []CodeEntry `json:"code_context"`

	// LibraryDocs contains library documentation.
	LibraryDocs []DocEntry `json:"library_docs"`

	// ToolResults contains recent tool outputs.
	ToolResults []ToolResult `json:"tool_results"`

	// ConversationHistory contains message history.
	ConversationHistory []Message `json:"conversation_history"`

	// TotalTokens is the current token count.
	TotalTokens int `json:"total_tokens"`

	// Relevance maps entry IDs to relevance scores.
	Relevance map[string]float64 `json:"relevance"`
}

AssembledContext represents the current context window for the LLM.

func (*AssembledContext) EnsureInitialized

func (c *AssembledContext) EnsureInitialized()

EnsureInitialized ensures all slice/map fields are non-nil. Call this after unmarshalling or constructing AssembledContext.

Thread Safety: This method is NOT safe for concurrent use.

func (*AssembledContext) GetRelevance

func (c *AssembledContext) GetRelevance(entryID string) float64

GetRelevance returns the relevance score for an entry ID. Returns 0.0 if the entry ID doesn't exist or if Relevance map is nil.

Thread Safety: This method is NOT safe for concurrent use.

func (*AssembledContext) SetRelevance

func (c *AssembledContext) SetRelevance(entryID string, score float64)

SetRelevance sets the relevance score for an entry ID. Initializes the Relevance map if nil (CT-001 fix).

Thread Safety: This method is NOT safe for concurrent use.

type ClarifyRequest

type ClarifyRequest struct {
	// Question is what the agent needs to know.
	Question string `json:"question"`

	// Options are suggested clarification options.
	Options []string `json:"options,omitempty"`

	// Context explains why clarification is needed.
	Context string `json:"context,omitempty"`
}

ClarifyRequest contains details when agent needs clarification.

type CodeEntry

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

	// FilePath is the relative path to the file.
	FilePath string `json:"file_path"`

	// SymbolName is the symbol name if applicable.
	SymbolName string `json:"symbol_name,omitempty"`

	// Content is the code content.
	Content string `json:"content"`

	// Tokens is the estimated token count.
	Tokens int `json:"tokens"`

	// Relevance is the relevance score (0.0-1.0).
	Relevance float64 `json:"relevance"`

	// AddedAt is the step when this was added.
	AddedAt int `json:"added_at"`

	// Reason explains why this was included.
	Reason string `json:"reason"`
}

CodeEntry represents a code snippet in context.

type DefaultAgentLoop

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

DefaultAgentLoop implements the AgentLoop interface.

Thread Safety: DefaultAgentLoop is safe for concurrent use.

func NewDefaultAgentLoop

func NewDefaultAgentLoop(opts ...DefaultLoopOption) *DefaultAgentLoop

NewDefaultAgentLoop creates a new agent loop.

Description:

Creates an agent loop with the specified options. If no session store
is provided, uses an in-memory store. If no phase registry is provided,
phases must be registered separately.

Inputs:

opts - Configuration options.

Outputs:

*DefaultAgentLoop - The configured agent loop.

func (*DefaultAgentLoop) Abort

func (l *DefaultAgentLoop) Abort(ctx context.Context, sessionID string) error

Abort implements AgentLoop.

Description:

Terminates a running session by transitioning it to ERROR state.
If the session is already in a terminal state, this is a no-op.

Inputs:

ctx - Context for the abort operation.
sessionID - The session ID to abort.

Outputs:

error - Non-nil if session not found.

Thread Safety: This method is safe for concurrent use.

func (*DefaultAgentLoop) CloseSession

func (l *DefaultAgentLoop) CloseSession(sessionID string) error

CloseSession implements AgentLoop.

Description:

Permanently closes a session and releases all resources. This removes
the session from the session store and runs all registered cleanup hooks.
Unlike Abort, this is for intentional cleanup when a session is
definitively finished (user ends conversation, timeout, or shutdown).

Inputs:

sessionID - The session ID to close.

Outputs:

error - Non-nil if session not found.

Thread Safety: This method is safe for concurrent use.

func (*DefaultAgentLoop) Continue

func (l *DefaultAgentLoop) Continue(ctx context.Context, sessionID string, clarification string) (*RunResult, error)

Continue implements AgentLoop.

Description:

Resumes execution after user provides clarification or follow-up question.
Accepts sessions in CLARIFY state (waiting for clarification) or COMPLETE
state (for multi-turn follow-up questions).

For CLARIFY state: Provides the requested clarification and continues.
For COMPLETE state: Treats input as a follow-up question with conversation
history preserved, enabling multi-turn conversations.

Inputs:

ctx - Context for cancellation and timeout.
sessionID - The session ID to continue.
clarification - The user's clarification or follow-up question.

Outputs:

*RunResult - The execution result.
error - Non-nil if session not found or invalid state.

Thread Safety: This method is safe for concurrent use.

func (*DefaultAgentLoop) GetSession

func (l *DefaultAgentLoop) GetSession(sessionID string) (*Session, error)

GetSession implements AgentLoop.

Description:

Returns the full session object for operations that need access
to CRS, trace recorder, or other internal state.

Inputs:

sessionID - The session ID to retrieve.

Outputs:

*Session - The full session object.
error - Non-nil if session not found.

Thread Safety: This method is safe for concurrent use.

func (*DefaultAgentLoop) GetState

func (l *DefaultAgentLoop) GetState(sessionID string) (*SessionState, error)

GetState implements AgentLoop.

Description:

Returns the current state of a session without modifying it.

Inputs:

sessionID - The session ID to query.

Outputs:

*SessionState - The session state.
error - Non-nil if session not found.

Thread Safety: This method is safe for concurrent use.

func (*DefaultAgentLoop) ListSessions

func (l *DefaultAgentLoop) ListSessions() []*SessionSummary

ListSessions implements AgentLoop.

Description:

Returns a summary of all active sessions for debug endpoints.

Outputs:

[]*SessionSummary - List of session summaries.

Thread Safety: This method is safe for concurrent use.

func (*DefaultAgentLoop) Run

func (l *DefaultAgentLoop) Run(ctx context.Context, session *Session, query string) (*RunResult, error)

Run implements AgentLoop.

Description:

Executes the agent loop for a new query. The session must be in IDLE state.
The loop runs until reaching a terminal state (COMPLETE, ERROR) or
CLARIFY state (which pauses for user input).

Inputs:

ctx - Context for cancellation and timeout.
session - The session to run.
query - The user's query.

Outputs:

*RunResult - The execution result.
error - Non-nil if an unrecoverable error occurred.

Thread Safety: This method is safe for concurrent use with different sessions.

type DefaultLoopOption

type DefaultLoopOption func(*DefaultAgentLoop)

DefaultLoopOption configures a DefaultAgentLoop.

func WithDependenciesFactory

func WithDependenciesFactory(factory DependenciesFactory) DefaultLoopOption

WithDependenciesFactory sets a factory for creating per-session dependencies.

Description:

When set, the factory is called to create Dependencies for each
phase execution. This is preferred over WithPhaseDependencies
for production use as it allows per-session configuration.

Inputs:

factory - The dependencies factory.

Outputs:

DefaultLoopOption - The configuration function.

func WithMaxConcurrentSessions

func WithMaxConcurrentSessions(max int) DefaultLoopOption

WithMaxConcurrentSessions limits concurrent sessions.

Inputs:

max - Maximum concurrent sessions (0 = unlimited).

Outputs:

DefaultLoopOption - The configuration function.

func WithPhaseDependencies

func WithPhaseDependencies(deps any) DefaultLoopOption

WithPhaseDependencies sets static dependencies passed to phases.

Description:

Sets static dependencies that are passed to all phases. Use
WithDependenciesFactory for per-session dependency creation.

Inputs:

deps - Dependencies for phase execution.

Outputs:

DefaultLoopOption - The configuration function.

func WithPhaseRegistry

func WithPhaseRegistry(registry PhaseRegistry) DefaultLoopOption

WithPhaseRegistry sets the phase registry.

Inputs:

registry - The phase registry implementation.

Outputs:

DefaultLoopOption - The configuration function.

func WithSessionStore

func WithSessionStore(store SessionStore) DefaultLoopOption

WithSessionStore sets the session store.

Inputs:

store - The session store implementation.

Outputs:

DefaultLoopOption - The configuration function.

type DefaultPhaseRegistry

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

DefaultPhaseRegistry implements PhaseRegistry.

Description:

DefaultPhaseRegistry maps AgentState values to PhaseExecutor implementations.
It provides thread-safe access to registered phases.

Thread Safety: DefaultPhaseRegistry is safe for concurrent use.

func NewPhaseRegistry

func NewPhaseRegistry() *DefaultPhaseRegistry

NewPhaseRegistry creates a new phase registry.

Description:

Creates an empty registry. Use Register() to add phases.

Outputs:

*DefaultPhaseRegistry - The new registry.

func (*DefaultPhaseRegistry) Count

func (r *DefaultPhaseRegistry) Count() int

Count returns the number of registered phases.

Outputs:

int - The number of registered phases.

Thread Safety: This method is safe for concurrent use.

func (*DefaultPhaseRegistry) GetPhase

func (r *DefaultPhaseRegistry) GetPhase(state AgentState) (PhaseExecutor, bool)

GetPhase implements PhaseRegistry.

Description:

Returns the phase registered for the given state. Returns false
if no phase is registered.

Inputs:

state - The state to get the phase for.

Outputs:

PhaseExecutor - The phase executor, or nil if not found.
bool - True if a phase was found.

Thread Safety: This method is safe for concurrent use.

func (*DefaultPhaseRegistry) MustGetPhase

func (r *DefaultPhaseRegistry) MustGetPhase(state AgentState) PhaseExecutor

MustGetPhase returns the phase for a state or panics.

Description:

Like GetPhase but panics if no phase is registered. Use only when
you know the phase must exist.

Inputs:

state - The state to get the phase for.

Outputs:

PhaseExecutor - The phase executor.

Thread Safety: This method is safe for concurrent use.

func (*DefaultPhaseRegistry) Register

func (r *DefaultPhaseRegistry) Register(state AgentState, executor PhaseExecutor)

Register adds a phase executor for a state.

Description:

Associates a PhaseExecutor with an AgentState. The executor will
be called when the agent enters that state. Overwrites any previously
registered executor for the state.

Inputs:

state - The state to register the phase for.
executor - The phase executor.

Thread Safety: This method is safe for concurrent use.

func (*DefaultPhaseRegistry) States

func (r *DefaultPhaseRegistry) States() []AgentState

States returns all registered states in sorted order.

Description:

Returns a list of all states that have registered phases.
The list is sorted for deterministic output.

Outputs:

[]AgentState - All registered states, sorted.

Thread Safety: This method is safe for concurrent use.

type DependenciesFactory

type DependenciesFactory interface {
	// Create builds Dependencies for the given session and query.
	//
	// Inputs:
	//   session - The current session.
	//   query - The user's query.
	//
	// Outputs:
	//   any - The dependencies (typically *phases.Dependencies).
	//   error - Non-nil if creation failed.
	Create(session *Session, query string) (any, error)
}

DependenciesFactory creates Dependencies for a session.

Description:

DependenciesFactory is called by the agent loop to create Dependencies
for each phase execution. This allows per-session configuration of
dependencies while reusing shared components like LLM clients.

type DocEntry

type DocEntry struct {
	// ID is a unique identifier.
	ID string `json:"id"`

	// Library is the library name.
	Library string `json:"library"`

	// Symbol is the symbol path.
	Symbol string `json:"symbol"`

	// Content is the documentation content.
	Content string `json:"content"`

	// Tokens is the estimated token count.
	Tokens int `json:"tokens"`
}

DocEntry represents a library documentation entry.

type EnrichmentStepProvider

type EnrichmentStepProvider interface {
	// EnrichmentTraceStep returns a TraceStep for the given graph's enrichment stats.
	EnrichmentTraceStep(graphID string) *crs.TraceStep
}

EnrichmentStepProvider provides enrichment TraceStep data.

Description:

GR-76: Optional interface that GraphInitializer implementations can also
implement to provide LSP enrichment statistics. ServiceGraphProvider
checks for this via type assertion.

Thread Safety: Implementations must be safe for concurrent use.

type GraphInitializer

type GraphInitializer interface {
	// InitGraph initializes a code graph for a project.
	//
	// Inputs:
	//   ctx - Context for cancellation.
	//   projectRoot - Path to the project root.
	//
	// Outputs:
	//   string - The graph ID.
	//   error - Non-nil if initialization fails.
	InitGraph(ctx context.Context, projectRoot string) (string, error)
}

GraphInitializer defines the initialization capability needed from a service.

Description:

This interface abstracts the graph initialization capability.
Implementations can wrap trace.Service or provide mock behavior.

type GraphStats

type GraphStats struct {
	// FilesParsed is the number of files in the graph.
	FilesParsed int `json:"files_parsed"`

	// SymbolsExtracted is the number of symbols extracted.
	SymbolsExtracted int `json:"symbols_extracted"`

	// EdgesBuilt is the number of edges in the graph.
	EdgesBuilt int `json:"edges_built"`

	// ParseTimeMs is how long graph construction took.
	ParseTimeMs int64 `json:"parse_time_ms"`
}

GraphStats contains statistics about the Trace graph.

type HistoryEntry

type HistoryEntry struct {
	// Step is the 0-indexed step number.
	Step int `json:"step"`

	// Type describes what happened (plan, tool_call, reflection, etc.).
	Type string `json:"type"`

	// State is the agent state at this step.
	State AgentState `json:"state"`

	// Query is the user's query (for plan entries).
	Query string `json:"query,omitempty"`

	// ToolName is the tool that was invoked (for tool_call entries).
	ToolName string `json:"tool_name,omitempty"`

	// Input contains the tool input or prompt.
	Input string `json:"input,omitempty"`

	// Output contains the tool result or LLM response.
	Output string `json:"output,omitempty"`

	// TokensUsed is the tokens consumed in this step.
	TokensUsed int `json:"tokens_used,omitempty"`

	// DurationMs is how long this step took in milliseconds.
	DurationMs int64 `json:"duration_ms"`

	// Timestamp is when this step occurred (Unix milliseconds UTC).
	Timestamp int64 `json:"timestamp"`

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

	// ClarificationPrompt is the prompt shown when entering CLARIFY state.
	ClarificationPrompt string `json:"clarification_prompt,omitempty"`
}

HistoryEntry records a single step in the agent's execution history.

type InMemorySessionStore

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

InMemorySessionStore is a simple in-memory session store.

Thread Safety: InMemorySessionStore is safe for concurrent use.

func NewInMemorySessionStore

func NewInMemorySessionStore() *InMemorySessionStore

NewInMemorySessionStore creates a new in-memory session store.

Outputs:

*InMemorySessionStore - The new store.

func (*InMemorySessionStore) Delete

func (s *InMemorySessionStore) Delete(id string)

Delete implements SessionStore.

func (*InMemorySessionStore) Get

func (s *InMemorySessionStore) Get(id string) (*Session, bool)

Get implements SessionStore.

func (*InMemorySessionStore) List

func (s *InMemorySessionStore) List() []string

List implements SessionStore.

Description:

Returns all session IDs sorted alphabetically for deterministic ordering.

Outputs:

[]string - All session IDs, sorted alphabetically.

Thread Safety: This method is safe for concurrent use.

func (*InMemorySessionStore) Put

func (s *InMemorySessionStore) Put(session *Session)

Put implements SessionStore.

type LoopDependencies

type LoopDependencies struct {
	// StateMachine handles state transitions.
	StateMachine *StateMachine

	// PhaseRegistry maps states to phase implementations.
	PhaseRegistry PhaseRegistry

	// SessionStore persists session state.
	SessionStore SessionStore

	// EventHandler processes agent events.
	EventHandler func(event any)
}

LoopDependencies contains dependencies for the agent loop.

type ManagedModelInfo

type ManagedModelInfo struct {
	Name      string        `json:"name"`
	IsLoaded  bool          `json:"is_loaded"`
	KeepAlive string        `json:"keep_alive"`
	LastUsed  int64         `json:"last_used"` // Unix milliseconds UTC
	LoadTime  time.Duration `json:"load_time"`
}

ManagedModelInfo contains information about a managed model.

type Message

type Message struct {
	// Role is "user", "assistant", or "system".
	Role string `json:"role"`

	// Content is the message content.
	Content string `json:"content"`

	// ToolCalls contains any tool calls in this message.
	ToolCalls []ToolInvocation `json:"tool_calls,omitempty"`
}

Message represents a conversation message.

type MetricField

type MetricField string

MetricField represents a session metric field for type-safe increments.

const (
	// MetricSteps is the total steps metric.
	MetricSteps MetricField = "steps"

	// MetricTokens is the total tokens metric.
	MetricTokens MetricField = "tokens"

	// MetricToolCalls is the tool calls metric.
	MetricToolCalls MetricField = "tool_calls"

	// MetricToolErrors is the tool errors metric.
	MetricToolErrors MetricField = "tool_errors"

	// MetricLLMCalls is the LLM calls metric.
	MetricLLMCalls MetricField = "llm_calls"

	// MetricCacheHits is the cache hits metric.
	MetricCacheHits MetricField = "cache_hits"

	// MetricGroundingRetries is the grounding validation retry count.
	MetricGroundingRetries MetricField = "grounding_retries"

	// MetricToolForcingRetries is the tool forcing retry count.
	MetricToolForcingRetries MetricField = "tool_forcing_retries"

	// MetricSurrenderRetries is the count of surrender detection retries (GR-59 Group F).
	MetricSurrenderRetries MetricField = "surrender_retries"
)

type ModelManager

type ModelManager interface {
	// WarmModel pre-loads a model into VRAM with the specified keep_alive.
	WarmModel(ctx context.Context, model string, keepAlive string) error

	// GetLoadedModels returns currently tracked models.
	GetLoadedModels() []ManagedModelInfo
}

ModelManager coordinates multiple LLM models to prevent thrashing.

Description

When using multiple models (e.g., tool router + main reasoner), ModelManager uses keep_alive to keep both models loaded in VRAM, preventing expensive model reload cycles.

Thread Safety

Implementations must be safe for concurrent use.

type ModelType

type ModelType string

ModelType identifies the LLM model for format-aware processing.

Description:

Used by control flow hardening layers to apply model-specific logic:
- Parser: Different models output tool calls in different formats
- Sanitizer: Some formats are native to certain models and shouldn't be stripped

Thread Safety: Safe for concurrent use (immutable string type).

const (
	// ModelClaude represents Anthropic Claude models.
	// Native format: <function_calls>/<invoke> - should not be stripped by sanitizer.
	ModelClaude ModelType = "claude"

	// ModelGLM4 represents GLM-4 models.
	// Uses <execute><command> format for tool calls.
	ModelGLM4 ModelType = "glm4"

	// ModelGPT4 represents OpenAI GPT-4 models.
	// Uses JSON function_call format.
	ModelGPT4 ModelType = "gpt4"

	// ModelGeneric represents unknown/generic models.
	// Default: strip all non-standard formats.
	ModelGeneric ModelType = "generic"
)

func (ModelType) IsAnthropicModel

func (m ModelType) IsAnthropicModel() bool

IsAnthropicModel returns true if this is an Anthropic model.

Description:

Anthropic models use native function_calls format that should be preserved
by the sanitizer rather than stripped as leaked markup.

Outputs:

bool - True if model is Claude

func (ModelType) String

func (m ModelType) String() string

String returns the string representation of the model type.

Outputs:

string - The model type as a string (e.g., "claude", "gpt4")

type NullGraphProvider

type NullGraphProvider struct{}

NullGraphProvider is a no-op graph provider for degraded mode.

Description:

NullGraphProvider always returns errors and reports unavailable.
Use this when the graph service is not configured or unavailable.

Thread Safety: NullGraphProvider is safe for concurrent use.

func (*NullGraphProvider) EnrichmentTraceStep

func (p *NullGraphProvider) EnrichmentTraceStep(graphID string) *crs.TraceStep

EnrichmentTraceStep implements phases.GraphProvider.

Description:

Always returns nil — no graph available in degraded mode.

Thread Safety: This method is safe for concurrent use.

func (*NullGraphProvider) Initialize

func (p *NullGraphProvider) Initialize(ctx context.Context, projectRoot string) (string, error)

Initialize implements phases.GraphProvider.

Description:

Always returns an error indicating the service is unavailable.

Outputs:

string - Empty string.
error - Always returns ErrServiceUnavailable.

func (*NullGraphProvider) IsAvailable

func (p *NullGraphProvider) IsAvailable() bool

IsAvailable implements phases.GraphProvider.

Description:

Always returns false.

Outputs:

bool - Always false.

type ParamExtractor

type ParamExtractor interface {
	// ExtractParams extracts corrected parameters for a tool.
	//
	// Inputs:
	//   - ctx: Context for cancellation/timeout.
	//   - query: The user's natural language query.
	//   - toolName: The name of the selected tool.
	//   - paramSchemas: Parameter definitions for the tool.
	//   - regexHint: The regex extractor's output (used as a hint).
	//
	// Outputs:
	//   - map[string]any: Corrected parameter values.
	//   - error: Non-nil if extraction fails (caller should use regexHint).
	ExtractParams(ctx context.Context, query string, toolName string,
		paramSchemas []ParamExtractorSchema, regexHint map[string]any) (map[string]any, error)

	// IsEnabled returns true if the extractor is enabled.
	IsEnabled() bool

	// ResolveConceptualSymbol uses the LLM to pick the best symbol from candidates
	// when the query uses conceptual descriptions instead of function names.
	// IT-12: Called as a fallback when regex extraction + fuzzy resolution fail.
	// D3: Added tier0Count, tier1Count params for grouped prompt formatting.
	// D3c: Added sourceContext param — describes the source function for find_path to-side.
	//
	// Inputs:
	//   - ctx: Context for cancellation/timeout.
	//   - query: The user's natural language query.
	//   - candidates: Symbol candidates found by keyword search of the index.
	//   - tier0Count: Number of tier0 (best match) candidates in the list.
	//   - tier1Count: Number of tier1 (partial match) candidates in the list.
	//   - sourceContext: Description of the source function (e.g., "Bind (method on Context
	//     in context.go:757)"). Empty when not resolving a find_path to-side.
	//
	// Outputs:
	//   - string: The best symbol name from the candidates.
	//   - error: Non-nil if resolution fails.
	ResolveConceptualSymbol(ctx context.Context, query string,
		candidates []SymbolCandidate, tier0Count, tier1Count int,
		sourceContext string) (string, error)
}

ParamExtractor uses a fast LLM to extract tool parameters from queries.

Description

Corrects regex-based parameter extraction errors using semantic understanding. When enabled, the regex result is passed as a hint and the LLM can confirm or correct it. Falls back to regex result on any error.

Thread Safety

Implementations must be safe for concurrent use.

type ParamExtractorSchema

type ParamExtractorSchema struct {
	// Name is the parameter name.
	Name string

	// Type is the parameter type (string, integer, boolean).
	Type string

	// Required indicates if the parameter is required.
	Required bool

	// Default is the default value as a string.
	Default string

	// Description explains what the parameter is for.
	Description string
}

ParamExtractorSchema describes a tool parameter for the LLM prompt.

type PhaseExecutor

type PhaseExecutor interface {
	// Execute runs the phase.
	Execute(ctx context.Context, deps any) (AgentState, error)

	// Name returns the phase name.
	Name() string
}

PhaseExecutor executes a phase and returns the next state.

type PhaseRegistry

type PhaseRegistry interface {
	// GetPhase returns the phase implementation for a state.
	GetPhase(state AgentState) (PhaseExecutor, bool)
}

PhaseRegistry provides access to phase implementations.

type ProposedChange

type ProposedChange struct {
	// FilePath is the file to modify.
	FilePath string `json:"file_path"`

	// ChangeType is create, modify, or delete.
	ChangeType string `json:"change_type"`

	// OldContent is the original content (for modify).
	OldContent string `json:"old_content,omitempty"`

	// NewContent is the new content.
	NewContent string `json:"new_content"`

	// Reason explains why this change is needed.
	Reason string `json:"reason"`
}

ProposedChange represents a code change the agent wants to make.

type QueryIntent

type QueryIntent struct {
	// Type is the query type (explore, modify, explain, debug, refactor).
	Type string `json:"type"`

	// Scope is the query scope (file, function, package, project).
	Scope string `json:"scope"`

	// Targets are specific symbols/files mentioned.
	Targets []string `json:"targets"`

	// Confidence is how certain we are about the classification (0.0-1.0).
	Confidence float64 `json:"confidence"`
}

QueryIntent represents the classified intent of a user query.

func (*QueryIntent) Validate

func (q *QueryIntent) Validate() error

Validate checks that the QueryIntent has valid values.

Outputs:

error - Non-nil if any field is invalid

type ReasoningSummary

type ReasoningSummary struct {
	// NodesExplored is the total number of nodes in the proof index.
	NodesExplored int `json:"nodes_explored"`

	// NodesProven is the count of nodes with PROVEN status.
	NodesProven int `json:"nodes_proven"`

	// NodesDisproven is the count of nodes with DISPROVEN status.
	NodesDisproven int `json:"nodes_disproven"`

	// NodesUnknown is the count of nodes with UNKNOWN or EXPANDED status.
	NodesUnknown int `json:"nodes_unknown"`

	// ConstraintsApplied is the number of active constraints.
	ConstraintsApplied int `json:"constraints_applied"`

	// ExplorationDepth is the number of history entries (proxy for depth).
	ExplorationDepth int `json:"exploration_depth"`

	// ConfidenceScore is the ratio of proven nodes to explored nodes.
	// Value is between 0.0 and 1.0. Use with caution - this is a coverage
	// metric, not a statistical confidence interval.
	ConfidenceScore float64 `json:"confidence_score"`
}

ReasoningSummary provides high-level metrics about reasoning progress.

Description:

Computed from CRS state to give a quick overview of reasoning
progress without requiring full index inspection. Included in
RunResult when CRS is enabled for the session.

type RunResult

type RunResult struct {
	// State is the current agent state after execution.
	State AgentState `json:"state"`

	// Response is the final response text (for COMPLETE state).
	Response string `json:"response,omitempty"`

	// NeedsClarify contains clarification details (for CLARIFY state).
	NeedsClarify *ClarifyRequest `json:"needs_clarify,omitempty"`

	// ToolsUsed lists all tool invocations made.
	ToolsUsed []ToolInvocation `json:"tools_used"`

	// TokensUsed is the total tokens consumed.
	TokensUsed int `json:"tokens_used"`

	// StepsTaken is the number of steps executed.
	StepsTaken int `json:"steps_taken"`

	// SafetyChecks contains any safety analysis results.
	SafetyChecks []SafetyResult `json:"safety_checks,omitempty"`

	// Error contains error details (for ERROR state).
	Error *AgentError `json:"error,omitempty"`

	// ReasoningSummary provides high-level metrics about the reasoning process.
	// Populated when CRS is enabled for the session.
	ReasoningSummary *ReasoningSummary `json:"reasoning_summary,omitempty"`
}

RunResult contains the outcome of a Run or Continue call.

type SafetyConstraintInfo

type SafetyConstraintInfo struct {
	// IssueCode is the safety issue code (e.g., "SUPPLY_CHAIN_INSTALL").
	IssueCode string `json:"issue_code"`

	// Pattern describes what triggered the violation.
	Pattern string `json:"pattern"`

	// Reason explains why this is blocked.
	Reason string `json:"reason"`
}

SafetyConstraintInfo contains constraint information from safety violations.

type SafetyResult

type SafetyResult struct {
	// Passed indicates if all safety checks passed.
	Passed bool `json:"passed"`

	// Issues contains security issues found.
	Issues []SecurityIssue `json:"issues"`

	// Blocked indicates if the operation was blocked.
	Blocked bool `json:"blocked"`

	// BlockReason explains why the operation was blocked.
	BlockReason string `json:"block_reason,omitempty"`
}

SafetyResult contains security analysis findings.

type SafetyViolation

type SafetyViolation struct {
	// NodeID is the MCTS node where the violation occurred.
	NodeID string `json:"node_id"`

	// ErrorMessage is the safety error message.
	ErrorMessage string `json:"error_message"`

	// Timestamp is when the violation was recorded (Unix milliseconds UTC).
	Timestamp int64 `json:"timestamp"`

	// Constraints are the extracted constraints for CDCL.
	Constraints []SafetyConstraintInfo `json:"constraints,omitempty"`
}

SafetyViolation represents a safety-blocked operation for CDCL learning.

Safety violations are classified as hard signals because: 1. They represent definitive failures (the action WILL be blocked) 2. CDCL should learn to avoid patterns that trigger safety blocks 3. Unlike soft signals, safety rules are deterministic

type SecurityIssue

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

	// Title is a short description.
	Title string `json:"title"`

	// Description provides details.
	Description string `json:"description"`

	// Severity is the issue severity (critical, high, medium, low).
	Severity string `json:"severity"`

	// Category is the issue category (injection, secrets, etc.).
	Category string `json:"category"`

	// FilePath is where the issue was found.
	FilePath string `json:"file_path,omitempty"`

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

	// Code is the problematic code snippet.
	Code string `json:"code,omitempty"`
}

SecurityIssue represents a single security finding.

type ServiceGraphProvider

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

ServiceGraphProvider adapts a GraphInitializer to phases.GraphProvider.

Description:

ServiceGraphProvider wraps a GraphInitializer to provide graph
initialization capabilities to the agent phases. It implements
the phases.GraphProvider interface.

Thread Safety: ServiceGraphProvider is safe for concurrent use if the underlying initializer is safe for concurrent use.

func NewServiceGraphProvider

func NewServiceGraphProvider(initializer GraphInitializer) *ServiceGraphProvider

NewServiceGraphProvider creates a new graph provider.

Description:

Creates a GraphProvider that delegates to the provided initializer.

Inputs:

initializer - The graph initializer to wrap.

Outputs:

*ServiceGraphProvider - The new provider.

func (*ServiceGraphProvider) EnrichmentTraceStep

func (p *ServiceGraphProvider) EnrichmentTraceStep(graphID string) *crs.TraceStep

EnrichmentTraceStep implements phases.GraphProvider.

Description:

GR-76: Returns a TraceStep describing LSP enrichment quality by
delegating to the initializer if it implements EnrichmentStepProvider.

Inputs:

graphID - The graph ID to query.

Outputs:

*crs.TraceStep - The enrichment TraceStep, or nil if unavailable.

Thread Safety: This method is safe for concurrent use.

func (*ServiceGraphProvider) Initialize

func (p *ServiceGraphProvider) Initialize(ctx context.Context, projectRoot string) (string, error)

Initialize implements phases.GraphProvider.

Description:

Initializes a code graph for the given project root by delegating
to the wrapped initializer.

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 (*ServiceGraphProvider) IsAvailable

func (p *ServiceGraphProvider) IsAvailable() bool

IsAvailable implements phases.GraphProvider.

Description:

Returns whether the graph service is available for use.
Returns true if the initializer is set.

Outputs:

bool - True if the initializer is available.

Thread Safety: This method is safe for concurrent use.

type Session

type Session struct {

	// ID is the unique session identifier.
	ID string `json:"id"`

	// ProjectRoot is the absolute path to the project.
	ProjectRoot string `json:"project_root"`

	// GraphID is the Trace graph ID (set after init).
	GraphID string `json:"graph_id,omitempty"`

	// State is the current agent state.
	State AgentState `json:"state"`

	// Config holds the session configuration.
	Config *SessionConfig `json:"config"`

	// History records all execution steps.
	History []HistoryEntry `json:"history"`

	// Metrics tracks session metrics.
	Metrics *SessionMetrics `json:"metrics"`

	// CurrentContext holds the current assembled context.
	CurrentContext *AssembledContext `json:"-"`

	// LastQuery is the most recent user query.
	LastQuery string `json:"last_query,omitempty"`

	// LastIntent is the classified intent of the last query.
	LastIntent *QueryIntent `json:"last_intent,omitempty"`

	// CreatedAt is when the session was created (Unix milliseconds UTC).
	CreatedAt int64 `json:"created_at"`

	// LastActiveAt is when the session was last active (Unix milliseconds UTC).
	LastActiveAt int64 `json:"last_active_at"`

	// CRS is the Code Reasoning State for MCTS-based reasoning.
	// Optional - nil when MCTS is not enabled.
	CRS crs.CRS `json:"-"`
	// contains filtered or unexported fields
}

Session represents an agent session with all state.

Thread Safety:

Session uses internal synchronization for state access.
Multiple goroutines can safely read session state.

func NewSession

func NewSession(projectRoot string, config *SessionConfig) (*Session, error)

NewSession creates a new agent session.

Description:

Creates a session with the given project root and configuration.
The session starts in IDLE state with empty history.

Inputs:

projectRoot - Absolute path to the project root
config - Session configuration (uses defaults if nil)

Outputs:

*Session - The new session
error - Non-nil if configuration is invalid

Example:

session, err := NewSession("/path/to/project", nil)
if err != nil {
    return fmt.Errorf("create session: %w", err)
}

func (*Session) AddHistoryEntry

func (s *Session) AddHistoryEntry(entry HistoryEntry)

AddHistoryEntry appends a history entry.

Thread Safety: This method is safe for concurrent use.

func (*Session) ClearSafetyViolations

func (s *Session) ClearSafetyViolations()

ClearSafetyViolations clears all recorded safety violations.

Description:

Call this after CDCL has processed the violations or when starting
a new query.

Thread Safety: This method is safe for concurrent use.

func (*Session) ClearToolErrors

func (s *Session) ClearToolErrors()

ClearToolErrors clears all recorded tool errors.

Description:

Call this when errors have been addressed or a new query starts.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetCRS

func (s *Session) GetCRS() crs.CRS

GetCRS returns the CRS instance for this session.

Outputs:

crs.CRS - The CRS instance, or nil if not set.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetCRSExport

func (s *Session) GetCRSExport() *crs.CRSExport

GetCRSExport returns the full CRS state export.

Description:

Exports all six CRS indexes and summary metrics in JSON-serializable format.
Returns nil if CRS is not enabled.

Outputs:

*crs.CRSExport - Full CRS export, or nil if CRS not enabled.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetClarificationPrompt

func (s *Session) GetClarificationPrompt() string

GetClarificationPrompt returns the clarification prompt if set.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetCurrentContext

func (s *Session) GetCurrentContext() *AssembledContext

GetCurrentContext returns the current assembled context.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetCycleDetector

func (s *Session) GetCycleDetector() *crs.CycleDetector

GetCycleDetector returns the cycle detector for this session.

Description:

Returns the Brent's algorithm cycle detector for real-time cycle detection.
CRS-03: The detector is lazily initialized when first accessed if CRS is enabled.

Outputs:

*crs.CycleDetector - The cycle detector, or nil if CRS is not enabled.

Thread Safety: This method is safe for concurrent use. A-03: Uses double-check locking to reduce contention on hot path.

func (*Session) GetGraphID

func (s *Session) GetGraphID() string

GetGraphID returns the graph ID if set.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetHistory

func (s *Session) GetHistory() []HistoryEntry

GetHistory returns a copy of the history.

Description:

Returns a shallow copy of the history slice. The slice itself is copied
but HistoryEntry structs are value types so modifications to the returned
slice won't affect the session's internal history.

Outputs:

[]HistoryEntry - Copy of the session history

Thread Safety: This method is safe for concurrent use.

func (*Session) GetMetric

func (s *Session) GetMetric(field MetricField) int

GetMetric returns the value of a specific metric field.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetMetrics

func (s *Session) GetMetrics() SessionMetrics

GetMetrics returns a copy of the session metrics.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetModelManager

func (s *Session) GetModelManager() ModelManager

GetModelManager returns the model manager for this session.

Outputs:

ModelManager - The model manager, or nil if not set.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetParamExtractor

func (s *Session) GetParamExtractor() ParamExtractor

GetParamExtractor returns the parameter extractor for this session.

Outputs:

ParamExtractor - The extractor, or nil if not enabled.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetProjectRoot

func (s *Session) GetProjectRoot() string

GetProjectRoot returns the project root path.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetReasoningSummary

func (s *Session) GetReasoningSummary() *ReasoningSummary

GetReasoningSummary returns the reasoning summary for this session.

Description:

Computes high-level metrics about the reasoning process from CRS state.
Returns nil if CRS is not enabled. Summary is cached until CRS changes.

Outputs:

*ReasoningSummary - Summary metrics, or nil if CRS not enabled.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetReasoningTrace

func (s *Session) GetReasoningTrace() *crs.ReasoningTrace

GetReasoningTrace returns the reasoning trace for this session.

Description:

Returns the step-by-step reasoning trace if a trace recorder is set.
Returns nil if trace recording is not enabled.

Outputs:

*crs.ReasoningTrace - The reasoning trace, or nil if not enabled.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetRecentToolErrors

func (s *Session) GetRecentToolErrors() []ToolRouterError

GetRecentToolErrors returns recent tool failures for router feedback.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetSafetyViolations

func (s *Session) GetSafetyViolations() []SafetyViolation

GetSafetyViolations returns recent safety violations for CDCL learning.

Description:

Returns safety violations that should be processed by CDCL as hard
signals. Each violation contains constraints that encode patterns
to avoid.

Outputs:

[]SafetyViolation - Recent safety violations, or nil if none.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetState

func (s *Session) GetState() AgentState

GetState returns the current session state.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetToolRouter

func (s *Session) GetToolRouter() ToolRouter

GetToolRouter returns the tool router for this session.

Outputs:

ToolRouter - The tool router, or nil if not enabled.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetTraceRecorder

func (s *Session) GetTraceRecorder() *crs.TraceRecorder

GetTraceRecorder returns the trace recorder for this session.

Outputs:

*crs.TraceRecorder - The trace recorder, or nil if not set.

Thread Safety: This method is safe for concurrent use.

func (*Session) GetTraceSteps

func (s *Session) GetTraceSteps() []crs.TraceStep

GetTraceSteps returns all recorded trace steps from this session.

Description:

Extracts trace steps from the trace recorder for history-aware routing.
This allows the router to see what tools were already called and what
they found, enabling better next-tool suggestions.

Outputs:

[]crs.TraceStep - The recorded trace steps, or nil if no recorder.

Thread Safety: This method is safe for concurrent use.

func (*Session) GraphToolHadSubstantiveResults

func (s *Session) GraphToolHadSubstantiveResults() bool

GraphToolHadSubstantiveResults returns true if a forced graph tool call returned substantive results during this session.

Description:

GR-59 Rev 4: Used by shouldForceSynthesisAfterGraphTools to detect when
a forced graph tool (find_implementations, find_callers, etc.) already
returned authoritative results. Prevents the LLM from spiraling into
Grep/Glob loops after receiving exhaustive graph data.

Outputs:

bool - True if a forced graph tool returned substantive results.

Thread Safety: This method is safe for concurrent use.

func (*Session) HasCRS

func (s *Session) HasCRS() bool

HasCRS returns true if CRS is enabled for this session.

Thread Safety: This method is safe for concurrent use.

func (*Session) HasFlag

func (s *Session) HasFlag(key string) bool

HasFlag checks whether a per-session boolean flag has been set.

Description:

Used by CRS scope relaxation to check if a tool has already been relaxed
in this session, preventing infinite retry loops.

Inputs:

key - The flag name (e.g., "scope_relaxed_find_hotspots").

Outputs:

bool - True if the flag has been set via SetFlag.

Thread Safety: Safe for concurrent use.

func (*Session) HasPendingSafetyViolations

func (s *Session) HasPendingSafetyViolations() bool

HasPendingSafetyViolations returns true if there are unprocessed violations.

Thread Safety: This method is safe for concurrent use.

func (*Session) HasToolRouter

func (s *Session) HasToolRouter() bool

HasToolRouter returns true if tool routing is enabled for this session.

Thread Safety: This method is safe for concurrent use.

func (*Session) IncrementMetric

func (s *Session) IncrementMetric(field MetricField, value int)

IncrementMetric increments a session metric.

Description:

Increments the specified metric by the given value. Use the
MetricField constants (MetricSteps, MetricTokens, etc.) for type safety.

Inputs:

field - The metric field to increment (use MetricField constants)
value - The amount to add

Thread Safety: This method is safe for concurrent use.

func (*Session) InvalidateSummaryCache

func (s *Session) InvalidateSummaryCache()

InvalidateSummaryCache clears the cached reasoning summary.

Description:

Call this after applying deltas to CRS to ensure fresh summary
is computed on next GetReasoningSummary call.

Thread Safety: This method is safe for concurrent use.

func (*Session) IsCircuitBreakerActive

func (s *Session) IsCircuitBreakerActive() bool

IsCircuitBreakerActive returns true if the circuit breaker has fired.

Description:

When the circuit breaker fires (e.g., tool called too many times),
the agent enters synthesis mode. This flag tells the execute phase
to NOT require tool usage and to accept text responses as final answers.

GR-44: Fixes death spiral where CB fires but execute phase still demands tools.

Thread Safety: This method is safe for concurrent use.

func (*Session) IsTerminated

func (s *Session) IsTerminated() bool

IsTerminated returns true if the session is in a terminal state.

Thread Safety: This method is safe for concurrent use.

func (*Session) IsToolRouterEnabled

func (s *Session) IsToolRouterEnabled() bool

IsToolRouterEnabled returns true if tool routing is configured and enabled.

Description:

Checks both the configuration flag and whether a router has been set.

Thread Safety: This method is safe for concurrent use.

func (*Session) RecordSafetyViolation

func (s *Session) RecordSafetyViolation(nodeID, errMsg string, constraints []safety.SafetyConstraint)

RecordSafetyViolation records a safety-blocked operation for CDCL learning.

Description:

Records a safety violation as a hard signal for CDCL learning.
Safety violations are classified as hard signals because they represent
definitive failures - the action WILL be blocked. CDCL should learn to
avoid patterns that trigger safety blocks.

This addresses Issue #6: Safety Blocking Learning Signal. Without this,
safety-blocked actions would be soft errors that MCTS/CDCL ignores,
potentially retrying the same blocked pattern.

Inputs:

nodeID - The MCTS node ID where the violation occurred.
errMsg - The safety error message.
constraints - The extracted constraints from safety issues.

Thread Safety: This method is safe for concurrent use.

func (*Session) RecordToolError

func (s *Session) RecordToolError(tool, errMsg string)

RecordToolError records a tool failure for router feedback.

Description:

Records that a tool failed with an error. This is fed back to the
tool router so it can avoid suggesting the same tool again.
Only keeps the last 5 errors to avoid unbounded growth.

Inputs:

tool - The tool name that failed.
errMsg - The error message.

Thread Safety: This method is safe for concurrent use.

func (*Session) RecordTraceStep

func (s *Session) RecordTraceStep(step crs.TraceStep)

RecordTraceStep records a reasoning trace step.

Description:

Records a step in the reasoning trace for audit and debugging.
This is a convenience wrapper around the TraceRecorder.
If trace recording is not enabled, this is a no-op.

Inputs:

step - The trace step to record.

Thread Safety: This method is safe for concurrent use.

func (*Session) Release

func (s *Session) Release()

Release releases the session after an operation.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetCRS

func (s *Session) SetCRS(crsInstance crs.CRS)

SetCRS sets the Code Reasoning State for this session.

Description:

Associates a CRS instance with this session for MCTS-based reasoning.
Also initializes the CRS serializer for later export operations.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetCircuitBreakerActive

func (s *Session) SetCircuitBreakerActive(active bool)

SetCircuitBreakerActive sets the circuit breaker state.

Description:

Call this when the circuit breaker fires to signal that the agent
should enter synthesis mode and stop requiring tool usage.

Inputs:

active - True when CB has fired, false to reset.

GR-44: Fixes death spiral where CB fires but execute phase still demands tools.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetCurrentContext

func (s *Session) SetCurrentContext(ctx *AssembledContext)

SetCurrentContext updates the current assembled context.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetDegradedMode

func (s *Session) SetDegradedMode(degraded bool)

SetDegradedMode sets the degraded mode flag.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetFlag

func (s *Session) SetFlag(key string)

SetFlag sets a per-session boolean flag.

Description:

Used by CRS scope relaxation to mark that a tool has been relaxed,
ensuring at most one relaxation retry per tool per session.

Inputs:

key - The flag name (e.g., "scope_relaxed_find_hotspots").

Thread Safety: Safe for concurrent use.

func (*Session) SetGraphID

func (s *Session) SetGraphID(graphID string)

SetGraphID sets the graph ID.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetGraphToolHadSubstantiveResults

func (s *Session) SetGraphToolHadSubstantiveResults(v bool)

SetGraphToolHadSubstantiveResults marks that a forced graph tool returned substantive results.

Description:

Called by executeToolDirectlyWithFallback when a graph tool like
find_implementations returns non-zero results. Once set, all subsequent
execution steps will force synthesis instead of allowing further search.

Inputs:

v - True when graph tool returned results, false to reset.

GR-59 Rev 4: Direct flag eliminates fragile metadata round-trip.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetModelManager

func (s *Session) SetModelManager(manager ModelManager)

SetModelManager sets the model manager for this session.

Description:

Associates a ModelManager instance with this session for multi-model
coordination. Used to prevent model thrashing when using tool router
with main LLM.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetParamExtractor

func (s *Session) SetParamExtractor(extractor ParamExtractor)

SetParamExtractor sets the LLM-based parameter extractor for this session.

Description:

Associates a ParamExtractor instance with this session for LLM-enhanced
parameter extraction. Should be called after session creation if LLM
parameter extraction is enabled.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetState

func (s *Session) SetState(state AgentState)

SetState updates the session state.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetToolRouter

func (s *Session) SetToolRouter(router ToolRouter)

SetToolRouter sets the tool router for this session.

Description:

Associates a ToolRouter instance with this session for fast tool selection.
Should be called after session creation if tool routing is enabled.

Thread Safety: This method is safe for concurrent use.

func (*Session) SetTraceRecorder

func (s *Session) SetTraceRecorder(recorder *crs.TraceRecorder)

SetTraceRecorder sets the trace recorder for this session.

Thread Safety: This method is safe for concurrent use.

func (*Session) ToSessionState

func (s *Session) ToSessionState() *SessionState

ToSessionState converts to an external SessionState.

Thread Safety: This method is safe for concurrent use.

func (*Session) TryAcquire

func (s *Session) TryAcquire() bool

TryAcquire attempts to acquire the session for an operation.

Returns false if another operation is in progress.

Thread Safety: This method is safe for concurrent use.

type SessionCleanupFunc

type SessionCleanupFunc func(sessionID string)

SessionCleanupFunc is a function called when a session is closed. It receives the session ID to clean up.

type SessionConfig

type SessionConfig struct {
	// MaxSteps is the maximum number of agent steps allowed.
	// Default: 50
	MaxSteps int `json:"max_steps"`

	// MaxTokensPerStep is the maximum tokens per LLM call.
	// Default: 4000
	MaxTokensPerStep int `json:"max_tokens_per_step"`

	// MaxTotalTokens is the total token budget for the session.
	// Default: 100000
	MaxTotalTokens int `json:"max_total_tokens"`

	// MaxToolCallsPerStep limits tool calls in a single step.
	// Default: 5
	MaxToolCallsPerStep int `json:"max_tool_calls_per_step"`

	// StepTimeout is the maximum duration for a single step.
	// Default: 30s
	StepTimeout time.Duration `json:"step_timeout"`

	// TotalTimeout is the maximum duration for the entire session.
	// Default: 10m
	TotalTimeout time.Duration `json:"total_timeout"`

	// InitialContextBudget is the token budget for initial context assembly.
	// Default: 8000
	InitialContextBudget int `json:"initial_context_budget"`

	// ContextEvictionPolicy determines how context is evicted when over budget.
	// Options: "lru", "relevance", "hybrid"
	// Default: "hybrid"
	ContextEvictionPolicy string `json:"context_eviction_policy"`

	// SummarizationThreshold is tokens before summarizing context.
	// Default: 50000
	SummarizationThreshold int `json:"summarization_threshold"`

	// RequireSafetyCheck enables safety checks before code changes.
	// Default: true
	RequireSafetyCheck bool `json:"require_safety_check"`

	// SafetyCheckScope determines what to analyze for safety.
	// Options: "changed_files", "blast_radius", "full"
	// Default: "blast_radius"
	SafetyCheckScope string `json:"safety_check_scope"`

	// BlockOnCritical blocks operations with critical security issues.
	// Default: true
	BlockOnCritical bool `json:"block_on_critical"`

	// EnabledToolSets specifies which tool categories are enabled.
	// Options: "exploration", "reasoning", "safety", "file"
	// Default: ["exploration", "reasoning", "safety", "file"]
	EnabledToolSets []string `json:"enabled_tool_sets"`

	// DisabledTools lists specific tools to disable.
	DisabledTools []string `json:"disabled_tools"`

	// ToolPriorities assigns priority weights to tools (higher = prefer).
	ToolPriorities map[string]int `json:"tool_priorities"`

	// ReflectionThreshold is steps before triggering reflection.
	// Default: 10
	ReflectionThreshold int `json:"reflection_threshold"`

	// ConfidenceThreshold triggers reflection below this confidence.
	// Default: 0.7
	ConfidenceThreshold float64 `json:"confidence_threshold"`

	// DegradationMode determines behavior when services unavailable.
	// Options: "fallback", "fail", "ask"
	// Default: "fallback"
	DegradationMode string `json:"degradation_mode"`

	// MainModel overrides the main reasoning LLM for this session.
	// CB-62: When non-empty, overrides OLLAMA_MODEL / TRACE_MAIN_MODEL env vars.
	// Set by the proxy when forwarding the user's model selection from OpenWebUI.
	// Default: "" (use environment/startup config).
	MainModel string `json:"main_model"`

	// ToolRouterEnabled enables the micro-LLM tool router for faster tool selection.
	// When enabled, a fast model (like granite4:micro-h) pre-selects tools before
	// the main reasoning LLM, reducing latency.
	// Default: false (opt-in feature)
	ToolRouterEnabled bool `json:"tool_router_enabled"`

	// ToolRouterModel is the Ollama model to use for tool routing.
	// Should be a small, fast model like "granite4:micro-h" or "granite4:3b-h".
	// Default: "granite4:micro-h"
	ToolRouterModel string `json:"tool_router_model"`

	// ToolRouterTimeout is the maximum time for a routing decision.
	// GR-44: If exceeded, the process fails (no fallback to main LLM).
	// Default: 20s
	ToolRouterTimeout time.Duration `json:"tool_router_timeout"`

	// ToolRouterConfidence is the minimum confidence for accepting a routing decision.
	// Below this threshold, falls back to main LLM tool selection.
	// Default: 0.7
	ToolRouterConfidence float64 `json:"tool_router_confidence"`

	// ParamExtractorModel is the Ollama model for LLM parameter extraction.
	// IT-08e: Should be a small, fast model optimized for JSON structured output.
	// Runs in parallel with the tool router on a separate model to avoid
	// Ollama serialization bottlenecks.
	// Default: "ministral-3:3b"
	ParamExtractorModel string `json:"param_extractor_model"`
}

SessionConfig holds all tunable parameters for a session.

Thread Safety:

SessionConfig is immutable after creation. Modifications require
creating a new config.

func DefaultSessionConfig

func DefaultSessionConfig() *SessionConfig

DefaultSessionConfig returns production-ready default configuration.

Description:

Returns a SessionConfig with sensible defaults suitable for most
use cases. Callers can modify specific fields as needed.

Outputs:

*SessionConfig - Configuration with default values

func (*SessionConfig) MergeOverrides

func (c *SessionConfig) MergeOverrides(overrides *SessionConfig) *SessionConfig

MergeOverrides applies non-zero fields from overrides onto the receiver.

Description:

Returns the receiver with non-zero fields from overrides applied.
This allows callers to send a partial config (e.g., only MainModel)
without zeroing out defaults for fields they didn't set.

Inputs:

overrides - Partial config. Nil is safe (returns receiver unchanged).

Outputs:

*SessionConfig - The receiver with overrides applied.

Thread Safety: Not safe for concurrent use.

func (*SessionConfig) Validate

func (c *SessionConfig) Validate() error

Validate checks that the configuration is valid.

Description:

Validates all configuration fields including numeric limits and string enums.
Returns ErrInvalidSession with details if validation fails.

Outputs:

error - Non-nil if configuration is invalid, contains validation details

type SessionMetrics

type SessionMetrics struct {
	// TotalSteps is the number of steps executed.
	TotalSteps int `json:"total_steps"`

	// TotalTokens is the total tokens consumed.
	TotalTokens int `json:"total_tokens"`

	// TotalDurationMs is the total execution time in milliseconds.
	TotalDurationMs int64 `json:"total_duration_ms"`

	// ToolCalls is the number of tool invocations.
	ToolCalls int `json:"tool_calls"`

	// ToolErrors is the number of failed tool calls.
	ToolErrors int `json:"tool_errors"`

	// LLMCalls is the number of LLM API calls.
	LLMCalls int `json:"llm_calls"`

	// CacheHits is the number of cache hits.
	CacheHits int `json:"cache_hits"`

	// DegradedMode indicates if running in degraded mode.
	DegradedMode bool `json:"degraded_mode"`

	// GroundingRetries is the number of grounding validation retries.
	GroundingRetries int `json:"grounding_retries"`

	// ToolForcingRetries is the number of tool forcing retries.
	ToolForcingRetries int `json:"tool_forcing_retries"`

	// GraphStats contains Trace graph statistics.
	GraphStats *GraphStats `json:"graph_stats,omitempty"`
}

SessionMetrics tracks metrics for a session.

type SessionState

type SessionState struct {
	// ID is the session identifier.
	ID string `json:"id"`

	// ProjectRoot is the project being analyzed.
	ProjectRoot string `json:"project_root"`

	// GraphID is the Trace graph ID.
	GraphID string `json:"graph_id,omitempty"`

	// State is the current agent state.
	State AgentState `json:"state"`

	// StepCount is the number of steps executed.
	StepCount int `json:"step_count"`

	// TokensUsed is the total tokens consumed.
	TokensUsed int `json:"tokens_used"`

	// CreatedAt is when the session started (Unix milliseconds UTC).
	CreatedAt int64 `json:"created_at"`

	// LastActiveAt is when the session was last active (Unix milliseconds UTC).
	LastActiveAt int64 `json:"last_active_at"`

	// DegradedMode indicates if running with limited tools.
	DegradedMode bool `json:"degraded_mode"`
}

SessionState contains the externally visible state of a session.

type SessionStore

type SessionStore interface {
	// Get retrieves a session by ID.
	Get(id string) (*Session, bool)

	// Put stores a session.
	Put(session *Session)

	// Delete removes a session.
	Delete(id string)

	// List returns all active session IDs.
	List() []string
}

SessionStore manages session persistence.

type SessionSummary

type SessionSummary struct {
	// ID is the session identifier.
	ID string `json:"id"`

	// State is the current agent state.
	State AgentState `json:"state"`

	// TraceStepCount is the number of CRS trace steps recorded.
	TraceStepCount int `json:"trace_step_count"`

	// CircuitBreakerActive indicates if the circuit breaker has fired.
	CircuitBreakerActive bool `json:"circuit_breaker_active"`

	// CreatedAt is when the session started (Unix milliseconds UTC).
	CreatedAt int64 `json:"created_at"`

	// ToolCalls is the total number of tool calls made.
	ToolCalls int `json:"tool_calls"`
}

SessionSummary is a brief summary of a session for listing/debug endpoints.

Description:

Contains minimal session information for debug endpoints that need to
list all sessions without exposing full session internals.

type StateMachine

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

StateMachine manages valid state transitions for the agent loop.

The state machine enforces the following transition graph:

IDLE → INIT                  : User query received
INIT → PLAN                  : Graph initialized successfully
INIT → DEGRADED              : Trace unavailable
INIT → ERROR                 : Unrecoverable init failure
PLAN → EXECUTE               : Initial context assembled
PLAN → CLARIFY               : Query ambiguous, need user input
PLAN → ERROR                 : Planning failed
CLARIFY → PLAN               : User provided clarification
CLARIFY → ERROR              : Clarification failed
EXECUTE → EXECUTE            : Tool call completed, continue
EXECUTE → REFLECT            : Hit step limit or confidence threshold
EXECUTE → COMPLETE           : Direct answer, no reflection needed
EXECUTE → CLARIFY            : Unable to proceed without user input
EXECUTE → ERROR              : Execution failed
REFLECT → EXECUTE            : Self-correction, try different approach
REFLECT → COMPLETE           : Answer satisfactory
REFLECT → CLARIFY            : Need user input
REFLECT → ERROR              : Reflection failed
COMPLETE → PLAN              : Multi-turn follow-up question
DEGRADED → PLAN              : Limited planning without graph
DEGRADED → ERROR             : Degraded mode failed
* → ERROR                    : Any state can transition to ERROR

Thread Safety:

StateMachine is safe for concurrent use.

func NewStateMachine

func NewStateMachine() *StateMachine

NewStateMachine creates a new state machine with all valid transitions.

Outputs:

*StateMachine - Configured state machine

func (*StateMachine) CanTransition

func (sm *StateMachine) CanTransition(from, to AgentState) bool

CanTransition checks if a transition from one state to another is valid.

Inputs:

from - Current state
to - Target state

Outputs:

bool - True if the transition is valid

Thread Safety: This method is safe for concurrent use.

func (*StateMachine) Transition

func (sm *StateMachine) Transition(session *Session, to AgentState) error

Transition attempts to transition a session from one state to another.

Description:

Validates the transition and updates the session state if valid.
Returns an error if the transition is not allowed.

Inputs:

session - The session to transition
to - Target state

Outputs:

error - ErrInvalidTransition if transition not allowed

Thread Safety: This method is safe for concurrent use.

func (*StateMachine) TransitionEvent

func (sm *StateMachine) TransitionEvent(from, to AgentState) HistoryEntry

TransitionEvent creates a history entry for a state transition.

Inputs:

from - Source state
to - Target state

Outputs:

HistoryEntry - Entry suitable for session history

func (*StateMachine) TransitionReason

func (sm *StateMachine) TransitionReason(from, to AgentState) string

TransitionReason provides a human-readable description of a transition.

Inputs:

from - Source state
to - Target state

Outputs:

string - Description of why this transition occurs

func (*StateMachine) ValidTransitionsFrom

func (sm *StateMachine) ValidTransitionsFrom(from AgentState) []AgentState

ValidTransitionsFrom returns all valid transitions from a given state.

Description:

Returns a sorted slice of all valid target states for deterministic
iteration order. States are sorted alphabetically by string value.

Inputs:

from - The source state

Outputs:

[]AgentState - All valid target states, sorted alphabetically

Thread Safety: This method is safe for concurrent use.

type SymbolCandidate

type SymbolCandidate struct {
	// Name is the symbol name (e.g., "_setMaterial").
	Name string

	// Kind is the symbol kind (e.g., "method", "function").
	Kind string

	// FilePath is the file where the symbol is defined.
	FilePath string

	// Line is the line number where the symbol is defined.
	Line int

	// Receiver is the receiver type name for methods (e.g., "Context" for Context.Bind).
	// D3c: Used to show method ownership in the LLM prompt so the model can
	// distinguish validateHeader (method on Context) from validate (function).
	// Empty for non-method symbols.
	Receiver string

	// OutEdges is the number of outgoing call edges (functions this symbol calls).
	// IT-12 Rev 4: Populated when graph is available. Zero means unknown or no edges.
	OutEdges int

	// InEdges is the number of incoming call edges (functions that call this symbol).
	// IT-12 Rev 4: Populated when graph is available. Zero means unknown or no edges.
	InEdges int
}

SymbolCandidate represents a symbol found by keyword search of the index. IT-12: Used for conceptual symbol resolution when regex extraction produces words that don't match any actual symbol.

type ToolHistoryEntry

type ToolHistoryEntry struct {
	// Tool is the tool name that was called.
	Tool string `json:"tool"`

	// Summary is a brief description of what was found/returned.
	// Example: "Found 5 callers of parseConfig in pkg/config/"
	Summary string `json:"summary"`

	// Success indicates whether the tool call succeeded.
	Success bool `json:"success"`

	// StepNumber when this tool was called.
	StepNumber int `json:"step_number,omitempty"`
}

ToolHistoryEntry captures a tool execution with its outcome.

Description

Records what tool was called, what it found, and whether it succeeded. This gives the router context about what information is already available, enabling it to suggest the NEXT logical tool rather than repeating.

type ToolInvocation

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

	// Tool is the tool name.
	Tool string `json:"tool"`

	// Parameters are the tool input parameters.
	Parameters *ToolParameters `json:"parameters"`

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

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

	// Result contains the tool execution result.
	Result *ToolResult `json:"result,omitempty"`
}

ToolInvocation represents a single tool call.

type ToolParameters

type ToolParameters struct {
	// RawJSON contains the raw JSON parameters for flexible tool inputs.
	// Use encoding/json to unmarshal into tool-specific parameter structs.
	RawJSON []byte `json:"raw_json,omitempty"`

	// StringParams contains string-typed parameters.
	StringParams map[string]string `json:"string_params,omitempty"`

	// IntParams contains integer-typed parameters.
	IntParams map[string]int `json:"int_params,omitempty"`

	// BoolParams contains boolean-typed parameters.
	BoolParams map[string]bool `json:"bool_params,omitempty"`
}

ToolParameters represents validated parameters for a tool invocation.

This struct provides type-safe parameter storage instead of map[string]any. The RawJSON field allows flexible parameter passing while maintaining type safety at the API boundary.

func (*ToolParameters) GetBool

func (p *ToolParameters) GetBool(key string) (bool, bool)

GetBool returns a boolean parameter by key.

Inputs:

key - The parameter name

Outputs:

bool - The parameter value
bool - True if the parameter exists

func (*ToolParameters) GetInt

func (p *ToolParameters) GetInt(key string) (int, bool)

GetInt returns an integer parameter by key.

Inputs:

key - The parameter name

Outputs:

int - The parameter value
bool - True if the parameter exists

func (*ToolParameters) GetString

func (p *ToolParameters) GetString(key string) (string, bool)

GetString returns a string parameter by key.

Inputs:

key - The parameter name

Outputs:

string - The parameter value
bool - True if the parameter exists

type ToolResult

type ToolResult struct {
	// InvocationID links back to the invocation.
	InvocationID string `json:"invocation_id"`

	// Success indicates if the tool succeeded.
	Success bool `json:"success"`

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

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

	// Duration is how long execution took (serialized as nanoseconds).
	Duration time.Duration `json:"duration"`

	// TokensUsed is the estimated tokens in the output.
	TokensUsed int `json:"tokens_used"`

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

	// Truncated indicates if output was truncated.
	Truncated bool `json:"truncated"`

	// Tool is the tool name that produced this result.
	// IT_CRS_03 AC-3: Used by getSingleFormattedResult() for tool-specific
	// pass-through decisions instead of fragile substring matching.
	Tool string `json:"tool,omitempty"`

	// ProofDelta overrides the default CRS proof delta when non-zero.
	// IT_CRS_03 AC-8: Higher values = stronger signal (exact match = 2, fuzzy = 1).
	ProofDelta int `json:"proof_delta,omitempty"`
}

ToolResult contains the outcome of a tool execution.

Note: Duration is serialized as nanoseconds (int64) in JSON per Go's default time.Duration marshaling. Use DurationMs() for milliseconds.

func (*ToolResult) DurationMs

func (r *ToolResult) DurationMs() int64

DurationMs returns the duration in milliseconds.

Outputs:

int64 - Duration in milliseconds

type ToolRouter

type ToolRouter interface {
	// SelectTool chooses the best tool for the given query and context.
	//
	// Inputs:
	//   - ctx: Context for cancellation/timeout.
	//   - query: The user's question or request.
	//   - availableTools: Tools currently available for selection.
	//   - codeContext: Optional context about the codebase.
	//
	// Outputs:
	//   - *ToolRouterSelection: The selected tool with confidence.
	//   - error: Non-nil if routing fails (caller should fall back to main LLM).
	SelectTool(ctx context.Context, query string, availableTools []ToolRouterSpec, codeContext *ToolRouterCodeContext) (*ToolRouterSelection, error)

	// Model returns the model being used for routing.
	Model() string

	// Close releases any resources held by the router.
	Close() error
}

ToolRouter selects the appropriate tool for a user query using a fast micro LLM.

Description

ToolRouter uses a small, fast model (like granite4:micro-h) to pre-select tools before the main reasoning LLM processes the request. This allows tool selection to complete in ~50-100ms instead of the full LLM inference time.

Thread Safety

Implementations must be safe for concurrent use.

type ToolRouterCodeContext

type ToolRouterCodeContext struct {
	Language       string            `json:"language,omitempty"`
	Files          int               `json:"files,omitempty"`
	Symbols        int               `json:"symbols,omitempty"`
	CurrentFile    string            `json:"current_file,omitempty"`
	RecentTools    []string          `json:"recent_tools,omitempty"`
	PreviousErrors []ToolRouterError `json:"previous_errors,omitempty"`

	// ToolHistory contains the sequence of tools used with their results.
	// This enables history-aware routing where the router can see what
	// was already tried and what was learned from each tool.
	ToolHistory []ToolHistoryEntry `json:"tool_history,omitempty"`

	// Progress describes the current state of information gathering.
	// Example: "Found 3 entry points, read 2 files, identified main handler"
	Progress string `json:"progress,omitempty"`

	// StepNumber is the current execution step (1-indexed).
	StepNumber int `json:"step_number,omitempty"`
}

ToolRouterCodeContext provides context about the codebase.

History-Aware Routing

This struct is designed to leverage Mamba2's O(n) linear complexity and 1M token context window. By including tool history with summaries, the router can make informed decisions about what information is still needed rather than suggesting the same tools repeatedly.

type ToolRouterError

type ToolRouterError struct {
	Tool      string `json:"tool"`
	Error     string `json:"error"`
	Timestamp string `json:"timestamp,omitempty"`
}

ToolRouterError captures a failed tool attempt for router feedback.

type ToolRouterSelection

type ToolRouterSelection struct {
	// Tool is the selected tool name.
	Tool string `json:"tool"`

	// Confidence is the router's confidence (0.0-1.0).
	Confidence float64 `json:"confidence"`

	// ParamsHint contains optional parameter suggestions.
	ParamsHint map[string]string `json:"params_hint,omitempty"`

	// Reasoning explains why this tool was selected.
	Reasoning string `json:"reasoning,omitempty"`

	// Duration is how long the routing decision took.
	Duration time.Duration `json:"duration,omitempty"`
}

ToolRouterSelection represents the router's decision.

type ToolRouterSpec

type ToolRouterSpec struct {
	// Name is the tool name.
	Name string `json:"name"`

	// Description explains what the tool does.
	Description string `json:"description"`

	// BestFor contains keywords that should trigger this tool.
	// CB-31e: Now populated from WhenToUse.Keywords.
	BestFor []string `json:"best_for,omitempty"`

	// UseWhen describes when to use this tool.
	UseWhen string `json:"use_when,omitempty"`

	// AvoidWhen describes when NOT to use this tool.
	AvoidWhen string `json:"avoid_when,omitempty"`

	// InsteadOf lists tools this should replace.
	InsteadOf []ToolRouterSubstitution `json:"instead_of,omitempty"`

	// Params lists parameter names.
	Params []string `json:"params,omitempty"`

	// Category is the tool category.
	Category string `json:"category,omitempty"`
}

ToolRouterSpec describes a tool for the router.

CB-31e: Extended with UseWhen, AvoidWhen, and InsteadOf fields to provide structured guidance for tool selection.

type ToolRouterSubstitution

type ToolRouterSubstitution struct {
	// Tool is the name of the tool to replace.
	Tool string `json:"tool"`

	// When describes when substitution applies.
	When string `json:"when"`
}

ToolRouterSubstitution describes a tool substitution for the router.

Directories

Path Synopsis
Package classifier provides query classification for tool forcing decisions.
Package classifier provides query classification for tool forcing decisions.
Package context provides context management for the agent loop.
Package context provides context management for the agent loop.
Package control provides control flow hardening for the agent loop.
Package control provides control flow hardening for the agent loop.
Package events provides event types and handling for the agent loop.
Package events provides event types and handling for the agent loop.
Package grounding provides anti-hallucination validation for LLM responses.
Package grounding provides anti-hallucination validation for LLM responses.
Package llm provides the LLM client interface for the agent loop.
Package llm provides the LLM client interface for the agent loop.
Package mcts implements Monte Carlo Tree Search-inspired plan tree reasoning.
Package mcts implements Monte Carlo Tree Search-inspired plan tree reasoning.
algorithms
Package algorithms provides pure function implementations for the MCTS system.
Package algorithms provides pure function implementations for the MCTS system.
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.
crs/indexes
Package indexes provides the 6 index implementations for CRS.
Package indexes provides the 6 index implementations for CRS.
Package phases implements the agent state machine phases.
Package phases implements the agent state machine phases.
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.
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.
Package routing provides tool selection using a fast micro LLM.
Package routing provides tool selection using a fast micro LLM.
Package safety provides safety gate functionality for the agent loop.
Package safety provides safety gate functionality for the agent loop.

Jump to

Keyboard shortcuts

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