mcts

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: 27 Imported by: 0

Documentation

Overview

Package mcts implements Monte Carlo Tree Search-inspired plan tree reasoning.

This package provides MCTS-based exploration of code change plans, enabling the agent to explore multiple approaches before committing to a strategy.

Architecture

The package consists of several key components:

  • PlanTree: Root structure containing the exploration tree
  • PlanNode: Individual node representing a plan step or alternative
  • PlannedAction: Validated action to be executed (edit, create, delete)
  • TreeBudget: Resource limits (nodes, depth, tokens, time, cost)
  • MCTSController: Orchestrates the MCTS loop (select, expand, simulate, backpropagate)
  • Simulator: Evaluates plan nodes via tiered simulation

MCTS Phases

1. SELECT: Pick promising node using UCB1 formula 2. EXPAND: Generate alternative approaches via LLM 3. SIMULATE: Evaluate node quality (syntax, lint, tests, blast radius) 4. BACKPROPAGATE: Update scores up the tree

Thread Safety

All exported types are safe for concurrent use unless documented otherwise. PlanNode uses atomic operations for visit/score updates, and mutex for structural modifications.

Budget Limits

TreeBudget enforces multiple limits:

  • MaxNodes: Maximum nodes to explore
  • MaxDepth: Maximum plan depth
  • TimeLimit: Wall clock limit
  • LLMCallLimit: Maximum LLM calls
  • CostLimitUSD: Maximum LLM cost

Security

PlannedAction validation provides:

  • Path traversal protection
  • Shell metacharacter detection
  • UTF-8 validation
  • Project boundary enforcement

Observability

The package integrates with OpenTelemetry for:

  • Distributed tracing of MCTS phases
  • Prometheus metrics for cost/latency/success
  • Structured logging with slog

Index

Constants

This section is empty.

Variables

View Source
var (
	// Budget errors
	ErrBudgetExhausted      = errors.New("mcts budget exhausted")
	ErrTimeLimitExceeded    = errors.New("mcts time limit exceeded")
	ErrNodeLimitExceeded    = errors.New("mcts node limit exceeded")
	ErrDepthLimitExceeded   = errors.New("mcts depth limit exceeded")
	ErrLLMCallLimitExceeded = errors.New("mcts LLM call limit exceeded")
	ErrCostLimitExceeded    = errors.New("mcts cost limit exceeded")

	// Validation errors
	ErrPathOutsideBoundary = errors.New("file path is outside project boundary")
	ErrInvalidActionType   = errors.New("invalid action type")
	ErrInvalidUTF8         = errors.New("code diff contains invalid UTF-8")
	ErrUnsafePath          = errors.New("file path contains unsafe characters")
	ErrEmptyDescription    = errors.New("action description is empty")
	ErrPathTooLong         = errors.New("file path exceeds maximum length")
	ErrCodeDiffTooLarge    = errors.New("code diff exceeds maximum size")
	ErrActionNotValidated  = errors.New("action used without validation")

	// Circuit breaker errors
	ErrCircuitOpen = errors.New("circuit breaker is open")

	// Tree errors
	ErrNoValidPath        = errors.New("no valid path found in tree")
	ErrTreeNotInitialized = errors.New("plan tree not initialized")
	ErrNodeAbandoned      = errors.New("node has been abandoned")
)

Sentinel errors for the mcts package.

ValidActionTypes is the exhaustive list of valid action types.

Functions

func AddMCTSEvent

func AddMCTSEvent(span trace.Span, name string, attrs ...attribute.KeyValue)

AddMCTSEvent adds an event to the current span.

Thread Safety: Safe for concurrent use.

func LoggerWithTrace

func LoggerWithTrace(ctx context.Context, logger *slog.Logger) *slog.Logger

LoggerWithTrace returns a logger with trace context.

Inputs:

  • ctx: Context that may contain trace information.
  • logger: Base logger.

Outputs:

  • *slog.Logger: Logger with trace_id and span_id if available.

func PUCTScore

func PUCTScore(node *PlanNode, parentVisits, prior, C float64) float64

PUCTScore calculates the PUCT score for a node.

Inputs:

  • node: The node to score.
  • parentVisits: Visit count of the parent.
  • prior: Prior probability for this node.
  • C: Exploration constant.

Outputs:

  • float64: The PUCT score.

func RecordBudgetUtilization

func RecordBudgetUtilization(ctx context.Context, usage BudgetUtilizationStats)

RecordBudgetUtilization records budget utilization metrics.

Inputs:

  • ctx: Context for metric recording.
  • usage: Budget utilization statistics.

Thread Safety: Safe for concurrent use.

func RecordCircuitBreakerState

func RecordCircuitBreakerState(ctx context.Context, state CircuitState)

RecordCircuitBreakerState records the circuit breaker state change.

Inputs:

  • ctx: Context for metric recording.
  • state: New circuit breaker state.

Thread Safety: Safe for concurrent use.

func RecordDegradation

func RecordDegradation(ctx context.Context, from, to TreeDegradation)

RecordDegradation records a degradation event.

Inputs:

  • ctx: Context for metric recording.
  • from: Previous degradation level.
  • to: New degradation level.

Thread Safety: Safe for concurrent use.

func RecordLLMCall

func RecordLLMCall(ctx context.Context, tokens int, costUSD float64, success bool)

RecordLLMCall records metrics for an LLM call.

Inputs:

  • ctx: Context for metric recording.
  • tokens: Number of tokens used.
  • costUSD: Cost in USD.
  • success: Whether the call succeeded.

Thread Safety: Safe for concurrent use.

func RecordNodeAbandoned

func RecordNodeAbandoned(ctx context.Context, reason string)

RecordNodeAbandoned records that a node was abandoned.

Inputs:

  • ctx: Context for metric recording.
  • reason: Reason for abandonment.

Thread Safety: Safe for concurrent use.

func RecordNodeCreated

func RecordNodeCreated(ctx context.Context)

RecordNodeCreated records that a node was created.

Thread Safety: Safe for concurrent use.

func RecordNodesPruned

func RecordNodesPruned(ctx context.Context, count int)

RecordNodesPruned records the number of nodes pruned.

Thread Safety: Safe for concurrent use.

func RecordSimulation

func RecordSimulation(ctx context.Context, tier SimulationTier, score float64, duration time.Duration)

RecordSimulation records metrics for a simulation.

Inputs:

  • ctx: Context for metric recording.
  • tier: Simulation tier (quick, standard, full).
  • score: Simulation score.
  • duration: Time taken for simulation.

Thread Safety: Safe for concurrent use.

func RecordTreeCompletion

func RecordTreeCompletion(ctx context.Context, stats TreeCompletionStats)

RecordTreeCompletion records metrics at tree completion.

Inputs:

  • ctx: Context for metric recording.
  • stats: Tree completion statistics.

Thread Safety: Safe for concurrent use.

func SelectWithVirtualLoss

func SelectWithVirtualLoss(tree *PlanTree, policy SelectionPolicy, virtualLoss float64) (*PlanNode, []*PlanNode, func())

SelectWithVirtualLoss performs selection while applying virtual loss. This is used for parallel MCTS to discourage multiple workers from selecting the same path.

Inputs:

  • tree: The plan tree to traverse.
  • policy: The selection policy to use.
  • virtualLoss: The virtual loss to apply during traversal.

Outputs:

  • *PlanNode: The selected leaf node.
  • []*PlanNode: The path from root to leaf.
  • func(): Release function to call after backpropagation.

Thread Safety: Safe for concurrent use.

func SetMCTSSpanResult

func SetMCTSSpanResult(span trace.Span, success bool, nodesExplored int64, bestScore float64)

SetMCTSSpanResult sets result attributes on an MCTS span.

Thread Safety: Safe for concurrent use.

func ShouldExpand

func ShouldExpand(node *PlanNode, config ProgressiveWideningConfig) (bool, int)

ShouldExpand determines whether a node should be expanded.

Inputs:

  • node: The node to check.
  • config: Progressive widening configuration.

Outputs:

  • bool: True if expansion is allowed.
  • int: Maximum number of new children allowed.

func StartMCTSSpan

func StartMCTSSpan(ctx context.Context, operation, task string) (context.Context, trace.Span)

StartMCTSSpan creates a span for MCTS operations.

Inputs:

  • ctx: Parent context.
  • operation: Operation name.
  • task: Task description.

Outputs:

  • context.Context: Context with span.
  • trace.Span: The created span.

Thread Safety: Safe for concurrent use.

func TreeTraversal

func TreeTraversal(tree *PlanTree, policy SelectionPolicy) (*PlanNode, []*PlanNode)

TreeTraversal traverses from root to leaf using the given selection policy.

Inputs:

  • tree: The plan tree to traverse.
  • policy: The selection policy to use.

Outputs:

  • *PlanNode: The selected leaf node.
  • []*PlanNode: The path from root to leaf.

Thread Safety: Safe for concurrent use if policy is thread-safe.

func UCB1Score

func UCB1Score(node *PlanNode, parentVisits float64, C float64) float64

UCB1Score calculates the UCB1 score for a node.

Inputs:

  • node: The node to score.
  • parentVisits: Visit count of the parent.
  • C: Exploration constant.

Outputs:

  • float64: The UCB1 score (infinity for unvisited nodes).

Types

type ActionExecutor

type ActionExecutor interface {
	ExecuteAction(ctx context.Context, action *PlannedAction) error
}

ActionExecutor executes planned actions.

Thread Safety: Implementations must be safe for concurrent use.

type ActionType

type ActionType string

ActionType represents valid action types.

const (
	ActionTypeEdit    ActionType = "edit"
	ActionTypeCreate  ActionType = "create"
	ActionTypeDelete  ActionType = "delete"
	ActionTypeRunTest ActionType = "run_test"
)

func (ActionType) String

func (a ActionType) String() string

String returns the string representation of the action type.

type ActionValidationConfig

type ActionValidationConfig struct {
	MaxPathLength    int      // Default: 500
	MaxCodeDiffBytes int      // Default: 100KB
	AllowedLanguages []string // Default: common languages
}

ActionValidationConfig contains validation limits.

func DefaultActionValidationConfig

func DefaultActionValidationConfig() ActionValidationConfig

DefaultActionValidationConfig returns sensible defaults.

type AlgorithmConfig

type AlgorithmConfig struct {
	ExplorationConstant   float64 `json:"exploration_constant" yaml:"exploration_constant"`
	MinVisitsBeforeExpand int     `json:"min_visits_before_expand" yaml:"min_visits_before_expand"`
	MaxAlternatives       int     `json:"max_alternatives" yaml:"max_alternatives"`
	SimulationDepth       int     `json:"simulation_depth" yaml:"simulation_depth"`
}

AlgorithmConfig contains MCTS algorithm settings.

type AuditAction

type AuditAction string

AuditAction represents an action type in the audit log.

const (
	// AuditActionExpand records node expansion.
	AuditActionExpand AuditAction = "expand"

	// AuditActionSimulate records simulation execution.
	AuditActionSimulate AuditAction = "simulate"

	// AuditActionBackprop records score backpropagation.
	AuditActionBackprop AuditAction = "backprop"

	// AuditActionAbandon records node abandonment.
	AuditActionAbandon AuditAction = "abandon"

	// AuditActionPrune records tree pruning.
	AuditActionPrune AuditAction = "prune"

	// AuditActionSelect records node selection.
	AuditActionSelect AuditAction = "select"
)

func (AuditAction) String

func (a AuditAction) String() string

String returns the string representation.

type AuditEntry

