Documentation
¶
Overview ¶
Package config provides configuration loading for the trace service.
This package implements the tool routing registry loader (CB-31e) which provides structured keywords and usage guidance for the tool router.
Thread Safety:
All exported functions and types are safe for concurrent use.
Index ¶
- Constants
- func PopulateToolDefinitionsWhenToUse(ctx context.Context, defs []tools.ToolDefinition) (int, error)
- func RecordFallbackBlocked()
- func RecordRoutingDecision(toolName, source string)
- func ResetPreFilterConfig()
- func ResetToolRoutingRegistry()
- type ConceptSynonyms
- type ConfusionPair
- type EncyclopediaEntry
- type ForcedMapping
- type IntentPattern
- type NegationRule
- type PreFilterConfig
- type ToolEntryYAML
- type ToolMatch
- type ToolRegistryYAML
- type ToolRoutingEntry
- type ToolRoutingRegistry
- func (r *ToolRoutingRegistry) FindToolsByKeyword(query string) []ToolMatch
- func (r *ToolRoutingRegistry) GetEntry(toolName string) (*ToolRoutingEntry, bool)
- func (r *ToolRoutingRegistry) GetWhenToUse(toolName string) (tools.WhenToUse, bool)
- func (r *ToolRoutingRegistry) KeywordCount() int
- func (r *ToolRoutingRegistry) LoadedAt() int64
- func (r *ToolRoutingRegistry) ToolCount() int
- type ToolSubstitutionYAML
Constants ¶
const ( // DefaultMinCandidates is the default minimum candidate count. DefaultMinCandidates = 3 // DefaultMaxCandidates is the default maximum candidate count. DefaultMaxCandidates = 20 // DefaultNegationProximity is the default maximum word distance for negation. DefaultNegationProximity = 3 // DefaultBoostAmount is the default confusion pair boost. DefaultBoostAmount = 3.0 // DefaultScoringMode is the default Phase 3 scoring strategy. // "embedding_primary" uses pure embedding scoring with passthrough fallback. DefaultScoringMode = "embedding_primary" // DefaultScoreGapThreshold is the minimum score drop between consecutive // tools that triggers a cutoff in the adaptive candidate window. DefaultScoreGapThreshold = 0.15 // DefaultScoreFloor is the minimum absolute score for inclusion in the // candidate set. Tools scoring below this are excluded. DefaultScoreFloor = 0.30 )
const ( // MaxYAMLFileSize is the maximum allowed YAML file size (1MB). // SEC2: Prevents memory issues from large files. MaxYAMLFileSize = 1024 * 1024 // MaxKeywordsPerTool is the maximum keywords allowed per tool. MaxKeywordsPerTool = 50 // MaxToolsInRegistry is the maximum tools allowed in registry. MaxToolsInRegistry = 200 )
Variables ¶
This section is empty.
Functions ¶
func PopulateToolDefinitionsWhenToUse ¶
func PopulateToolDefinitionsWhenToUse(ctx context.Context, defs []tools.ToolDefinition) (int, error)
PopulateToolDefinitionsWhenToUse populates WhenToUse on tool definitions from the registry.
Description:
This function bridges the gap between the YAML-defined routing metadata and the code-defined ToolDefinitions. Call this after loading tools to enrich them with routing guidance.
Inputs:
ctx - Context for tracing. Must not be nil. defs - Slice of tool definitions to populate (modified in place).
Outputs:
int - Number of tools that were populated. error - Non-nil if registry loading fails.
Thread Safety: Safe for concurrent use.
Example:
defs := registry.GetToolDefinitions()
count, err := config.PopulateToolDefinitionsWhenToUse(ctx, defs)
if err != nil {
slog.Warn("Failed to populate WhenToUse", "error", err)
}
func RecordFallbackBlocked ¶
func RecordFallbackBlocked()
RecordFallbackBlocked records when fallback was blocked.
Description:
Increments the fallback_blocked_total Prometheus counter when the router forces synthesis instead of falling back to main LLM.
Thread Safety: Safe for concurrent use.
func RecordRoutingDecision ¶
func RecordRoutingDecision(toolName, source string)
RecordRoutingDecision records a routing decision metric.
Description:
Increments the tool_routing_decisions_total Prometheus counter with the specified tool name and decision source.
Inputs:
toolName - The name of the tool that was selected. source - The decision source (e.g., "router", "keywords", "fallback").
Thread Safety: Safe for concurrent use.
func ResetPreFilterConfig ¶
func ResetPreFilterConfig()
ResetPreFilterConfig resets the cached config for testing.
Description:
Clears the cached pre-filter config so tests can reload with different data.
Thread Safety: Safe for concurrent use.
func ResetToolRoutingRegistry ¶
func ResetToolRoutingRegistry()
ResetToolRoutingRegistry resets the cached registry for testing.
Description:
Clears the cached registry and sync.Once state to allow re-loading the registry on the next call to GetToolRoutingRegistry.
Thread Safety:
Safe for concurrent use. Uses mutex to protect against data races when called concurrently with GetToolRoutingRegistry.
WARNING: This function is intended for testing only. Do not use in production code as it can cause inconsistent state if called while other goroutines are using the registry.
Types ¶
type ConceptSynonyms ¶
ConceptSynonyms maps natural-language concept nouns to the verb/prefix forms that developers use in function names. Used by IT-12 conceptual symbol resolution to bridge the gap between user descriptions ("initialization") and actual code naming conventions ("init", "new", "build").
The map is loaded from concept_synonyms.yaml at startup and cached.
Thread Safety ¶
Safe for concurrent use after initialization (immutable after load).
func LoadConceptSynonyms ¶
func LoadConceptSynonyms() (ConceptSynonyms, error)
LoadConceptSynonyms loads and caches the concept synonym mappings from the embedded YAML configuration. Returns the cached result on subsequent calls.
Description ¶
Parses concept_synonyms.yaml which maps concept nouns to function name verbs/prefixes. The YAML format is a simple map of string to string list.
Outputs ¶
- ConceptSynonyms: The loaded mapping. Never nil on success.
- error: Non-nil if YAML parsing fails.
Thread Safety ¶
Safe for concurrent use (uses sync.Once internally).
func MustLoadConceptSynonyms ¶
func MustLoadConceptSynonyms() ConceptSynonyms
MustLoadConceptSynonyms loads concept synonyms or returns an empty map on error. Logs a warning if loading fails but does not panic — conceptual resolution will still work, just without synonym expansion.
Description ¶
Convenience wrapper for code paths where synonym loading failure should degrade gracefully rather than stop the system.
Outputs ¶
- ConceptSynonyms: The loaded mapping, or an empty map on error.
Thread Safety ¶
Safe for concurrent use.
type ConfusionPair ¶
type ConfusionPair struct {
// ToolA is the first tool in the pair.
ToolA string `yaml:"tool_a"`
// ToolB is the second tool in the pair.
ToolB string `yaml:"tool_b"`
// ToolAPatterns boost ToolA when matched.
ToolAPatterns []string `yaml:"tool_a_patterns"`
// ToolBPatterns boost ToolB when matched.
ToolBPatterns []string `yaml:"tool_b_patterns"`
// BoostAmount is the score boost applied (default 3.0).
BoostAmount float64 `yaml:"boost_amount"`
}
ConfusionPair resolves ambiguity between two frequently confused tools.
Description:
When both tools in a pair appear in the candidate set, pattern matching determines which one to boost. This prevents the router from picking the wrong one in an ambiguous pair.
type EncyclopediaEntry ¶
type EncyclopediaEntry struct {
// Tool is the target tool name.
Tool string `yaml:"tool"`
// Tier is the action tier: "force", "boost", or "hint".
Tier string `yaml:"tier"`
// BoostAmount is the score bonus applied when tier=boost. Ignored for other tiers.
// Range [0.0, 0.30] to nudge without overriding embedding scores.
BoostAmount float64 `yaml:"boost_amount"`
// Intents are regex or substring patterns describing user intent.
Intents []IntentPattern `yaml:"intents"`
// AntiSignals suppress this entry when ANY anti-signal matches the query.
// Use specific phrases, not single words.
AntiSignals []string `yaml:"anti_signals"`
// ConflictWith names a tool that conflicts with this entry.
// Used for documentation and future conflict resolution.
ConflictWith string `yaml:"conflict_with,omitempty"`
// Reason explains why this mapping exists (for logging/tracing).
Reason string `yaml:"reason"`
}
EncyclopediaEntry represents a single tool's intent-to-routing mapping.
Description:
Maps user intent patterns to a tool with a tiered action: - "force": deterministic selection, skip the router entirely. - "boost": add boost_amount to the tool's embedding score. - "hint": ensure the tool is in the candidate set (min_candidates fill). Anti-signals suppress the entry when matched, preventing false positives. CB-62 Rev 2.
Thread Safety: Immutable after loading; safe for concurrent use.
type ForcedMapping ¶
type ForcedMapping struct {
// Patterns are substring or regex patterns to match against the query.
Patterns []string `yaml:"patterns"`
// Tool is the tool to force when a pattern matches.
Tool string `yaml:"tool"`
// Reason explains why this mapping exists (for logging/tracing).
Reason string `yaml:"reason"`
}
ForcedMapping maps phrase patterns to a deterministic tool selection.
Description:
When any pattern matches the query (substring or regex), the pre-filter forces the specified tool and skips the LLM router entirely.
type IntentPattern ¶
type IntentPattern struct {
// Pattern is the matching pattern (regex if contains ".*", otherwise substring).
Pattern string `yaml:"pattern"`
// Description optionally explains what this pattern matches.
Description string `yaml:"description,omitempty"`
}
IntentPattern is a regex or substring pattern describing a user intent.
Description:
Patterns containing ".*" are treated as regex; otherwise substring match. CB-62 Rev 2.
type NegationRule ¶
type NegationRule struct {
// NegationWords are words that negate meaning (e.g., "no", "not", "never").
NegationWords []string `yaml:"negation_words"`
// TriggerKeywords are keywords that, when negated, change the tool choice.
TriggerKeywords []string `yaml:"trigger_keywords"`
// WrongTool is the tool the router would likely choose without negation awareness.
WrongTool string `yaml:"wrong_tool"`
// CorrectTool is the tool to use when negation is detected.
CorrectTool string `yaml:"correct_tool"`
// Action is either "force" (skip router) or "boost" (increase score).
Action string `yaml:"action"`
// Reason explains why this rule exists.
Reason string `yaml:"reason"`
}
NegationRule detects negation patterns that require different tool selection.
Description:
When a negation word appears within NegationProximity words of a trigger keyword, the pre-filter redirects from WrongTool to CorrectTool.
type PreFilterConfig ¶
type PreFilterConfig struct {
// Enabled controls whether the pre-filter is active.
Enabled bool `yaml:"enabled"`
// MinCandidates is the minimum number of tools to return.
// Ensures the router always has enough candidates.
MinCandidates int `yaml:"min_candidates"`
// MaxCandidates is the maximum number of tools to return.
// Limits the router's classification space.
MaxCandidates int `yaml:"max_candidates"`
// NegationProximity is the maximum word distance between a negation word
// and a trigger keyword for negation detection to fire.
NegationProximity int `yaml:"negation_proximity"`
// ScoringMode controls Phase 3 scoring: "hybrid" (0.4 BM25 + 0.6 embedding)
// or "embedding_primary" (pure embedding, passthrough on fallback).
ScoringMode string `yaml:"scoring_mode"`
// ScoreGapThreshold is the minimum score drop between consecutive tools
// that triggers a cutoff. Tools below the gap are excluded. Default: 0.15.
ScoreGapThreshold float64 `yaml:"score_gap_threshold"`
// ScoreFloor is the minimum absolute score for inclusion. Default: 0.30.
ScoreFloor float64 `yaml:"score_floor"`
// AlwaysInclude lists tool names that must always be in the narrowed set.
AlwaysInclude []string `yaml:"always_include"`
// ForcedMappings maps exact phrase patterns to deterministic tool selections.
ForcedMappings []ForcedMapping `yaml:"forced_mappings"`
// NegationRules detect negation patterns that change tool selection.
NegationRules []NegationRule `yaml:"negation_rules"`
// ConfusionPairs resolve ambiguity between frequently confused tools.
ConfusionPairs []ConfusionPair `yaml:"confusion_pairs"`
// RoutingEncyclopedia maps user intent patterns to tools with tiered actions.
// CB-62 Rev 2: Replaces ad-hoc forced_mappings/confusion_pairs over time.
RoutingEncyclopedia []EncyclopediaEntry `yaml:"routing_encyclopedia"`
}
PreFilterConfig defines the pre-filter behavior and rules.
Description:
Contains all configuration for the rule-based pre-filter including forced mappings, negation rules, confusion pairs, and candidate bounds.
Thread Safety: Immutable after loading; safe for concurrent use.
func GetPreFilterConfig ¶
func GetPreFilterConfig(ctx context.Context) (*PreFilterConfig, error)
GetPreFilterConfig returns the cached pre-filter configuration.
Description:
Loads the pre-filter rules on first call and caches for subsequent calls. Uses sync.Once for thread-safe initialization.
Inputs:
ctx - Context for tracing. Must not be nil.
Outputs:
*PreFilterConfig - The loaded configuration. Never nil on success. error - Non-nil if loading or validation failed.
Thread Safety: Safe for concurrent use via sync.Once.
func LoadPreFilterConfig ¶
func LoadPreFilterConfig(ctx context.Context, data []byte) (*PreFilterConfig, error)
LoadPreFilterConfig loads and validates a PreFilterConfig from YAML bytes.
Description:
Parses the YAML, applies defaults for missing fields, and validates all rules for consistency (non-empty tool names, valid actions, etc.).
Inputs:
ctx - Context for tracing. data - Raw YAML bytes to parse.
Outputs:
*PreFilterConfig - The validated configuration. error - Non-nil if parsing or validation fails.
type ToolEntryYAML ¶
type ToolEntryYAML struct {
Name string `yaml:"name"`
Keywords []string `yaml:"keywords"`
UseWhen string `yaml:"use_when"`
AvoidWhen string `yaml:"avoid_when,omitempty"`
InsteadOf []ToolSubstitutionYAML `yaml:"instead_of,omitempty"`
Requires []string `yaml:"requires,omitempty"`
}
ToolEntryYAML represents a single tool entry in the YAML file.
type ToolMatch ¶
type ToolMatch struct {
ToolName string
MatchCount int
MatchedKeywords []string
Entry *ToolRoutingEntry
}
ToolMatch represents a tool that matched keywords in a query.
type ToolRegistryYAML ¶
type ToolRegistryYAML struct {
Tools []ToolEntryYAML `yaml:"tools"`
}
ToolRegistryYAML is the root structure for YAML deserialization.
This struct uses concrete types (ToolEntryYAML, ToolSubstitutionYAML) rather than map[string]any to comply with CLAUDE.md Section 4.5. All nested slices are validated during parsing via parseToolRegistryYAML().
type ToolRoutingEntry ¶
type ToolRoutingEntry struct {
// Name is the tool name.
Name string
// Keywords are query terms that trigger this tool.
Keywords []string
// UseWhen describes when to use this tool.
UseWhen string
// AvoidWhen describes when NOT to use this tool.
AvoidWhen string
// InsteadOf lists tool substitutions.
InsteadOf []tools.ToolSubstitution
// Requires lists prerequisites.
Requires []string
}
ToolRoutingEntry contains routing guidance for a single tool.
type ToolRoutingRegistry ¶
type ToolRoutingRegistry struct {
// contains filtered or unexported fields
}
ToolRoutingRegistry provides tool routing metadata for the tool router.
Thread Safety: Safe for concurrent use after initialization.
func GetToolRoutingRegistry ¶
func GetToolRoutingRegistry(ctx context.Context) (*ToolRoutingRegistry, error)
GetToolRoutingRegistry returns the cached tool routing registry.
Description:
Loads the tool routing registry on first call and caches it for subsequent calls. Uses sync.Once for thread-safe initialization.
Inputs:
ctx - Context for tracing. Must not be nil.
Outputs:
*ToolRoutingRegistry - The loaded registry. Never nil on success. error - Non-nil if loading failed.
Thread Safety: Safe for concurrent use via sync.Once.
Example:
registry, err := config.GetToolRoutingRegistry(ctx)
if err != nil {
return fmt.Errorf("loading tool registry: %w", err)
}
matches := registry.FindToolsByKeyword("callers")
func (*ToolRoutingRegistry) FindToolsByKeyword ¶
func (r *ToolRoutingRegistry) FindToolsByKeyword(query string) []ToolMatch
FindToolsByKeyword finds tools matching keywords in a query.
Description:
Performs O(1) keyword lookup using the pre-built keyword index. Returns tools sorted by number of matching keywords (most matches first).
Inputs:
query - The user query to match against.
Outputs:
[]ToolMatch - Tools matching the query, sorted by match count.
P2: Uses pre-built keyword index for O(1) lookup.
func (*ToolRoutingRegistry) GetEntry ¶
func (r *ToolRoutingRegistry) GetEntry(toolName string) (*ToolRoutingEntry, bool)
GetEntry returns the routing entry for a tool.
Inputs:
toolName - The tool name to look up.
Outputs:
*ToolRoutingEntry - The entry, or nil if not found. bool - True if found.
func (*ToolRoutingRegistry) GetWhenToUse ¶
func (r *ToolRoutingRegistry) GetWhenToUse(toolName string) (tools.WhenToUse, bool)
GetWhenToUse returns WhenToUse guidance for a tool.
Description:
Converts the routing entry to a WhenToUse struct for use in ToolDefinition population.
Inputs:
toolName - The tool name.
Outputs:
tools.WhenToUse - The guidance struct. bool - True if tool was found.
func (*ToolRoutingRegistry) KeywordCount ¶
func (r *ToolRoutingRegistry) KeywordCount() int
KeywordCount returns the number of unique keywords indexed.
Outputs:
int - Number of unique keywords across all tools.
Thread Safety: Safe for concurrent use (read-only after initialization).
func (*ToolRoutingRegistry) LoadedAt ¶
func (r *ToolRoutingRegistry) LoadedAt() int64
LoadedAt returns when the registry was loaded.
Outputs:
int64 - Unix milliseconds UTC when the registry was loaded.
Thread Safety: Safe for concurrent use (read-only after initialization).
func (*ToolRoutingRegistry) ToolCount ¶
func (r *ToolRoutingRegistry) ToolCount() int
ToolCount returns the number of tools in the registry.
Outputs:
int - Number of registered tools.
Thread Safety: Safe for concurrent use (read-only after initialization).
type ToolSubstitutionYAML ¶
ToolSubstitutionYAML represents a tool substitution in YAML.