type AuditEntry struct {
	// Timestamp when this entry was created (Unix milliseconds UTC).
	Timestamp int64 `json:"timestamp"`

	// Action is the type of operation performed.
	Action AuditAction `json:"action"`

	// NodeID identifies the affected node.
	NodeID string `json:"node_id"`

	// NodeHash is the content hash of the node at this time.
	NodeHash string `json:"node_hash,omitempty"`

	// ParentHash is the content hash of the parent node.
	ParentHash string `json:"parent_hash,omitempty"`

	// LLMRequestID links to the LLM request that generated this action.
	LLMRequestID string `json:"llm_request_id,omitempty"`

	// Score is the score associated with this action.
	Score float64 `json:"score,omitempty"`

	// Details contains additional action-specific information.
	Details string `json:"details,omitempty"`

	// ChainHash is the running hash at this entry (computed during Record).
	ChainHash string `json:"chain_hash,omitempty"`
}

AuditEntry records an action in the tree for audit trail.

Each entry is immutable once created. The hash chain ensures the integrity of the audit log can be verified.

func NewAuditEntry

func NewAuditEntry(action AuditAction, nodeID string) *AuditEntry

NewAuditEntry creates a new audit entry.

Inputs:

  • action: The action being recorded.
  • nodeID: ID of the affected node.

Outputs:

  • *AuditEntry: A new entry with timestamp set.

func (*AuditEntry) WithDetails

func (e *AuditEntry) WithDetails(details string) *AuditEntry

WithDetails sets the details.

func (*AuditEntry) WithLLMRequestID

func (e *AuditEntry) WithLLMRequestID(id string) *AuditEntry

WithLLMRequestID sets the LLM request ID.

func (*AuditEntry) WithNodeHash

func (e *AuditEntry) WithNodeHash(hash string) *AuditEntry

WithNodeHash sets the node hash.

func (*AuditEntry) WithParentHash

func (e *AuditEntry) WithParentHash(hash string) *AuditEntry

WithParentHash sets the parent hash.

func (*AuditEntry) WithScore

func (e *AuditEntry) WithScore(score float64) *AuditEntry

WithScore sets the score.

type AuditLog

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

AuditLog maintains an immutable audit trail with hash chain verification.

The audit log uses a hash chain where each entry includes a hash of itself combined with the previous hash. This allows verification of the log's integrity.

Thread Safety: Safe for concurrent use.

func NewAuditLog

func NewAuditLog() *AuditLog

NewAuditLog creates a new audit log.

Outputs:

  • *AuditLog: An empty audit log with genesis hash.

Thread Safety: The returned log is safe for concurrent use.

func (*AuditLog) CurrentHash

func (l *AuditLog) CurrentHash() string

CurrentHash returns the current chain hash.

Thread Safety: Safe for concurrent use.

func (*AuditLog) Entries

func (l *AuditLog) Entries() []AuditEntry

Entries returns a copy of all audit entries.

Outputs:

  • []AuditEntry: A copy of all entries.

Thread Safety: Safe for concurrent use.

func (*AuditLog) EntriesAfter

func (l *AuditLog) EntriesAfter(after time.Time) []AuditEntry

EntriesAfter returns entries recorded after the given timestamp.

Inputs:

  • after: Return entries after this time.

Outputs:

  • []AuditEntry: Entries after the given time.

Thread Safety: Safe for concurrent use.

func (*AuditLog) EntriesByAction

func (l *AuditLog) EntriesByAction(action AuditAction) []AuditEntry

EntriesByAction returns entries with the given action type.

Inputs:

  • action: The action type to filter by.

Outputs:

  • []AuditEntry: Entries with the given action.

Thread Safety: Safe for concurrent use.

func (*AuditLog) EntriesByNode

func (l *AuditLog) EntriesByNode(nodeID string) []AuditEntry

EntriesByNode returns entries for a specific node.

Inputs:

  • nodeID: The node ID to filter by.

Outputs:

  • []AuditEntry: Entries for the given node.

Thread Safety: Safe for concurrent use.

func (*AuditLog) Len

func (l *AuditLog) Len() int

Len returns the number of entries.

Thread Safety: Safe for concurrent use.

func (*AuditLog) Record

func (l *AuditLog) Record(entry AuditEntry)

Record adds an entry to the audit log.

The entry's timestamp is set to the current time, and a chain hash is computed that includes the previous hash and entry data.

Inputs:

  • entry: The audit entry to record.

Thread Safety: Safe for concurrent use.

func (*AuditLog) Summary

func (l *AuditLog) Summary() AuditSummary

Summary returns a summary of the audit log.

Outputs:

  • AuditSummary: Summary statistics.

Thread Safety: Safe for concurrent use.

func (*AuditLog) Verify

func (l *AuditLog) Verify() bool

Verify checks the integrity of the audit log.

Recomputes the hash chain from genesis and verifies it matches the current hash. Returns false if any tampering is detected.

Outputs:

  • bool: True if the log is intact, false if tampered.

Thread Safety: Safe for concurrent use.

type AuditSummary

type AuditSummary struct {
	TotalEntries int                 `json:"total_entries"`
	FirstEntry   int64               `json:"first_entry,omitempty"` // Unix milliseconds UTC
	LastEntry    int64               `json:"last_entry,omitempty"`  // Unix milliseconds UTC
	ActionCounts map[AuditAction]int `json:"action_counts"`
}

AuditSummary contains summary statistics for the audit log.

type BasicSecurityScanner

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

BasicSecurityScanner provides simple pattern-based security scanning.

This is a lightweight scanner for use during MCTS simulation. For production, integrate with CB-23 (security analysis) for deeper scanning.

Thread Safety: Safe for concurrent use.

func NewBasicSecurityScanner

func NewBasicSecurityScanner() *BasicSecurityScanner

NewBasicSecurityScanner creates a scanner with default patterns.

Outputs:

  • *BasicSecurityScanner: Ready to use security scanner.

func NewBasicSecurityScannerWithPatterns

func NewBasicSecurityScannerWithPatterns(patterns []SecurityPattern) *BasicSecurityScanner

NewBasicSecurityScannerWithPatterns creates a scanner with custom patterns.

Inputs:

  • patterns: Custom security patterns to check.

Outputs:

  • *BasicSecurityScanner: Ready to use security scanner.

func (*BasicSecurityScanner) AddPattern

func (s *BasicSecurityScanner) AddPattern(pattern SecurityPattern)

AddPattern adds a custom security pattern.

func (*BasicSecurityScanner) Patterns

func (s *BasicSecurityScanner) Patterns() []SecurityPattern

Patterns returns the configured security patterns.

func (*BasicSecurityScanner) ScanCode

ScanCode scans code for security issues.

Inputs:

  • ctx: Context for cancellation.
  • code: The code to scan.

Outputs:

  • *SecurityScanResult: Scan results with score and issues.
  • error: Non-nil on context cancellation.

ReDoS Mitigation:

  • Context is checked between each pattern for cancellation
  • Match count is limited to maxMatchesPerPattern per pattern
  • Input size should be bounded by caller (e.g., ActionValidationConfig.MaxCodeDiffBytes)

func (*BasicSecurityScanner) ScanCodeWithLanguage

func (s *BasicSecurityScanner) ScanCodeWithLanguage(ctx context.Context, code, language string) (*SecurityScanResult, error)

ScanCodeWithLanguage scans code with language-specific patterns.

Inputs:

  • ctx: Context for cancellation.
  • code: The code to scan.
  • language: The programming language for language-specific patterns.

Outputs:

  • *SecurityScanResult: Scan results with score and issues.
  • error: Non-nil on context cancellation.

ReDoS Mitigation: Same protections as ScanCode apply.

type BlastRadiusAnalyzer

type BlastRadiusAnalyzer interface {
	Analyze(ctx context.Context, filePath string, includeTests bool) (*BlastRadiusResult, error)
}

BlastRadiusAnalyzer analyzes change impact.

Contract:

  • Must respect ctx for cancellation
  • Return TotalAffected as count of files/functions affected by change
  • Return error only for infrastructure failures

type BlastRadiusResult

type BlastRadiusResult struct {
	TotalAffected int      // Number of files/symbols affected
	AffectedFiles []string // Paths of affected files
}

BlastRadiusResult contains impact analysis.

type BudgetConfig

type BudgetConfig struct {
	MaxNodes      int           `json:"max_nodes" yaml:"max_nodes"`
	MaxDepth      int           `json:"max_depth" yaml:"max_depth"`
	MaxExpansions int           `json:"max_expansions" yaml:"max_expansions"`
	TimeLimit     time.Duration `json:"time_limit" yaml:"time_limit"`
	LLMTokenLimit int           `json:"llm_token_limit" yaml:"llm_token_limit"`
	LLMCallLimit  int           `json:"llm_call_limit" yaml:"llm_call_limit"`
	CostLimitUSD  float64       `json:"cost_limit_usd" yaml:"cost_limit_usd"`
}

BudgetConfig contains budget-related settings.

func (BudgetConfig) ToTreeBudgetConfig

func (c BudgetConfig) ToTreeBudgetConfig() TreeBudgetConfig

ToTreeBudgetConfig converts BudgetConfig to TreeBudgetConfig.

Outputs:

  • TreeBudgetConfig: Budget configuration for tree operations.

type BudgetRemaining

type BudgetRemaining struct {
	Nodes    int           `json:"nodes"`
	Time     time.Duration `json:"time"`
	LLMCalls int           `json:"llm_calls"`
	Tokens   int           `json:"tokens"`
	CostUSD  float64       `json:"cost_usd"`
}

BudgetRemaining contains remaining budget values.

type BudgetUtilizationStats

type BudgetUtilizationStats struct {
	NodesUsed   int64
	NodesMax    int64
	TokensUsed  int64
	TokensMax   int64
	CallsUsed   int64
	CallsMax    int64
	CostUsedUSD float64
	CostMaxUSD  float64
	Elapsed     time.Duration
	TimeLimit   time.Duration
}

BudgetUtilizationStats contains budget utilization information.

type CircuitBreaker

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

CircuitBreaker provides circuit breaker protection for LLM calls.

The circuit breaker pattern prevents cascading failures by temporarily blocking requests after repeated failures. It has three states:

  • Closed: Normal operation, requests pass through.
  • Open: After FailureThreshold failures, requests are rejected.
  • Half-Open: After OpenDuration, limited requests test recovery.

Thread Safety: Safe for concurrent use.

func NewCircuitBreaker

func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker.

Inputs:

  • config: Circuit breaker configuration.

Outputs:

  • *CircuitBreaker: Ready to use circuit breaker.

Thread Safety: The returned circuit breaker is safe for concurrent use.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() (bool, func())

Allow checks if a request should be allowed.

Outputs:

  • bool: True if the request should proceed.
  • func(): Release function to call when request completes (may be nil).

Usage:

allowed, release := cb.Allow()
if !allowed {
    return ErrCircuitOpen
}
if release != nil {
    defer release()
}
// ... make request ...

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(ctx context.Context, fn func() error) error

Execute wraps a function with circuit breaker protection.

Inputs:

  • ctx: Context for the operation.
  • fn: The function to execute.

Outputs:

  • error: ErrCircuitOpen if rejected, or the error from fn.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed request.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful request.

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset resets the circuit breaker to closed state.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns the current circuit state.

func (*CircuitBreaker) Stats

func (cb *CircuitBreaker) Stats() CircuitBreakerStats

Stats returns circuit breaker statistics.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// FailureThreshold is the number of failures before opening (default: 3).
	FailureThreshold int

	// SuccessThreshold is successes needed to close from half-open (default: 2).
	SuccessThreshold int

	// OpenDuration is how long to stay open before testing recovery (default: 30s).
	OpenDuration time.Duration

	// HalfOpenMax is max concurrent requests in half-open state (default: 1).
	HalfOpenMax int
}

CircuitBreakerConfig configures the circuit breaker behavior.

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns sensible defaults.

type CircuitBreakerStats

type CircuitBreakerStats struct {
	State           string    `json:"state"`
	TotalCalls      int64     `json:"total_calls"`
	TotalFailures   int64     `json:"total_failures"`
	TotalRejections int64     `json:"total_rejections"`
	CurrentFailures int       `json:"current_failures"`
	LastStateChange time.Time `json:"last_state_change"`
}

CircuitBreakerStats contains circuit breaker statistics.

type CircuitState

type CircuitState int

CircuitState represents the circuit breaker state.

const (
	// CircuitClosed is normal operation - requests pass through.
	CircuitClosed CircuitState = iota
	// CircuitOpen means too many failures - requests are rejected.
	CircuitOpen
	// CircuitHalfOpen is testing recovery - limited requests allowed.
	CircuitHalfOpen
)

func (CircuitState) String

func (s CircuitState) String() string

String returns a human-readable state name.

type DegradationConfig

type DegradationConfig struct {
	// ConsecutiveFailuresForReduced is failures before reduced mode (default: 2).
	ConsecutiveFailuresForReduced int

	// ConsecutiveFailuresForMinimal is failures before minimal mode (default: 4).
	ConsecutiveFailuresForMinimal int

	// ConsecutiveFailuresForLinear is failures before linear fallback (default: 6).
	ConsecutiveFailuresForLinear int

	// CircuitOpenDegradation is the level when circuit opens (default: Linear).
	CircuitOpenDegradation TreeDegradation

	// SuccessesForRecovery is successes to recover one level (default: 3).
	SuccessesForRecovery int

	// NotifyOnDegradation enables callbacks on degradation events.
	NotifyOnDegradation bool
}

DegradationConfig configures degradation behavior.

func DefaultDegradationConfig

func DefaultDegradationConfig() DegradationConfig

DefaultDegradationConfig returns sensible defaults.

type DegradationManager

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

DegradationManager manages degradation state.

It progressively reduces tree mode capabilities in response to failures, and recovers after sustained successes. This provides graceful degradation when LLM calls are failing or expensive.

Thread Safety: Safe for concurrent use.

func NewDegradationManager

func NewDegradationManager(config DegradationConfig, cb *CircuitBreaker) *DegradationManager

NewDegradationManager creates a degradation manager.

Inputs:

  • config: Degradation configuration.
  • cb: Optional circuit breaker for coordination (may be nil).

Outputs:

  • *DegradationManager: Ready to use degradation manager.

Thread Safety: The returned manager is safe for concurrent use.

func (*DegradationManager) Config

Config returns the degradation configuration.

func (*DegradationManager) CurrentLevel

func (m *DegradationManager) CurrentLevel() TreeDegradation

CurrentLevel returns the current degradation level.

func (*DegradationManager) GetBudgetForLevel

func (m *DegradationManager) GetBudgetForLevel() TreeBudgetConfig

GetBudgetForLevel returns an appropriate budget for the current degradation level.

Outputs:

  • TreeBudgetConfig: Budget configuration appropriate for the current level.

func (*DegradationManager) OnDegradation

func (m *DegradationManager) OnDegradation(fn func(from, to TreeDegradation, reason string))

OnDegradation sets a callback for degradation events.

func (*DegradationManager) RecordFailure

func (m *DegradationManager) RecordFailure()

RecordFailure records a failed operation.

func (*DegradationManager) RecordSuccess

func (m *DegradationManager) RecordSuccess()

RecordSuccess records a successful operation.

func (*DegradationManager) Reset

func (m *DegradationManager) Reset()

Reset resets the degradation manager to normal level.

func (*DegradationManager) ShouldUseLinearFallback

func (m *DegradationManager) ShouldUseLinearFallback() bool

ShouldUseLinearFallback returns true if we should skip tree mode entirely.

func (*DegradationManager) Status

Status returns current degradation status for observability.

type DegradationStatus

type DegradationStatus struct {
	Level                string    `json:"level"`
	ConsecutiveFailures  int       `json:"consecutive_failures"`
	ConsecutiveSuccesses int       `json:"consecutive_successes"`
	LastDegradation      time.Time `json:"last_degradation,omitempty"`
	CircuitState         string    `json:"circuit_state"`
}

DegradationStatus contains current status.

type ExpansionConfig

type ExpansionConfig struct {
	// MaxChildren is the maximum number of children to generate per expansion.
	// Default: 3
	MaxChildren int

	// MinChildren is the minimum number of children to generate.
	// If LLM returns fewer, the expansion is considered failed.
	// Default: 1
	MinChildren int

	// GeneratePriors controls whether to generate PUCT priors.
	// If true, expander should return confidence scores for each child.
	// Default: true
	GeneratePriors bool

	// IncludeActions controls whether to generate PlannedActions for children.
	// If false, only descriptions are generated (cheaper but less precise).
	// Default: true
	IncludeActions bool
}

ExpansionConfig configures expansion behavior.

func DefaultExpansionConfig

func DefaultExpansionConfig() ExpansionConfig

DefaultExpansionConfig returns sensible defaults.

type ExpansionContext

type ExpansionContext struct {
	// Task is the original task description.
	Task string

	// PathFromRoot describes the decisions made to reach this node.
	PathFromRoot []string

	// CurrentDepth is how deep in the tree we are.
	CurrentDepth int

	// SiblingDescriptions are the descriptions of sibling nodes.
	// Helps the LLM generate diverse alternatives.
	SiblingDescriptions []string

	// ParentAction is the action of the parent node (if any).
	ParentAction *PlannedAction

	// BudgetRemaining shows how much budget is left.
	BudgetRemaining BudgetRemaining
}

ContextExpander extracts expansion context from the tree.

This provides information needed by an LLM to generate meaningful expansions.

func BuildExpansionContext

func BuildExpansionContext(tree *PlanTree, node *PlanNode, budget *TreeBudget) *ExpansionContext

BuildExpansionContext creates context for expansion.

Inputs:

  • tree: The plan tree.
  • node: The node being expanded.
  • budget: The current budget.

Outputs:

  • *ExpansionContext: Context for the expansion.

type ExpansionResult

type ExpansionResult struct {
	// Children are the generated child nodes.
	Children []*PlanNode

	// Priors are the PUCT prior probabilities for each child.
	// Same length as Children, or nil if not generated.
	Priors []float64

	// TokensUsed is the number of LLM tokens consumed.
	TokensUsed int

	// CostUSD is the cost of the expansion operation.
	CostUSD float64
}

ExpansionResult contains the output of an expansion operation.

type HybridScannerMetrics

type HybridScannerMetrics struct {
	ASTScans      int64
	RegexScans    int64
	ASTFallbacks  int64
	TestsExcluded int64
	// contains filtered or unexported fields
}

HybridScannerMetrics tracks scanner usage for observability.

type HybridScannerOption

type HybridScannerOption func(*HybridSecurityScanner)

HybridScannerOption configures the HybridSecurityScanner.

func WithCustomRegexPatterns

func WithCustomRegexPatterns(patterns []SecurityPattern) HybridScannerOption

WithCustomRegexPatterns provides custom regex patterns for fallback scanning.

func WithExcludeTests

func WithExcludeTests(exclude bool) HybridScannerOption

WithExcludeTests configures the scanner to skip test files.

Test files are detected by patterns:

  • *_test.go (Go)
  • test_*.py, *_test.py (Python)
  • *.test.js, *.test.ts, *.spec.js, *.spec.ts (JavaScript/TypeScript)

type HybridSecurityScanner

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

HybridSecurityScanner combines AST-based and regex-based security scanning.

Description

For known languages (Go, Python, JavaScript, TypeScript), uses tree-sitter AST analysis which automatically excludes patterns in comments and strings. For unknown languages or when AST parsing fails, falls back to regex-based BasicSecurityScanner.

This addresses the "Regex Castle" problem where security patterns in comments trigger false positives (e.g., "// TODO: Remove exec.Command").

Thread Safety

Safe for concurrent use. The scanner maintains no mutable state after construction. Both underlying scanners are also thread-safe.

func NewHybridSecurityScanner

func NewHybridSecurityScanner(opts ...HybridScannerOption) *HybridSecurityScanner

NewHybridSecurityScanner creates a new hybrid scanner.

Inputs

  • opts: Optional configuration options.

Outputs

  • *HybridSecurityScanner: Ready to use hybrid scanner.

func (*HybridSecurityScanner) Metrics

Metrics returns a copy of the current scanner metrics.

Thread Safety

Safe for concurrent use.

func (*HybridSecurityScanner) ResetMetrics

func (s *HybridSecurityScanner) ResetMetrics()

ResetMetrics resets all scanner metrics to zero.

Thread Safety

Safe for concurrent use.

func (*HybridSecurityScanner) ScanCode

func (s *HybridSecurityScanner) ScanCode(ctx context.Context, code, language, filePath string) (*SecurityScanResult, error)

ScanCode scans code for security issues using the optimal method.

Description

Determines the best scanning method based on the language:

  • For Go, Python, JavaScript, TypeScript: Uses AST-based scanning
  • For other languages or unknown: Falls back to regex-based scanning
  • If AST parsing fails: Falls back to regex with a warning flag

Inputs

  • ctx: Context for cancellation.
  • code: The source code to scan.
  • language: Programming language (e.g., "go", "python"). Empty = unknown.
  • filePath: File path for reporting and test file detection.

Outputs

  • *SecurityScanResult: Scan results with score and issues.
  • error: Non-nil on context cancellation.

Thread Safety

Safe for concurrent use.

func (*HybridSecurityScanner) ScanCodeWithMode

func (s *HybridSecurityScanner) ScanCodeWithMode(ctx context.Context, code, language, filePath string) (*SecurityScanResult, ScanMode, error)

ScanCodeWithMode scans code and returns the scan mode used.

Description

Same as ScanCode but also returns which scanning method was used. Useful for debugging and metrics collection.

Inputs

  • ctx: Context for cancellation.
  • code: The source code to scan.
  • language: Programming language.
  • filePath: File path for reporting.

Outputs

  • *SecurityScanResult: Scan results.
  • ScanMode: Which scanning method was used.
  • error: Non-nil on context cancellation.

type LeafParallelConfig

type LeafParallelConfig struct {
	// SimulationsPerLeaf is how many simulations to run per leaf in parallel.
	// Default: 4
	SimulationsPerLeaf int

	// AggregationMethod is how to combine multiple simulation results.
	// Options: "mean", "max", "weighted"
	// Default: "mean"
	AggregationMethod string
}

LeafParallelConfig configures leaf parallelization.

func DefaultLeafParallelConfig

func DefaultLeafParallelConfig() LeafParallelConfig

DefaultLeafParallelConfig returns sensible defaults.

type LeafParallelMCTSEngine

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

LeafParallelMCTSEngine uses leaf parallelization instead of root parallelization.

In leaf parallelization, multiple simulations are run in parallel on the same leaf node. This can be more efficient when simulations are expensive but tree traversal is cheap.

Write Serialization: Similar to ParallelMCTSEngine, actions with side effects are serialized. However, leaf parallelization runs multiple simulations on the SAME leaf, so write conflicts are handled at simulation level.

Thread Safety: Safe for concurrent use.

func NewLeafParallelMCTSEngine

func NewLeafParallelMCTSEngine(engine *MCTSEngine, config LeafParallelConfig) *LeafParallelMCTSEngine

NewLeafParallelMCTSEngine creates a leaf-parallel MCTS engine.

func (*LeafParallelMCTSEngine) Run

func (l *LeafParallelMCTSEngine) Run(ctx context.Context, task string, budget *TreeBudget) (*PlanTree, error)

Run executes leaf-parallel MCTS.

func (*LeafParallelMCTSEngine) RunMCTS

func (l *LeafParallelMCTSEngine) RunMCTS(ctx context.Context, task string, budget *TreeBudget) (*PlanTree, error)

RunMCTS implements the MCTSRunner interface.

type LinearPlan

type LinearPlan struct {
	Steps []PlanStep `json:"steps"`
}

LinearPlan represents a CB-41 linear plan.

type LinearPlanner

type LinearPlanner interface {
	Plan(ctx context.Context, task string) (*LinearPlan, error)
}

LinearPlanner is the interface for CB-41 linear planning.

type LintResult

type LintResult struct {
	Valid    bool
	Errors   []string
	Warnings []string
}

LintResult contains linter output.

type LintRunner

type LintRunner interface {
	LintContent(ctx context.Context, content []byte, language string) (*LintResult, error)
}

LintRunner runs linting on code.

Contract:

  • Must respect ctx for cancellation
  • Should complete within reasonable time (< 30s)
  • Return error only for infrastructure failures, not lint findings

type MCTSEngine

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

MCTSEngine implements the full MCTS algorithm for plan tree exploration.

The engine performs the classic MCTS loop:

  1. SELECT: Traverse tree using UCB1/PUCT to find a leaf
  2. EXPAND: Generate child nodes via LLM
  3. SIMULATE: Evaluate the selected child
  4. BACKPROPAGATE: Update scores up the tree

Thread Safety: Safe for concurrent use.

func NewMCTSEngine

func NewMCTSEngine(
	expander NodeExpander,
	simulator *Simulator,
	config MCTSEngineConfig,
	opts ...MCTSEngineOption,
) *MCTSEngine

NewMCTSEngine creates a new MCTS engine.

Inputs:

  • expander: Node expander for generating children.
  • simulator: Simulator for evaluating nodes.
  • config: Engine configuration.
  • opts: Optional configuration functions.

Outputs:

  • *MCTSEngine: Ready to use engine.

func (*MCTSEngine) Run

func (e *MCTSEngine) Run(ctx context.Context, task string, budget *TreeBudget) (*PlanTree, error)

Run executes the MCTS algorithm.

This is the main entry point for MCTS exploration. It:

  1. Creates a plan tree for the task
  2. Runs iterations until budget exhausted or max iterations reached
  3. Extracts and returns the best path

Inputs:

  • ctx: Context for cancellation.
  • task: The task description.
  • budget: Resource budget for exploration.

Outputs:

  • *PlanTree: The explored tree with best path set.
  • error: Non-nil on failure.

func (*MCTSEngine) RunMCTS

func (e *MCTSEngine) RunMCTS(ctx context.Context, task string, budget *TreeBudget) (*PlanTree, error)

RunMCTS implements the MCTSRunner interface.

type MCTSEngineConfig

type MCTSEngineConfig struct {
	// MaxIterations is the maximum number of MCTS iterations.
	// If 0, uses budget constraints only.
	MaxIterations int

	// SimulationTier is the default simulation tier to use.
	SimulationTier SimulationTier

	// UseProgressiveSimulation enables tiered simulation promotion.
	UseProgressiveSimulation bool

	// ExplorationConstant for UCB1/PUCT (default: sqrt(2)).
	ExplorationConstant float64

	// UsePUCT enables PUCT selection instead of UCB1.
	UsePUCT bool

	// UseRAVE enables RAVE (Rapid Action Value Estimation).
	UseRAVE bool

	// RAVEBeta is the RAVE blending parameter (0-1).
	// Higher values favor RAVE estimates over MCTS.
	RAVEBeta float64

	// UseTransposition enables transposition table.
	UseTransposition bool

	// MinVisitsBeforeExpand requires this many visits before expanding.
	// Default: 1 (expand immediately)
	MinVisitsBeforeExpand int

	// AbandonThreshold is the score below which nodes are abandoned.
	// Default: 0.1
	AbandonThreshold float64
}

MCTSEngineConfig configures the MCTS engine.

func DefaultMCTSEngineConfig

func DefaultMCTSEngineConfig() MCTSEngineConfig

DefaultMCTSEngineConfig returns sensible defaults.

type MCTSEngineOption

type MCTSEngineOption func(*MCTSEngine)

MCTSEngineOption configures the MCTS engine.

func WithMCTSLogger

func WithMCTSLogger(logger *slog.Logger) MCTSEngineOption

WithLogger sets the logger.

func WithMCTSTracer

func WithMCTSTracer(tracer *MCTSTracer) MCTSEngineOption

WithTracer sets the tracer for observability.

func WithProgressiveWidening

func WithProgressiveWidening(config ProgressiveWideningConfig) MCTSEngineOption

WithProgressiveWidening sets the progressive widening config.

type MCTSFullConfig

type MCTSFullConfig struct {
	// Budget contains resource limit settings.
	Budget BudgetConfig `json:"budget" yaml:"budget"`

	// Algorithm contains MCTS algorithm settings.
	Algorithm AlgorithmConfig `json:"algorithm" yaml:"algorithm"`

	// Simulation contains simulation settings.
	Simulation SimulationFullConfig `json:"simulation" yaml:"simulation"`

	// CircuitBreaker contains circuit breaker settings.
	CircuitBreaker CircuitBreakerConfig `json:"circuit_breaker" yaml:"circuit_breaker"`

	// Degradation contains degradation settings.
	Degradation DegradationConfig `json:"degradation" yaml:"degradation"`

	// Parallel contains parallel execution settings.
	Parallel ParallelConfig `json:"parallel" yaml:"parallel"`

	// Pruning contains tree pruning settings.
	Pruning PruningConfig `json:"pruning" yaml:"pruning"`

	// Observability contains observability settings.
	Observability ObservabilityConfig `json:"observability" yaml:"observability"`
}

MCTSFullConfig contains all MCTS-related configuration. This is the top-level config struct that can be loaded from files/env.

Thread Safety: Safe to read concurrently. Not safe to modify after creation.

func DefaultMCTSFullConfig

func DefaultMCTSFullConfig() MCTSFullConfig

DefaultMCTSFullConfig returns the default configuration.

Outputs:

  • MCTSFullConfig: Default configuration with sensible values.

func LoadMCTSConfig

func LoadMCTSConfig(configPath string) (MCTSFullConfig, error)

LoadMCTSConfig loads configuration with priority: env > file > defaults.

Inputs:

  • configPath: Path to YAML/JSON config file (optional, can be empty).

Outputs:

  • MCTSFullConfig: Merged configuration.
  • error: Non-nil if file exists but is invalid.

func (MCTSFullConfig) Validate

func (c MCTSFullConfig) Validate() error

Validate checks that the configuration is valid.

Outputs:

  • error: Non-nil if configuration is invalid.

type MCTSRunner

type MCTSRunner interface {
	RunMCTS(ctx context.Context, task string, budget *TreeBudget) (*PlanTree, error)
}

MCTSRunner runs MCTS exploration.

type MCTSTracer

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

MCTSTracer provides OpenTelemetry tracing for MCTS operations.

Thread Safety: Safe for concurrent use.

func NewMCTSTracer

func NewMCTSTracer(logger *slog.Logger, config ObservabilityConfig) *MCTSTracer

NewMCTSTracer creates a new tracer.

Inputs:

  • logger: Logger for structured logging (can be nil for no logging).
  • config: Observability configuration.

Outputs:

  • *MCTSTracer: Tracer instance.

func (*MCTSTracer) EndBackpropagate

func (t *MCTSTracer) EndBackpropagate(span trace.Span, nodesUpdated int)

EndBackpropagate completes the backpropagation span.

Inputs:

  • span: The span to end.
  • nodesUpdated: Number of nodes updated during backpropagation.

func (*MCTSTracer) EndExpand

func (t *MCTSTracer) EndExpand(span trace.Span, children []*PlanNode, tokens int, cost float64, err error)

EndExpand completes the expansion span.

Inputs:

  • span: The span to end.
  • children: The created child nodes.
  • tokens: Tokens used.
  • cost: Cost in USD.
  • err: Error if expansion failed.

func (*MCTSTracer) EndMCTSRun

func (t *MCTSTracer) EndMCTSRun(span trace.Span, tree *PlanTree, budget *TreeBudget, err error)

EndMCTSRun completes the MCTS run span.

Inputs:

  • span: The span to end.
  • tree: The resulting plan tree (can be nil).
  • budget: Budget tracker with usage.
  • err: Error if run failed.

func (*MCTSTracer) EndSimulate

func (t *MCTSTracer) EndSimulate(span trace.Span, result *SimulationResult, err error)

EndSimulate completes the simulation span.

Inputs:

  • span: The span to end.
  • result: Simulation result.
  • err: Error if simulation failed.

func (*MCTSTracer) StartMCTSRun

func (t *MCTSTracer) StartMCTSRun(ctx context.Context, task string, budget *TreeBudget) (context.Context, trace.Span)

StartMCTSRun starts a span for the entire MCTS run.

Inputs:

  • ctx: Parent context.
  • task: Task description.
  • budget: Budget configuration.

Outputs:

  • context.Context: Context with span.
  • trace.Span: The created span (nil if tracing disabled).

func (*MCTSTracer) TraceBackpropagate

func (t *MCTSTracer) TraceBackpropagate(ctx context.Context, node *PlanNode, score float64) (context.Context, trace.Span)

TraceBackpropagate traces the backpropagation phase.

Inputs:

  • ctx: Parent context.
  • node: The starting node for backpropagation.
  • score: The score to propagate.

Outputs:

  • context.Context: Context with span.
  • trace.Span: The created span.

func (*MCTSTracer) TraceBudgetExhaustion

func (t *MCTSTracer) TraceBudgetExhaustion(ctx context.Context, reason string, budget *TreeBudget)

TraceBudgetExhaustion records budget exhaustion.

Inputs:

  • ctx: Context with span.
  • reason: The budget limit that was exceeded.
  • budget: Budget tracker with current usage.

func (*MCTSTracer) TraceCircuitBreakerStateChange

func (t *MCTSTracer) TraceCircuitBreakerStateChange(ctx context.Context, from, to CircuitState)

TraceCircuitBreakerStateChange records circuit breaker state changes.

Inputs:

  • ctx: Context with span.
  • from: Previous circuit state.
  • to: New circuit state.

func (*MCTSTracer) TraceDegradation

func (t *MCTSTracer) TraceDegradation(ctx context.Context, from, to TreeDegradation, reason string)

TraceDegradation records a degradation event.

Inputs:

  • ctx: Context with span.
  • from: Previous degradation level.
  • to: New degradation level.
  • reason: Reason for degradation.

func (*MCTSTracer) TraceExpand

func (t *MCTSTracer) TraceExpand(ctx context.Context, parentNode *PlanNode) (context.Context, trace.Span)

TraceExpand traces the expansion phase.

Inputs:

  • ctx: Parent context.
  • parentNode: The node being expanded.

Outputs:

  • context.Context: Context with span.
  • trace.Span: The created span.

func (*MCTSTracer) TraceIteration

func (t *MCTSTracer) TraceIteration(ctx context.Context, iteration int) (context.Context, trace.Span)

TraceIteration traces a single MCTS iteration.

Inputs:

  • ctx: Parent context.
  • iteration: Iteration number.

Outputs:

  • context.Context: Context with span.
  • trace.Span: The created span.

func (*MCTSTracer) TraceNodeAbandon

func (t *MCTSTracer) TraceNodeAbandon(ctx context.Context, node *PlanNode, reason string)

TraceNodeAbandon records a node abandonment event.

Inputs:

  • ctx: Context with span.
  • node: The abandoned node.
  • reason: Reason for abandonment.

func (*MCTSTracer) TraceSelect

func (t *MCTSTracer) TraceSelect(ctx context.Context, selectedNode *PlanNode) (context.Context, trace.Span)

TraceSelect traces the selection phase.

Inputs:

  • ctx: Parent context.
  • selectedNode: The node selected for expansion.

Outputs:

  • context.Context: Context with span.
  • trace.Span: The created span.

func (*MCTSTracer) TraceSimulate

func (t *MCTSTracer) TraceSimulate(ctx context.Context, node *PlanNode, tier SimulationTier) (context.Context, trace.Span)

TraceSimulate traces the simulation phase.

Inputs:

  • ctx: Parent context.
  • node: The node being simulated.
  • tier: Simulation tier.

Outputs:

  • context.Context: Context with span.
  • trace.Span: The created span.

type MockExpander

type MockExpander struct {
	// ChildrenPerExpansion is how many children to generate.
	ChildrenPerExpansion int

	// Priors to return (if nil, uniform priors are generated).
	Priors []float64

	// Error to return (if set).
	Err error

	// ChildGenerator allows custom child generation.
	// If nil, default children are generated.
	ChildGenerator func(parent *PlanNode, count int) ([]*PlanNode, []float64)
}

MockExpander is a test implementation of NodeExpander.

Thread Safety: Safe for concurrent use.

func NewMockExpander

func NewMockExpander(childrenPerExpansion int) *MockExpander

NewMockExpander creates a mock expander for testing.

func (*MockExpander) Expand

func (m *MockExpander) Expand(ctx context.Context, parent *PlanNode, budget *TreeBudget) ([]*PlanNode, []float64, error)

Expand implements NodeExpander for testing.

type NodeExpander

type NodeExpander interface {
	// Expand generates child nodes for the given parent.
	//
	// Inputs:
	//   - ctx: Context for cancellation and timeout.
	//   - parent: The node to expand.
	//   - budget: Budget to check before expansion.
	//
	// Outputs:
	//   - []*PlanNode: Generated child nodes with descriptions and optional actions.
	//   - []float64: Prior probabilities for each child (for PUCT). May be nil.
	//   - error: Non-nil on failure.
	Expand(ctx context.Context, parent *PlanNode, budget *TreeBudget) ([]*PlanNode, []float64, error)
}

NodeExpander generates child nodes for a given parent node.

In MCTS for code planning, expansion typically involves:

  1. Sending the current state to an LLM
  2. Generating 2-3 alternative approaches
  3. Creating PlanNode instances for each alternative

Thread Safety: Implementations must be safe for concurrent use.

type NodeState

type NodeState string

NodeState represents the lifecycle state of a plan node.

const (
	NodeUnexplored NodeState = "unexplored"
	NodeExploring  NodeState = "exploring"
	NodeCompleted  NodeState = "completed"
	NodeAbandoned  NodeState = "abandoned"
)

func (NodeState) IsTerminal

func (s NodeState) IsTerminal() bool

IsTerminal returns true if this state is terminal (completed or abandoned).

func (NodeState) String

func (s NodeState) String() string

String returns the string representation of the node state.

type NoopActionExecutor

type NoopActionExecutor struct{}

NoopActionExecutor is a no-op executor for testing.

func (*NoopActionExecutor) ExecuteAction

func (n *NoopActionExecutor) ExecuteAction(_ context.Context, _ *PlannedAction) error

ExecuteAction does nothing and returns nil.

type NoopLinearPlanner

type NoopLinearPlanner struct {
	Plan_ *LinearPlan
}

NoopLinearPlanner is a no-op linear planner for testing.

func (*NoopLinearPlanner) Plan

func (n *NoopLinearPlanner) Plan(_ context.Context, task string) (*LinearPlan, error)

Plan returns the configured plan or a default.

type NoopMCTSRunner

type NoopMCTSRunner struct {
	Tree_ *PlanTree
	Err   error
}

NoopMCTSRunner is a no-op MCTS runner for testing.

func (*NoopMCTSRunner) RunMCTS

func (n *NoopMCTSRunner) RunMCTS(_ context.Context, task string, budget *TreeBudget) (*PlanTree, error)

RunMCTS returns the configured tree or creates a default.

type ObservabilityConfig

type ObservabilityConfig struct {
	TracingEnabled bool    `json:"tracing_enabled" yaml:"tracing_enabled"`
	MetricsEnabled bool    `json:"metrics_enabled" yaml:"metrics_enabled"`
	LogLevel       string  `json:"log_level" yaml:"log_level"`
	SampleRate     float64 `json:"sample_rate" yaml:"sample_rate"`
	ServiceName    string  `json:"service_name" yaml:"service_name"`
}

ObservabilityConfig contains observability settings.

type PUCTPolicy

type PUCTPolicy struct {
	// ExplorationConstant (C_puct) controls exploration.
	// AlphaGo uses values around 1.0-2.0.
	ExplorationConstant float64
	// contains filtered or unexported fields
}

PUCTPolicy implements the Predictor + Upper Confidence Tree policy.

PUCT is the selection policy used by AlphaGo/AlphaZero. It incorporates a prior probability for each action (from a policy network or LLM):

PUCT(node) = avgScore + C * prior * sqrt(parentVisits) / (1 + nodeVisits)

The prior allows the policy to favor actions that are estimated to be good even before they've been explored.

Thread Safety: Safe for concurrent use.

func NewPUCTPolicy

func NewPUCTPolicy(explorationConstant float64) *PUCTPolicy

NewPUCTPolicy creates a PUCT selection policy.

Inputs:

  • explorationConstant: The C_puct parameter (typically 1.0-2.0).

Outputs:

  • *PUCTPolicy: Ready to use selection policy.

func (*PUCTPolicy) GetPrior

func (p *PUCTPolicy) GetPrior(nodeID string, numSiblings int) float64

GetPrior returns the prior for a node (default: uniform).

func (*PUCTPolicy) Select

func (p *PUCTPolicy) Select(parent *PlanNode) *PlanNode

Select implements SelectionPolicy using PUCT.

func (*PUCTPolicy) SetPrior

func (p *PUCTPolicy) SetPrior(nodeID string, prior float64)

SetPrior sets the prior probability for a node.

Inputs:

  • nodeID: The node's ID.
  • prior: Prior probability [0, 1]. Higher means more likely to be selected.

func (*PUCTPolicy) SetPriors

func (p *PUCTPolicy) SetPriors(priors map[string]float64)

SetPriors sets priors for multiple nodes at once.

Inputs:

  • priors: Map of nodeID → prior probability.

type ParallelConfig

type ParallelConfig struct {
	Enabled        bool `json:"enabled" yaml:"enabled"`
	MaxConcurrency int  `json:"max_concurrency" yaml:"max_concurrency"`
	BatchSize      int  `json:"batch_size" yaml:"batch_size"`
}

ParallelConfig contains parallel execution settings.

type ParallelMCTSConfig

type ParallelMCTSConfig struct {
	// NumWorkers is the number of concurrent workers.
	// Default: 4
	NumWorkers int

	// VirtualLossValue is the penalty applied during selection.
	// Higher values = more exploration across workers.
	// Default: 1.0
	VirtualLossValue float64

	// BatchSize is how many iterations each worker performs before syncing.
	// Default: 1
	BatchSize int

	// ChannelBufferSize is the size of the work channel buffer.
	// Default: NumWorkers * 2
	ChannelBufferSize int
}

ParallelMCTSConfig configures parallel MCTS execution.

func DefaultParallelMCTSConfig

func DefaultParallelMCTSConfig() ParallelMCTSConfig

DefaultParallelMCTSConfig returns sensible defaults.

type ParallelMCTSEngine

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

ParallelMCTSEngine runs multiple MCTS iterations concurrently using virtual loss.

Virtual Loss: When a worker selects a path, it applies a "virtual loss" to discourage other workers from selecting the same path. This ensures better exploration across workers. After simulation, the virtual loss is removed and the real score is backpropagated.

Write Serialization: Actions with side effects (edit, create, delete) modify the filesystem. Running these in parallel causes data corruption where one worker's writes overwrite another's, leading to incorrect test results. Write operations are serialized using a mutex while read-only operations (run_test) can parallelize freely.

Thread Safety: Safe for concurrent use.

func NewParallelMCTSEngine

func NewParallelMCTSEngine(
	engine *MCTSEngine,
	config ParallelMCTSConfig,
) *ParallelMCTSEngine

NewParallelMCTSEngine creates a parallel MCTS engine.

Inputs:

  • engine: The underlying MCTS engine.
  • config: Parallel configuration.

Outputs:

  • *ParallelMCTSEngine: Ready to use parallel engine.

func (*ParallelMCTSEngine) Run

func (p *ParallelMCTSEngine) Run(ctx context.Context, task string, budget *TreeBudget) (*PlanTree, error)

Run executes parallel MCTS.

Inputs:

  • ctx: Context for cancellation.
  • task: The task description.
  • budget: Resource budget for exploration.

Outputs:

  • *PlanTree: The explored tree with best path set.
  • error: Non-nil on failure.

func (*ParallelMCTSEngine) RunMCTS

func (p *ParallelMCTSEngine) RunMCTS(ctx context.Context, task string, budget *TreeBudget) (*PlanTree, error)

RunMCTS implements the MCTSRunner interface.

func (*ParallelMCTSEngine) WithParallelLogger

func (p *ParallelMCTSEngine) WithParallelLogger(logger *slog.Logger) *ParallelMCTSEngine

WithParallelLogger sets the logger.

type ParallelMCTSStats

type ParallelMCTSStats struct {
	TotalIterations   int64
	IterationsPerSec  float64
	AverageWorkerTime time.Duration
	WorkerStats       []WorkerStats
}

ParallelMCTSStats contains statistics about parallel execution.

type PatchValidator

type PatchValidator interface {
	CheckSyntax(code, language string) bool
}

PatchValidator validates code syntax.

Contract:

  • CheckSyntax must be fast (< 100ms) and not make network calls
  • Return true if the code is syntactically valid for the language
  • Return false for syntax errors; do not panic

type PlanNode

type PlanNode struct {
	// Immutable after creation
	ID          string `json:"id"`
	Description string `json:"description"`
	CreatedAt   int64  `json:"created_at"` // Unix milliseconds UTC
	Depth       int    `json:"depth"`
	ContentHash string `json:"content_hash"` // SHA256 of description+action
	// contains filtered or unexported fields
}

PlanNode represents a node in the MCTS plan tree.

Thread Safety: Safe for concurrent use. Uses atomic operations for visit/score updates and mutex for structural modifications (children).

func ExpandAndIntegrate

func ExpandAndIntegrate(
	ctx context.Context,
	tree *PlanTree,
	node *PlanNode,
	expander NodeExpander,
	budget *TreeBudget,
	pwConfig ProgressiveWideningConfig,
	puctPolicy *PUCTPolicy,
) ([]*PlanNode, error)

ExpandAndIntegrate expands a node and integrates children into the tree.

This is a convenience function that:

  1. Checks if expansion is allowed (progressive widening, budget)
  2. Calls the expander
  3. Adds children to the parent
  4. Updates tree statistics
  5. Records budget usage

Inputs:

  • ctx: Context for cancellation.
  • tree: The plan tree.
  • node: The node to expand.
  • expander: The node expander to use.
  • budget: The budget to check and update.
  • pwConfig: Progressive widening configuration.
  • puctPolicy: Optional PUCT policy to set priors (can be nil).

Outputs:

  • []*PlanNode: The generated children (already added to tree).
  • error: Non-nil on failure.

func NewPlanNode

func NewPlanNode(id, description string, opts ...PlanNodeOption) *PlanNode

NewPlanNode creates a new plan node with the given ID and description.

Inputs:

  • id: Unique identifier for this node (e.g., "1", "1.1", "1.1.2")
  • description: Human-readable description of this plan step
  • opts: Optional configuration functions

Outputs:

  • *PlanNode: The created node, never nil

Thread Safety: The returned node is safe for concurrent use.

func (*PlanNode) Action

func (n *PlanNode) Action() *PlannedAction

Action returns the planned action (may be nil).

func (*PlanNode) AddChild

func (n *PlanNode) AddChild(child *PlanNode)

AddChild adds a child node and sets its parent pointer.

func (*PlanNode) AddScore

func (n *PlanNode) AddScore(score float64)

AddScore adds to the total score atomically.

func (*PlanNode) AvgScore

func (n *PlanNode) AvgScore() float64

AvgScore returns the average score (total/visits). Returns 0 if no visits.

func (*PlanNode) ChildCount

func (n *PlanNode) ChildCount() int

ChildCount returns the number of children.

func (*PlanNode) Children

func (n *PlanNode) Children() []*PlanNode

Children returns a copy of the children slice.

func (*PlanNode) IncrementVisits

func (n *PlanNode) IncrementVisits() int64

IncrementVisits atomically increments the visit count and returns the new value.

func (*PlanNode) IsLeaf

func (n *PlanNode) IsLeaf() bool

IsLeaf returns true if this node has no children.

func (*PlanNode) IsRoot

func (n *PlanNode) IsRoot() bool

IsRoot returns true if this node has no parent.

func (*PlanNode) IsSimulated

func (n *PlanNode) IsSimulated() bool

IsSimulated returns whether this node has been simulated.

func (*PlanNode) MarshalJSON

func (n *PlanNode) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler with custom handling.

func (*PlanNode) NeedsExpansion

func (n *PlanNode) NeedsExpansion() bool

NeedsExpansion returns true if this node should be expanded. A node needs expansion if it's unexplored and has no children.

func (*PlanNode) Parent

func (n *PlanNode) Parent() *PlanNode

Parent returns the parent node (may be nil for root).

func (*PlanNode) PathFromRoot

func (n *PlanNode) PathFromRoot() []*PlanNode

PathFromRoot returns the path from root to this node.

func (*PlanNode) PathIDs

func (n *PlanNode) PathIDs() []string

PathIDs returns the IDs of nodes from root to this node.

func (*PlanNode) RemoveChild

func (n *PlanNode) RemoveChild(childID string) bool

RemoveChild removes a child node by ID.

func (*PlanNode) SetAction

func (n *PlanNode) SetAction(action *PlannedAction)

SetAction sets the planned action.

func (*PlanNode) SetSimulationResult

func (n *PlanNode) SetSimulationResult(result *SimulationResult)

SetSimulationResult sets the simulation result.

func (*PlanNode) SetState

func (n *PlanNode) SetState(state NodeState)

SetState updates the node state.

func (*PlanNode) SimulationResult

func (n *PlanNode) SimulationResult() *SimulationResult

SimulationResult returns the simulation result (may be nil).

func (*PlanNode) State

func (n *PlanNode) State() NodeState

State returns the current node state.

func (*PlanNode) String

func (n *PlanNode) String() string

String returns a human-readable representation of the node.

func (*PlanNode) TotalScore

func (n *PlanNode) TotalScore() float64

TotalScore returns the total score (requires lock).

func (*PlanNode) Visits

func (n *PlanNode) Visits() int64

Visits returns the visit count atomically.

type PlanNodeOption

type PlanNodeOption func(*PlanNode)

PlanNodeOption configures a PlanNode during creation.

func WithAction

func WithAction(action *PlannedAction) PlanNodeOption

WithAction sets the planned action for a node.

func WithParent

func WithParent(parent *PlanNode) PlanNodeOption

WithParent sets the parent node.

type PlanPhaseConfig

type PlanPhaseConfig struct {
	// Tree mode triggers
	ComplexityThreshold float64 // Complexity score to trigger tree mode (default: 0.7)
	AlwaysUseTreeMode   bool    // Force tree mode for all planning
	EnableTreeMode      bool    // Allow tree mode (default: true)

	// Fallback behavior
	FallbackOnTreeFailure bool // Use linear plan if tree fails (default: true)
	MaxTreeRetries        int  // Retries before fallback (default: 1)
}

PlanPhaseConfig extends plan phase configuration for tree mode.

This configuration determines when the agent should use tree-based MCTS planning versus simple linear planning.

func DefaultPlanPhaseConfig

func DefaultPlanPhaseConfig() PlanPhaseConfig

DefaultPlanPhaseConfig returns sensible defaults.

Outputs:

  • PlanPhaseConfig: Configuration with default values.

type PlanResult

type PlanResult struct {
	Mode       PlanningMode `json:"mode"`
	Tree       *PlanTree    `json:"tree"`
	DAG        *dag.DAG     `json:"dag,omitempty"`
	LinearPlan *LinearPlan  `json:"linear_plan,omitempty"`
	BestScore  float64      `json:"best_score,omitempty"`
	Budget     *TreeBudget  `json:"budget_usage,omitempty"`
}

PlanResult contains the output of planning.

type PlanStep

type PlanStep struct {
	Description string         `json:"description"`
	Action      *PlannedAction `json:"action,omitempty"`
}

PlanStep represents a single step in a linear plan.

type PlanStepNode

type PlanStepNode struct {
	dag.BaseNode
	// contains filtered or unexported fields
}

PlanStepNode is a DAG node that executes a plan step.

Thread Safety: Safe for concurrent use.

func (*PlanStepNode) Execute

func (n *PlanStepNode) Execute(ctx context.Context, inputs map[string]any) (any, error)

Execute implements dag.Node.

Inputs:

  • ctx: Context for cancellation.
  • inputs: Map of dependency node outputs.

Outputs:

  • any: Execution result map.
  • error: Non-nil on failure.

func (*PlanStepNode) PlanNode

func (n *PlanStepNode) PlanNode() *PlanNode

PlanNode returns the underlying plan node.

type PlanToDAGConverter

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

PlanToDAGConverter converts plan trees to executable DAGs.

Thread Safety: Safe for concurrent use.

func NewPlanToDAGConverter

func NewPlanToDAGConverter(executor ActionExecutor, projectRoot string) *PlanToDAGConverter

NewPlanToDAGConverter creates a converter.

Inputs:

  • executor: The action executor for plan step execution.
  • projectRoot: Root directory for path validation (can be empty for no validation).

Outputs:

  • *PlanToDAGConverter: The converter instance.

func (*PlanToDAGConverter) ToDAG

func (c *PlanToDAGConverter) ToDAG(tree *PlanTree, taskID string) (*dag.DAG, error)

ToDAG converts a plan tree's best path to an executable DAG.

Inputs:

  • tree: The plan tree with BestPath populated.
  • taskID: Unique identifier for this execution.

Outputs:

  • *dag.DAG: Executable DAG.
  • error: Non-nil if conversion fails.

type PlanTree

type PlanTree struct {
	// Task description (immutable after creation)
	Task      string `json:"task"`
	CreatedAt int64  `json:"created_at"` // Unix milliseconds UTC
	// contains filtered or unexported fields
}

PlanTree represents the root structure of an MCTS plan tree.

Thread Safety: Safe for concurrent use.

func NewPlanTree

func NewPlanTree(task string, budget *TreeBudget) *PlanTree

NewPlanTree creates a new plan tree for the given task.

Inputs:

  • task: The task description
  • budget: Resource budget for tree exploration

Outputs:

  • *PlanTree: The created tree with a root node

Thread Safety: The returned tree is safe for concurrent use.

func (*PlanTree) BestPath

func (t *PlanTree) BestPath() []*PlanNode

BestPath returns a copy of the best path.

func (*PlanTree) BestScore

func (t *PlanTree) BestScore() float64

BestScore returns the average score of the best leaf node. Returns 0 if no best path exists.

func (*PlanTree) Budget

func (t *PlanTree) Budget() *TreeBudget

Budget returns the tree budget.

func (*PlanTree) CountByState

func (t *PlanTree) CountByState() map[NodeState]int

CountByState returns a map of node counts by state.

func (*PlanTree) ExtractBestPath

func (t *PlanTree) ExtractBestPath() []*PlanNode

ExtractBestPath finds the best path from root to leaf. Uses highest average score at each level.

func (*PlanTree) FindNode

func (t *PlanTree) FindNode(id string) *PlanNode

FindNode finds a node by ID using BFS.

func (*PlanTree) Format

func (t *PlanTree) Format() string

Format returns a formatted string representation of the tree.

func (*PlanTree) IncrementNodeCount

func (t *PlanTree) IncrementNodeCount() int64

IncrementNodeCount atomically increments the node count.

func (*PlanTree) MarshalJSON

func (t *PlanTree) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*PlanTree) MaxDepth

func (t *PlanTree) MaxDepth() int

MaxDepth returns the maximum depth of the tree.

func (*PlanTree) Prune

func (t *PlanTree) Prune(keepTopN int, minVisits int64) int

Prune removes low-scoring branches to free memory. Keeps the top N children by average score at each level.

Inputs:

  • keepTopN: Number of top-scoring children to keep per node
  • minVisits: Minimum visits required to be considered for pruning

Outputs:

  • int: Number of nodes pruned

Thread Safety: Safe for concurrent use, but may conflict with ongoing MCTS.

func (*PlanTree) Root

func (t *PlanTree) Root() *PlanNode

Root returns the root node of the tree.

func (*PlanTree) SetBestPath

func (t *PlanTree) SetBestPath(path []*PlanNode)

SetBestPath updates the best path.

func (*PlanTree) TotalNodes

func (t *PlanTree) TotalNodes() int64

TotalNodes returns the total number of nodes in the tree.

type PlanTreeDAGNode

type PlanTreeDAGNode struct {
	dag.BaseNode
	// contains filtered or unexported fields
}

PlanTreeDAGNode wraps MCTS exploration as a DAG node. This allows tree planning to be part of a larger DAG workflow.

Thread Safety: Safe for concurrent use.

func NewPlanTreeDAGNode

func NewPlanTreeDAGNode(
	id string,
	task string,
	runner MCTSRunner,
	budget *TreeBudget,
	converter *PlanToDAGConverter,
) *PlanTreeDAGNode

NewPlanTreeDAGNode creates a DAG node that runs MCTS planning.

Inputs:

  • id: Unique node identifier.
  • task: The task description for MCTS.
  • runner: The MCTS runner.
  • budget: Budget for MCTS exploration.
  • converter: Converter to create executable DAG from result.

Outputs:

  • *PlanTreeDAGNode: The DAG node.

func (*PlanTreeDAGNode) Execute

func (n *PlanTreeDAGNode) Execute(ctx context.Context, inputs map[string]any) (any, error)

Execute runs MCTS and returns the resulting plan.

Inputs:

  • ctx: Context for cancellation.
  • inputs: Map of dependency node outputs.

Outputs:

  • any: PlanTreeResult containing the tree and DAG.
  • error: Non-nil on failure.

type PlanTreeResult

type PlanTreeResult struct {
	Tree       *PlanTree   `json:"tree"`
	DAG        *dag.DAG    `json:"dag"`
	BestScore  float64     `json:"best_score"`
	StepsCount int         `json:"steps_count"`
	Budget     *TreeBudget `json:"budget_usage"`
}

PlanTreeResult contains the output of MCTS planning.

type PlannedAction

type PlannedAction struct {
	Type        ActionType `json:"type"`
	FilePath    string     `json:"file_path,omitempty"`
	Description string     `json:"description"`
	CodeDiff    string     `json:"code_diff,omitempty"`
	Language    string     `json:"language,omitempty"`
	// contains filtered or unexported fields
}

PlannedAction represents a validated action from the LLM.

Thread Safety: Designed for validate-once-then-use pattern. After Validate() returns successfully, the action is immutable and safe for concurrent reads. Do not call Validate() concurrently or modify fields after validation. Clone() creates an unvalidated copy that must be validated separately before use.

func (*PlannedAction) AbsolutePath

func (a *PlannedAction) AbsolutePath() string

AbsolutePath returns the absolute file path within the project. Panics if not validated. Returns empty string if no file path.

func (*PlannedAction) Clone

func (a *PlannedAction) Clone() *PlannedAction

Clone creates a deep copy of the action (without validation state).

func (*PlannedAction) HasSideEffects

func (a *PlannedAction) HasSideEffects() bool

HasSideEffects returns true if this action modifies the filesystem.

Description:

Actions with side effects (edit, create, delete) modify files on disk.
These must be serialized in parallel MCTS to prevent corruption.
Read-only actions (run_test) can safely run in parallel.

Outputs:

bool - True if action writes to filesystem.

Thread Safety: Safe for concurrent use.

func (*PlannedAction) IsReadOnly

func (a *PlannedAction) IsReadOnly() bool

IsReadOnly returns true if this action only reads without modifying state.

Thread Safety: Safe for concurrent use.

func (*PlannedAction) IsValidated

func (a *PlannedAction) IsValidated() bool

IsValidated returns whether this action has been validated.

func (*PlannedAction) MustValidate

func (a *PlannedAction) MustValidate()

MustValidate panics if the action hasn't been validated. Use this in code paths that require validation.

func (*PlannedAction) ProjectRoot

func (a *PlannedAction) ProjectRoot() string

ProjectRoot returns the project root this action was validated against. Returns empty string if not validated.

func (*PlannedAction) Validate

func (a *PlannedAction) Validate(projectRoot string, config ActionValidationConfig) error

Validate checks the PlannedAction for safety and correctness.

Inputs:

  • projectRoot: Absolute path to project root. All file paths must be within this.
  • config: Validation configuration with limits.

Outputs:

  • error: Non-nil if validation fails. Contains specific error type.

Thread Safety: Safe for concurrent use (read-only on receiver until validated flag set).

type PlanningMode

type PlanningMode int

PlanningMode defines how planning is performed.

const (
	// PlanningModeLinear uses CB-41 linear planning.
	PlanningModeLinear PlanningMode = iota

	// PlanningModeTree uses CB-28 MCTS planning.
	PlanningModeTree

	// PlanningModeHybrid tries tree first, falls back to linear.
	PlanningModeHybrid
)

func (PlanningMode) String

func (m PlanningMode) String() string

String returns a human-readable planning mode name.

type PlanningOrchestrator

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

PlanningOrchestrator coordinates between CB-41 linear and CB-28 tree planning.

Thread Safety: Safe for concurrent use.

func NewPlanningOrchestrator

func NewPlanningOrchestrator(
	linear LinearPlanner,
	tree MCTSRunner,
	converter *PlanToDAGConverter,
	config PlanPhaseConfig,
	degradation *DegradationManager,
) *PlanningOrchestrator

NewPlanningOrchestrator creates an orchestrator.

Inputs:

  • linear: CB-41 linear planner (can be nil if only tree mode is used).
  • tree: MCTS runner for tree planning.
  • converter: DAG converter.
  • config: Plan phase configuration.
  • degradation: Degradation manager (can be nil for no degradation handling).

Outputs:

  • *PlanningOrchestrator: The orchestrator.

func (*PlanningOrchestrator) Plan

func (o *PlanningOrchestrator) Plan(ctx context.Context, task string, metrics *SessionMetrics) (*PlanResult, error)

Plan decides which planning mode to use and executes it.

Inputs:

  • ctx: Context for cancellation.
  • task: The task description.
  • metrics: Optional session metrics for complexity estimation (can be nil).

Outputs:

  • *PlanResult: The planning result.
  • error: Non-nil on failure.

func (*PlanningOrchestrator) PlanWithMode

func (o *PlanningOrchestrator) PlanWithMode(ctx context.Context, task string, mode PlanningMode) (*PlanResult, error)

PlanWithMode executes planning using a specific mode.

Inputs:

  • ctx: Context for cancellation.
  • task: The task description.
  • mode: The planning mode to use.

Outputs:

  • *PlanResult: The planning result.
  • error: Non-nil on failure.

type ProgressiveWideningConfig

type ProgressiveWideningConfig struct {
	// Enabled controls whether progressive widening is active.
	Enabled bool

	// Alpha is the exponent for the widening formula (typically 0.5).
	// Higher values allow faster branching growth.
	Alpha float64

	// K is the scaling constant (typically 1.0).
	// Higher values allow more initial children.
	K float64

	// MinChildren is the minimum children allowed regardless of formula.
	// Default: 1
	MinChildren int

	// MaxChildren is the hard cap on children regardless of formula.
	// Default: 10
	MaxChildren int
}

ProgressiveWideningConfig configures progressive widening behavior.

Progressive widening limits the branching factor but allows it to grow with the number of visits to a node:

maxChildren = k * visits^alpha

This prevents explosive branching early while allowing more exploration of promising paths.

func DefaultProgressiveWideningConfig

func DefaultProgressiveWideningConfig() ProgressiveWideningConfig

DefaultProgressiveWideningConfig returns sensible defaults.

type PruningConfig

type PruningConfig struct {
	PruneInterval   int           `json:"prune_interval" yaml:"prune_interval"`
	MinVisitsToKeep int           `json:"min_visits_to_keep" yaml:"min_visits_to_keep"`
	MaxAbandonedAge time.Duration `json:"max_abandoned_age" yaml:"max_abandoned_age"`
	KeepBestN       int           `json:"keep_best_n" yaml:"keep_best_n"`
	ScoreThreshold  float64       `json:"score_threshold" yaml:"score_threshold"`
	VisitsThreshold int64         `json:"visits_threshold" yaml:"visits_threshold"`
}

PruningConfig contains tree pruning settings.

func DefaultPruningConfig

func DefaultPruningConfig() PruningConfig

DefaultPruningConfig returns the default pruning configuration.

type RAVETracker

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

RAVETracker tracks Rapid Action Value Estimation scores.

RAVE shares value estimates between all nodes using the same action type. This helps bootstrap value estimates for unexplored nodes.

Thread Safety: Safe for concurrent use.

func NewRAVETracker

func NewRAVETracker() *RAVETracker

NewRAVETracker creates a new RAVE tracker.

func (*RAVETracker) Count

func (r *RAVETracker) Count(action ActionType) int

Count returns the number of observations for an action type.

func (*RAVETracker) GetScore

func (r *RAVETracker) GetScore(action ActionType) float64

GetScore returns the average RAVE score for an action type. Returns -1 if no observations exist.

func (*RAVETracker) Update

func (r *RAVETracker) Update(action ActionType, score float64)

Update adds a score observation for an action type.

type RetryPolicy

type RetryPolicy struct {
	MaxRetries int
	BackoffMs  int
}

RetryPolicy defines retry behavior for plan steps.

func DefaultPlanStepRetryPolicy

func DefaultPlanStepRetryPolicy() RetryPolicy

DefaultPlanStepRetryPolicy returns the default retry policy.

type ScanMode

type ScanMode string

ScanMode indicates which scanning method was used.

const (
	ScanModeAST      ScanMode = "ast"
	ScanModeRegex    ScanMode = "regex"
	ScanModeSkipped  ScanMode = "skipped"
	ScanModeFallback ScanMode = "fallback"
)

type SecurityIssue

type SecurityIssue struct {
	Severity string `json:"severity"`
	Message  string `json:"message"`
	Pattern  string `json:"pattern,omitempty"`
}

SecurityIssue represents a security finding.

type SecurityPattern

type SecurityPattern struct {
	Name        string
	Pattern     *regexp.Regexp
	Severity    string // critical, high, medium, low
	Description string
	Languages   []string // Empty = all languages
}

SecurityPattern defines a security anti-pattern to detect.

type SecurityScanResult

type SecurityScanResult struct {
	Score  float64
	Issues []SecurityIssue
}

SecurityScanResult contains security scan output.

type SecurityScanner

type SecurityScanner interface {
	ScanCode(ctx context.Context, code string) (*SecurityScanResult, error)
}

SecurityScanner scans code for vulnerabilities.

Contract:

  • Must respect ctx for cancellation
  • Return Score in range [0, 1] where 1 = no issues
  • Return error only for infrastructure failures

type SelectionPolicy

type SelectionPolicy interface {
	// Select returns the best child to explore based on the policy.
	// Returns nil if node has no children or all children are abandoned.
	//
	// Inputs:
	//   - parent: The parent node whose children to select from.
	//
	// Outputs:
	//   - *PlanNode: The selected child, or nil if none available.
	Select(parent *PlanNode) *PlanNode
}

SelectionPolicy determines how nodes are selected during MCTS traversal.

Thread Safety: Implementations must be safe for concurrent use.

func DefaultSelectionPolicy

func DefaultSelectionPolicy() SelectionPolicy

DefaultSelectionPolicy returns a standard UCB1 policy with sqrt(2) constant.

type SessionMetrics

type SessionMetrics struct {
	// PreviousPlanFailed indicates the last plan attempt failed.
	PreviousPlanFailed bool

	// EstimatedBlastRadius is the number of files/symbols affected.
	EstimatedBlastRadius int

	// PreviousIterations is how many planning iterations were needed.
	PreviousIterations int
}

SessionMetrics contains metrics from a previous session that may influence tree mode decision.

type SignalWeights

type SignalWeights struct {
	Syntax      float64
	Complexity  float64
	Lint        float64
	BlastRadius float64
	Tests       float64
	Security    float64
}

SignalWeights defines weights for each signal in score calculation.

type SimulationFullConfig

type SimulationFullConfig struct {
	QuickScoreThreshold    float64       `json:"quick_score_threshold" yaml:"quick_score_threshold"`
	StandardScoreThreshold float64       `json:"standard_score_threshold" yaml:"standard_score_threshold"`
	QuickTimeout           time.Duration `json:"quick_timeout" yaml:"quick_timeout"`
	StandardTimeout        time.Duration `json:"standard_timeout" yaml:"standard_timeout"`
	FullTimeout            time.Duration `json:"full_timeout" yaml:"full_timeout"`
	EnableSecurityScan     bool          `json:"enable_security_scan" yaml:"enable_security_scan"`
}

SimulationFullConfig contains simulation settings.

func (SimulationFullConfig) ToSimulatorConfig

func (c SimulationFullConfig) ToSimulatorConfig() SimulatorConfig

ToSimulatorConfig converts SimulationFullConfig to SimulatorConfig.

Outputs:

  • SimulatorConfig: Simulator configuration.

type SimulationResult

type SimulationResult struct {
	Score         float64            `json:"score"`
	Signals       map[string]float64 `json:"signals"`
	Errors        []string           `json:"errors,omitempty"`
	Warnings      []string           `json:"warnings,omitempty"`
	Duration      time.Duration      `json:"duration"`
	Tier          string             `json:"tier"`            // quick, standard, full
	PromoteToNext bool               `json:"promote_to_next"` // Should run next tier?
}

SimulationResult holds the outcome of simulating a node.

type SimulationTier

type SimulationTier int

SimulationTier defines the depth of simulation.

const (
	// SimTierQuick runs only fast checks (syntax, complexity).
	// Use for initial exploration. ~5ms.
	SimTierQuick SimulationTier = iota

	// SimTierStandard adds linter checks.
	// Use for promising nodes. ~100ms.
	SimTierStandard

	// SimTierFull adds blast radius and test execution.
	// Use only for best path candidates. ~500ms+.
	SimTierFull
)

func (SimulationTier) String

func (t SimulationTier) String() string

String returns a human-readable tier name.

type Simulator

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

Simulator provides tiered simulation for plan nodes.

Thread Safety: Safe for concurrent use.

func NewSimulator

func NewSimulator(config SimulatorConfig, opts ...SimulatorOption) *Simulator

NewSimulator creates a simulator with the given providers.

Inputs:

  • config: Simulator configuration.
  • opts: Optional configuration via SimulatorOption functions.

Outputs:

  • *Simulator: Ready to use simulator.

func (*Simulator) Config

func (s *Simulator) Config() SimulatorConfig

Config returns the simulator configuration.

func (*Simulator) Simulate

func (s *Simulator) Simulate(ctx context.Context, node *PlanNode, tier SimulationTier) (*SimulationResult, error)

Simulate runs simulation at the specified tier.

Inputs:

  • ctx: Context for cancellation and timeout.
  • node: The plan node to simulate.
  • tier: The simulation tier to run.

Outputs:

  • *SimulationResult: Simulation results with score.
  • error: Non-nil on context cancellation only.

func (*Simulator) SimulateProgressive

func (s *Simulator) SimulateProgressive(ctx context.Context, node *PlanNode) (*SimulationResult, error)

SimulateProgressive runs simulation progressively through tiers. Stops early if score is too low to warrant further analysis.

Inputs:

  • ctx: Context for cancellation.
  • node: The plan node to simulate.

Outputs:

  • *SimulationResult: Final simulation results.
  • error: Non-nil on context cancellation.

type SimulatorConfig

type SimulatorConfig struct {
	// Score thresholds for tier promotion
	QuickScoreThreshold    float64 // Score needed to run standard tier (default: 0.5)
	StandardScoreThreshold float64 // Score needed to run full tier (default: 0.7)

	// Timeouts per tier
	QuickTimeout    time.Duration
	StandardTimeout time.Duration
	FullTimeout     time.Duration

	// Signal weights by tier
	QuickWeights    SignalWeights
	StandardWeights SignalWeights
	FullWeights     SignalWeights
}

SimulatorConfig configures the simulator behavior.

func DefaultSimulatorConfig

func DefaultSimulatorConfig() SimulatorConfig

DefaultSimulatorConfig returns sensible defaults.

type SimulatorOption

type SimulatorOption func(*Simulator)

SimulatorOption configures the simulator.

func WithBlastRadius

func WithBlastRadius(b BlastRadiusAnalyzer) SimulatorOption

WithBlastRadius sets the blast radius analyzer.

func WithLinter

func WithLinter(l LintRunner) SimulatorOption

WithLinter sets the lint runner.

func WithSecurityScanner

func WithSecurityScanner(ss SecurityScanner) SimulatorOption

WithSecurityScanner sets the security scanner.

func WithTestRunner

func WithTestRunner(t TestRunner) SimulatorOption

WithTestRunner sets the test runner.

func WithValidator

func WithValidator(v PatchValidator) SimulatorOption

WithValidator sets the patch validator.

type TestResult

type TestResult struct {
	Passed   bool          // True if test passed
	Output   string        // Test output (stdout/stderr)
	Duration time.Duration // How long the test took
}

TestResult contains test execution output.

type TestRunner

type TestRunner interface {
	RunTest(ctx context.Context, testFile, testName string) (*TestResult, error)
}

TestRunner executes tests.

Contract:

  • Must respect ctx for cancellation and timeout
  • Return TestResult.Passed = true only if test passes
  • Return error only for infrastructure failures (test failure is not an error)

type TranspositionTable

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

TranspositionTable stores nodes by their state hash to detect transpositions.

A transposition occurs when different move sequences lead to the same state. By detecting these, we can reuse evaluations and avoid redundant work.

Thread Safety: Safe for concurrent use.

func NewTranspositionTable

func NewTranspositionTable() *TranspositionTable

NewTranspositionTable creates a new transposition table.

func (*TranspositionTable) Clear

func (t *TranspositionTable) Clear()

Clear removes all entries from the table.

func (*TranspositionTable) Lookup

func (t *TranspositionTable) Lookup(hash string) *PlanNode

Lookup retrieves a node by its content hash. Returns nil if not found.

func (*TranspositionTable) Size

func (t *TranspositionTable) Size() int

Size returns the number of entries in the table.

func (*TranspositionTable) Store

func (t *TranspositionTable) Store(hash string, node *PlanNode)

Store adds a node to the transposition table.

type TreeBudget

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

TreeBudget tracks resource consumption during MCTS exploration.

Thread Safety: Safe for concurrent use.

func NewTreeBudget

func NewTreeBudget(config TreeBudgetConfig) *TreeBudget

NewTreeBudget creates a new budget tracker.

Inputs:

  • config: Budget configuration

Outputs:

  • *TreeBudget: Budget tracker, ready to use

Thread Safety: The returned budget is safe for concurrent use.

func (*TreeBudget) CanExpand

func (b *TreeBudget) CanExpand(currentChildCount int) bool

CanExpand checks if we can expand (create children) at the current state.

Inputs:

  • currentChildCount: Number of children the node already has

Outputs:

  • bool: True if expansion is allowed

func (*TreeBudget) CheckDepth

func (b *TreeBudget) CheckDepth(depth int) error

CheckDepth checks if the given depth is within limits.

Inputs:

  • depth: The depth to check

Outputs:

  • error: Non-nil if depth exceeds MaxDepth

func (*TreeBudget) Config

func (b *TreeBudget) Config() TreeBudgetConfig

Config returns the budget configuration.

func (*TreeBudget) CostUSD

func (b *TreeBudget) CostUSD() float64

CostUSD returns the total cost in USD.

func (*TreeBudget) Elapsed

func (b *TreeBudget) Elapsed() time.Duration

Elapsed returns time elapsed since budget was created.

func (*TreeBudget) Exhausted

func (b *TreeBudget) Exhausted() bool

Exhausted returns whether the budget has been exhausted.

func (*TreeBudget) ExhaustedBy

func (b *TreeBudget) ExhaustedBy() string

ExhaustedBy returns which limit caused exhaustion (empty if not exhausted).

func (*TreeBudget) LLMCalls

func (b *TreeBudget) LLMCalls() int64

LLMCalls returns the number of LLM calls made.

func (*TreeBudget) NodesExplored

func (b *TreeBudget) NodesExplored() int64

NodesExplored returns the number of nodes explored.

func (*TreeBudget) RecordLLMCall

func (b *TreeBudget) RecordLLMCall(tokens int64, costUSD float64) error

RecordLLMCall records an LLM call with token usage and cost.

Inputs:

  • tokens: Number of tokens used
  • costUSD: Cost in USD for this call

Outputs:

  • error: Non-nil if budget is exhausted by this call

func (*TreeBudget) RecordNodeExplored

func (b *TreeBudget) RecordNodeExplored() int64

RecordNodeExplored records a node exploration.

func (*TreeBudget) Remaining

func (b *TreeBudget) Remaining() BudgetRemaining

Remaining returns the remaining budget as a struct.

func (*TreeBudget) Report

func (b *TreeBudget) Report() UsageReport

Report generates a usage report.

func (*TreeBudget) Reset

func (b *TreeBudget) Reset()

Reset resets the budget counters but keeps the same configuration. Useful for restarting exploration with fresh budget.

func (*TreeBudget) String

func (b *TreeBudget) String() string

String returns a human-readable budget status.

func (*TreeBudget) TokensUsed

func (b *TreeBudget) TokensUsed() int64

TokensUsed returns the total tokens used.

type TreeBudgetConfig

type TreeBudgetConfig struct {
	MaxNodes      int           // Maximum nodes to explore
	MaxDepth      int           // Maximum plan depth
	MaxExpansions int           // Maximum alternatives per node
	TimeLimit     time.Duration // Wall clock limit
	LLMCallLimit  int           // Maximum LLM calls
	LLMTokenLimit int           // Maximum tokens across all LLM calls
	CostLimitUSD  float64       // Maximum cost in USD
}

TreeBudgetConfig contains configuration for tree exploration limits.

func DefaultTreeBudgetConfig

func DefaultTreeBudgetConfig() TreeBudgetConfig

DefaultTreeBudgetConfig returns sensible defaults.

type TreeCompletionStats

type TreeCompletionStats struct {
	TotalNodes  int64
	PrunedNodes int64
	MaxDepth    int
	BestScore   float64
}

TreeCompletionStats contains statistics for tree completion.

type TreeDegradation

type TreeDegradation int

TreeDegradation represents the current degradation level.

const (
	// TreeDegradationNormal is full MCTS with all features.
	TreeDegradationNormal TreeDegradation = iota

	// TreeDegradationReduced has fewer expansions and quick simulation only.
	TreeDegradationReduced

	// TreeDegradationMinimal has single expansion and no simulation.
	TreeDegradationMinimal

	// TreeDegradationLinear falls back to linear planning.
	TreeDegradationLinear
)

func (TreeDegradation) String

func (d TreeDegradation) String() string

String returns a human-readable degradation level name.

type TreeModeDecision

type TreeModeDecision struct {
	// UseTreeMode is true if tree-based MCTS should be used.
	UseTreeMode bool

	// Reason explains why this decision was made.
	Reason string

	// Complexity is the estimated task complexity (0-1).
	Complexity float64

	// Triggers lists which conditions activated tree mode.
	Triggers []string
}

TreeModeDecision contains the decision about whether to use tree mode.

func ShouldUseTreeMode

func ShouldUseTreeMode(task string, metrics *SessionMetrics, config PlanPhaseConfig) TreeModeDecision

ShouldUseTreeMode determines if tree mode should be activated.

The decision is based on: - Configuration settings (EnableTreeMode, AlwaysUseTreeMode) - Task complexity estimation from the description - Session history (previous failures, blast radius)

Inputs:

  • task: The user's task description.
  • metrics: Session metrics (may be nil).
  • config: Plan phase configuration.

Outputs:

  • TreeModeDecision: Decision with reasoning.

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

type TreeSubState

type TreeSubState string

TreeSubState represents states within tree mode planning. Used to track progress through MCTS phases within the broader CB-11 agent loop.

const (
	// TreeSubStateNone indicates not in tree mode.
	TreeSubStateNone TreeSubState = ""

	// TreeSubStateExpand indicates the expansion phase (generating child nodes).
	TreeSubStateExpand TreeSubState = "expanding"

	// TreeSubStateSelect indicates the selection phase (UCB1 traversal).
	TreeSubStateSelect TreeSubState = "selecting"

	// TreeSubStateSimulate indicates the simulation phase (evaluating actions).
	TreeSubStateSimulate TreeSubState = "simulating"

	// TreeSubStateBackprop indicates the backpropagation phase (updating scores).
	TreeSubStateBackprop TreeSubState = "backpropagating"

	// TreeSubStateExtracting indicates extracting the best path.
	TreeSubStateExtracting TreeSubState = "extracting_best"
)

func (TreeSubState) IsActive

func (s TreeSubState) IsActive() bool

IsActive returns true if in an active tree mode state.

func (TreeSubState) String

func (s TreeSubState) String() string

String returns the string representation.

type UCB1Policy

type UCB1Policy struct {
	// ExplorationConstant (C) controls exploration vs exploitation.
	// Higher values favor exploration of less-visited nodes.
	// Typical values: 1.41 (sqrt(2)), 2.0 (more exploration)
	ExplorationConstant float64
}

UCB1Policy implements the Upper Confidence Bound 1 selection policy.

UCB1 balances exploitation (high average score) with exploration (low visit count) using the formula:

UCB1(node) = avgScore + C * sqrt(ln(parentVisits) / nodeVisits)

Where C is the exploration constant (typically sqrt(2) ≈ 1.41).

Thread Safety: Safe for concurrent use.

func NewUCB1Policy

func NewUCB1Policy(explorationConstant float64) *UCB1Policy

NewUCB1Policy creates a UCB1 selection policy.

Inputs:

  • explorationConstant: The C parameter (use 1.41 for standard UCB1).

Outputs:

  • *UCB1Policy: Ready to use selection policy.

func (*UCB1Policy) Select

func (p *UCB1Policy) Select(parent *PlanNode) *PlanNode

Select implements SelectionPolicy using UCB1.

type UsageReport

type UsageReport struct {
	Elapsed       time.Duration   `json:"elapsed"`
	NodesExplored int64           `json:"nodes_explored"`
	LLMCalls      int64           `json:"llm_calls"`
	TokensUsed    int64           `json:"tokens_used"`
	CostUSD       float64         `json:"cost_usd"`
	Exhausted     bool            `json:"exhausted"`
	ExhaustedBy   string          `json:"exhausted_by,omitempty"`
	Remaining     BudgetRemaining `json:"remaining"`
}

UsageReport returns a detailed usage report.

type WorkerStats

type WorkerStats struct {
	WorkerID   int
	Iterations int64
	TotalTime  time.Duration
}

WorkerStats contains per-worker statistics.

Directories

Path Synopsis
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.
indexes
Package indexes provides the 6 index implementations for CRS.
Package indexes provides the 6 index implementations for CRS.

Jump to

Keyboard shortcuts

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