Documentation
¶
Overview ¶
This file re-exports symbols from the agent sub-package so that existing callers of engine.SubAgentMode, engine.NewSubAgentBudget, etc. keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
This file re-exports symbols from the compact sub-package so that existing callers of engine.* keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
This file re-exports symbols from the intelligence sub-package so that existing callers of engine.Intent, engine.NewIntentClassifier, etc. keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
This file re-exports symbols from the lifecycle sub-package so that existing callers of engine.SessionLifecycle, engine.NewLimitTracker, etc. keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
This file re-exports symbols from the observability sub-package so that existing callers of engine.Profiler, engine.NewProfiler, etc. keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
This file re-exports symbols from the planning sub-package so that existing callers of engine.ExecutionPlan, engine.NewExecutionPlanner, etc. keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
This file re-exports symbols from the project sub-package so that existing callers of engine.ProjectAnalysis, engine.NewProjectAnalyzer, etc. keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
Package engine holds the extracted tool execution types and functions. These are prepared for future integration into the agentLoop.
This file re-exports symbols from the streaming sub-package so that existing callers of engine.ResponseCache, engine.NewResponseCache, etc. keep compiling during the Stage 2 migration. See REFACTOR_PLAN.md.
Index ¶
- Constants
- Variables
- func AdjustIndexToPreserveAPIInvariants(msgs []types.EyrieMessage, startIdx int) int
- func AutoFixPrompt(path, content string, errors []ValidationError) string
- func BrainstormPrompt(phase BrainstormPhase, topic string, context string) string
- func BuildCompactPrompt(variant CompactVariant) string
- func BuildEditorPrompt(plan *ArchitectPlan, step PlanStep) string
- func CheckpointPrompts(phase CheckpointPhase, files []string) string
- func ClassifyRisk(changes []SemanticChange) string
- func ClassifyTaskComplexity(task string) string
- func CompressForContext(text string, budget int) (string, int)
- func CorrectCoursePrompt(originalIntent, currentState, problem string) string
- func CountTokens(text string) int
- func CountTokensFast(text string) int
- func DefaultCouncilModels() []string
- func DefaultSoulPath() string
- func DefaultValidateCmd(dir string) string
- func DegradationTimeout(turnCount int) time.Duration
- func DetectGenerated(path string) bool
- func DiffPrompts(old, new string) string
- func DirectivePrompt(d Directive) string
- func DynamicMaxTokens(messages []types.EyrieMessage, contextSize int, taskType string) int
- func EditStrategyPrompt(strategy EditStrategy) string
- func EstimateDiffTokens(diff string) int
- func EstimateMessageTokens(m types.EyrieMessage) int
- func EstimateSavings(plan *ArchitectPlan, architectCost, editorCost float64) string
- func EstimateStringTokens(content string) int
- func EstimateTokens(msgs []types.EyrieMessage) int
- func ExperimentPrompt(iteration int, validateCmd string, history []ExperimentResult, ...) string
- func ExtractPattern(errorMsg string) string
- func FilterToolsForMode(mode SubAgentMode, available []string) []string
- func FormatCompactSummary(raw string) string
- func FormatCompressedPR(pr *CompressedPR) string
- func FormatCostDisplay(totalUSD float64) string
- func FormatError(enriched *EnrichedError) string
- func FormatGateResults(results []GateResult) string
- func FormatHealResult(result *HealResult) string
- func FormatPartyTurn(p Persona, content string) string
- func FormatPattern(p *PromptPattern) string
- func FormatPrediction(pred *Prediction, model string) string
- func FormatPrompt(base string, sections []PromptSection) string
- func FormatResults(results []BackgroundResult) string
- func FormatSkill(s *Skill) string
- func FormatTeachingMoment(action, reasoning string) string
- func GenerateAwaySummary(ctx context.Context, session *Session, cfg AwaySummaryConfig, ...) (string, error)
- func GenerateSummary(diff *SemanticDiff) string
- func HasTextContent(m types.EyrieMessage) bool
- func ImplementFromSpecPrompt(spec *Spec) string
- func InitSoulPrompt() string
- func InvestigatePrompt(phase InvestigatePhase, context string) string
- func IsCompactableTool(name string) bool
- func LearnPrompt(context string) string
- func ListPersonas() string
- func LoadCostHistory() ([]analytics.CostEntry, error)
- func MergeSynthesisPrompt(subtasks []SubTask, results map[string]string) string
- func ModelPricing(modelName string) (inputPricePerM, outputPricePerM float64)
- func NormalizeError(msg string) string
- func QuickDevClarifyPrompt(userInput string) string
- func QuickDevPresentPrompt() string
- func QuickDevReviewPrompt(filesChanged []string) string
- func RebuildSessionTransport(ctx context.Context, s *Session, useDeploymentRouting bool, ...) error
- func ReflectPrompt(sessionSummary string) string
- func ReviewPrompt(files []string) string
- func ShouldShowAwaySummary(lastActivity time.Time, cfg AwaySummaryConfig) bool
- func ShouldUseArchitect(prompt string, messageCount int) bool
- func SpecGeneratePrompt(intent string) string
- func SummarizeTrajectory(messages []types.EyrieMessage) string
- func SynthesizeSubAgent(ctx context.Context, llm LLMClient, model string, ...) (string, error)
- func TeachPromptAugment(depth int) string
- func TruncateHunks(diff string, maxTokens int) string
- func WarnIfExpensive(pred *Prediction, budgetUSD float64) string
- type AIComment
- type AIWatcher
- type APICompactConfig
- type APICompactStrategy
- type ActionManager
- type ActionRequired
- type AdaptivePrompt
- type AdversarialReview
- type AgentIntelligence
- type AgentLogger
- type AliasSuggestion
- type Allocation
- type Annotation
- type AnnotationManager
- type Architect
- type ArchitectConfig
- type ArchitectMessage
- type ArchitectPlan
- type Assessment
- type Assumption
- type AssumptionStatus
- type AssumptionTracker
- func (at *AssumptionTracker) Add(text string)
- func (at *AssumptionTracker) Failed() []Assumption
- func (at *AssumptionTracker) Reset()
- func (at *AssumptionTracker) Summary() string
- func (at *AssumptionTracker) VerifyCommandSucceeds(text, cmd string)
- func (at *AssumptionTracker) VerifyFileExists(text, path string)
- type AutoCommitter
- type AutoCompactor
- func (ac *AutoCompactor) AutoCompactIfNeeded(ctx context.Context, sess *Session) (string, bool)
- func (ac *AutoCompactor) GetAutoCompactThreshold() int
- func (ac *AutoCompactor) LastStrategy() string
- func (ac *AutoCompactor) ResetFailures()
- func (ac *AutoCompactor) RunCompaction(ctx context.Context, sess *Session) (string, error)
- func (ac *AutoCompactor) ShouldAutoCompact(sess *Session) bool
- type AutonomyConfig
- type AutonomyLevel
- type AwaySummaryConfig
- type BackgroundAgentPool
- type BackgroundResult
- type BackgroundRunner
- func (br *BackgroundRunner) Collect(id string) *BackgroundTask
- func (br *BackgroundRunner) Delegate(ctx context.Context, prompt string, ...) string
- func (br *BackgroundRunner) ListActive() []*BackgroundTask
- func (br *BackgroundRunner) PendingCount() int
- func (br *BackgroundRunner) Status(id string) *BackgroundTask
- type BackgroundTask
- type BacktrackEngine
- type Belief
- type BeliefState
- func (bs *BeliefState) FormatForPrompt() string
- func (bs *BeliefState) Get(subject string) []*Belief
- func (bs *BeliefState) Invalidate(subject string)
- func (bs *BeliefState) Prune(currentTurn int)
- func (bs *BeliefState) Record(category, subject, content string, turn int)
- func (bs *BeliefState) Size() int
- type Bot
- type BrainstormPhase
- type BrainstormSession
- type BudgetAlert
- type BudgetAllocator
- func (ba *BudgetAllocator) Allocate() map[string]int
- func (ba *BudgetAllocator) DefaultAllocations()
- func (ba *BudgetAllocator) FormatBudget() string
- func (ba *BudgetAllocator) GetAvailable() int
- func (ba *BudgetAllocator) Rebalance()
- func (ba *BudgetAllocator) Register(name string, min, max, priority int, flexible bool)
- func (ba *BudgetAllocator) Release(name string, amount int)
- func (ba *BudgetAllocator) RequestMore(name string, needed int) int
- func (ba *BudgetAllocator) SuggestCompaction() string
- func (ba *BudgetAllocator) WouldExceed(name string, additional int) bool
- type CacheEntry
- type CacheStats
- type Capability
- type CapabilityRegistry
- type ChangeEntry
- type ChangeStats
- type ChatClient
- type CheckpointPhase
- type ChunkedResponse
- type ClassifiedInput
- type ClipboardBridge
- type ClipboardMonitor
- type CodingSoul
- type CommandFrequency
- type CommandHistory
- type CommandRecord
- type CommandSuggestion
- type Comment
- type CompactConfig
- type CompactResult
- type CompactStrategy
- type CompactVariant
- type CompactionTrigger
- type CompressMessage
- type CompressStrategy
- type CompressedBlock
- type CompressedFile
- type CompressedPR
- type CompressionResult
- type ConsensusResult
- type ConsensusSampler
- type ConsolidatedMemory
- type ConsolidatorStats
- type Convention
- type ConventionSet
- type ConversationSummarizer
- type CoreLoop
- type Cost
- type CostEntry
- type CostOptimizer
- type CostTracker
- type CostTrackerInterface
- type CouncilConfig
- type CouncilRanking
- type CouncilResponse
- type CouncilResult
- type Counter
- type Critic
- type CronExpr
- type CronJob
- type CronScheduler
- type CrossSessionLearner
- type DebugRecorder
- type DebugSession
- type DebugStep
- type DecisionPoint
- type DegradationDetector
- func (dd *DegradationDetector) IsDegraded() bool
- func (dd *DegradationDetector) RecordTurn(toolName string, success bool)
- func (dd *DegradationDetector) RecoveryAction() string
- func (dd *DegradationDetector) Reset()
- func (dd *DegradationDetector) Signal() DegradationSignal
- func (dd *DegradationDetector) Stats() (turns, errors, consecutive int)
- type DegradationSignal
- type Dependency
- type DependencyUpdater
- type Diff3Conflict
- type Diff3Region
- type Diff3Result
- type Diff3Stats
- type DiffHunk
- type DiffLine
- type DiffPreview
- type DiffReporter
- type DiffSandbox
- type DiffSummarizer
- type DiffSummary
- type Directive
- type DistillExample
- type DistillStats
- type DistillationPipeline
- type Edit
- type EditStrategy
- type EfficientPrompter
- func (ep *EfficientPrompter) DisableStrategy(name string)
- func (ep *EfficientPrompter) EnableStrategy(name string)
- func (ep *EfficientPrompter) EstimateSavings(prompt string) int
- func (ep *EfficientPrompter) FormatEfficientStats() string
- func (ep *EfficientPrompter) Optimize(prompt string) *OptimizedResult
- func (ep *EfficientPrompter) OptimizeMessages(messages []PromptMsg) []PromptMsg
- func (ep *EfficientPrompter) OptimizeOutput(output string) string
- type EfficientStats
- type Engine
- type EnrichedError
- type ErrorContext
- type ErrorGroup
- type ErrorGrouper
- type ErrorHelp
- type ErrorInstance
- type ErrorLearner
- type ErrorLearnerStats
- type ErrorPattern
- type ErrorPatternDB
- type ErrorRecovery
- type Event
- type EventBus
- type EventType
- type EvolvingMemoryAdapter
- type EvolvingMemoryInterface
- type ExecutionPlan
- type ExecutionPlanner
- type ExecutionStep
- type Experience
- type ExperienceStats
- type ExperienceStore
- type ExperimentLoop
- type ExperimentResult
- type FailureLayer
- type FailurePattern
- type Feedback
- type FeedbackCollector
- type FewShotExample
- type FewShotStore
- type FieldSpec
- type FileChange
- type FileDiffReport
- type FileEvent
- type FileFix
- type FileMentionDetector
- type FileSnapshot
- type FileState
- type FileSummary
- type FileTracker
- type FileWatcher
- type FormField
- type FormResponse
- type FormatRule
- type FormattedResponse
- type GatePhase
- type GateResult
- type GenCheck
- type GenIssue
- type GenValidation
- type GenValidator
- type Goal
- type GoalEvent
- type GoalOption
- type GoalStatus
- type GoalTracker
- type GroundingResult
- type HallucinationGuard
- type HeadTailWindow
- type HealAttempt
- type HealResult
- type HintsLoader
- type Hypothesis
- type ImpactAnalysis
- type ImpactAnalyzer
- type ImplicitSignal
- type InjectionScanner
- type Insight
- type InspectionAction
- type InspectionResult
- type IntegrationPipeline
- func (p *IntegrationPipeline) EndSession(success bool, taskGoal string) *SessionSummary
- func (p *IntegrationPipeline) FormatPipelineStatus() string
- func (p *IntegrationPipeline) PostResponse(response string, messages []types.EyrieMessage) *PostResponseResult
- func (p *IntegrationPipeline) PostToolExecution(toolName string, args map[string]interface{}, output string, err error) *PostToolResult
- func (p *IntegrationPipeline) PreQuery(messages []types.EyrieMessage, userInput string) *PreQueryResult
- type Intelligence
- type Intent
- type IntentClassifier
- type IntentRule
- type InvestigatePhase
- type Issue
- type IssueIndex
- type KnowledgeBase
- type KnowledgeEntry
- type KnowledgeStats
- type LLMClient
- type LanguageConfig
- type LanguageRegistry
- type LargeResponseHandler
- type LearnedPattern
- type LearnerStats
- type LimitTracker
- type LintLoop
- type LintResult
- type LogEntry
- type LogLevel
- type LoopDetector
- type MemoryConsolidator
- type MemoryRecaller
- type MicroCompactConfig
- type MicroCompactStrategy
- type MigrationPlan
- type MigrationPlanner
- type MigrationResult
- type MigrationStep
- type ModelPrice
- type ModuleInfo
- type MultiRepoConfig
- type MultiRepoContext
- type Observability
- type OptimizedResult
- type Optimizer
- type OutputRedactor
- type PRCompressor
- type PartySession
- type PartyTurn
- type PatchVerdict
- type Pattern
- type PatternLibrary
- type PendingChange
- type PermissionEngine
- type PermissionMemory
- type PermissionMode
- type PermissionRequest
- type Persona
- type PlanState
- type PlanStep
- type PlannedCall
- type PostResponseResult
- type PostToolResult
- type PreQueryResult
- type Prediction
- type PredictionRecord
- type Preview
- type ProfileSpan
- type Profiler
- type ProjectAnalysis
- type ProjectAnalyzer
- type ProjectContext
- type ProjectSnapshot
- type ProjectSnapshotCache
- type PromptAdjustment
- type PromptBuildContext
- type PromptMsg
- type PromptOpt
- type PromptPattern
- type PromptSection
- type ProtectedPaths
- type QualityGate
- type QualityScorer
- type QuickDevPhase
- type QuickDevState
- type RawMemory
- type Recipe
- type RecipeRegistry
- type Recommendation
- type RecoveryAttempt
- type RecoveryContext
- type RecoveryResult
- type RecoveryStrategy
- type RedactPattern
- type RedactStats
- type ReflectionEntry
- type Reflector
- type Release
- type ReleaseManager
- type ReleaseStats
- type RepoRelation
- type Report
- type RequestCost
- type ResearchAgent
- type ResearchFinding
- type ResearchQuery
- type ResearchResult
- type ResponseCache
- type ResponseContext
- type ResponseFormatter
- type Result
- type ReviewBot
- type ReviewComment
- type ReviewFinding
- type ReviewReport
- type ReviewResult
- type ReviewRule
- type RiskAssessment
- type RiskAssessor
- type RiskContext
- type RiskFactor
- type RiskFactorDef
- type RotatingWriter
- type Rule
- type SafetyLayer
- type SafetyLimits
- type Sample
- type Scaffolder
- type ScaleBehavior
- type ScanResult
- type Schema
- type SchemaValidationError
- type SchemaValidationResult
- type SchemaValidator
- type ScoreWeights
- type ScoredResponse
- type ScrapeResult
- type SelectedTests
- type SelfAssessor
- type SelfAwareness
- type SelfHealer
- func (sh *SelfHealer) ApplyFixes(fixes []FileFix) error
- func (sh *SelfHealer) BuildFixPrompt(script, output, errorMsg string, attempt int) string
- func (sh *SelfHealer) Heal(ctx context.Context, scriptPath string) (*HealResult, error)
- func (sh *SelfHealer) HealCommand(ctx context.Context, command string) (*HealResult, error)
- func (sh *SelfHealer) ParseFix(response string) ([]FileFix, error)
- func (sh *SelfHealer) RunScript(ctx context.Context, path string) (stdout, stderr string, exitCode int, err error)
- type SelfImproveEntry
- type SelfImprover
- type SelfReviewResult
- type SemanticAnalyzer
- type SemanticChange
- type SemanticDiff
- type ServiceOption
- func WithCascade(cascade *branching.CascadeRouter) ServiceOption
- func WithGuardian(guardian *permissions.Guardian) ServiceOption
- func WithLogger(log *logger.Logger) ServiceOption
- func WithMaxBudget(budget float64) ServiceOption
- func WithMemory(mem MemoryRecaller) ServiceOption
- func WithProvider(provider, model string) ServiceOption
- func WithSandbox(sandbox *DiffSandbox) ServiceOption
- func WithTools(registry *tool.Registry) ServiceOption
- func WithTracing(tracer *oteltrace.Tracer) ServiceOption
- type Session
- func (s *Session) AddAssistant(content string)
- func (s *Session) AddUser(content string)
- func (s *Session) AppendSystemContext(content string)
- func (s *Session) AutoCompactIfNeeded() bool
- func (s *Session) Compact()
- func (s *Session) ConvoHead() string
- func (s *Session) ForkConversation(nodeID string) (string, error)
- func (s *Session) ListBranches(nodeID string) ([]*storage.DAGNode, error)
- func (s *Session) LoadMessages(msgs []types.EyrieMessage)
- func (s *Session) MessageCount() int
- func (s *Session) Metrics() *metrics.Registry
- func (s *Session) Model() string
- func (s *Session) Provider() string
- func (s *Session) RawMessages() []types.EyrieMessage
- func (s *Session) ReattachTransport(chat ChatClient, provider string, deploymentRouting bool)
- func (s *Session) RemoveLastExchange()
- func (s *Session) ReplaceSystemContextSection(header, content string)
- func (s *Session) Services() *SessionServices
- func (s *Session) SetAPIKey(provider, apiKey string)
- func (s *Session) SetAPIKeys(apiKeys map[string]string)
- func (s *Session) SetAllowedDirs(dirs []string)
- func (s *Session) SetLogger(l *logger.Logger)
- func (s *Session) SetMaxBudgetUSD(amount float64) error
- func (s *Session) SetMaxTurns(turns int) error
- func (s *Session) SetModel(model string)
- func (s *Session) SetPermissionMode(mode string) error
- func (s *Session) SetProvider(provider string)
- func (s *Session) SetTestClient(c ChatClient)
- func (s *Session) ShouldAutoCompact() bool
- func (s *Session) SmartCompact()
- func (s *Session) SplitTurnNeeded(keepCount int) bool
- func (s *Session) Stream(ctx context.Context) (<-chan StreamEvent, error)
- func (s *Session) SubSession(model, systemPrompt string, registry *tool.Registry) *Session
- func (s *Session) SwitchBranch(nodeID string) error
- func (s *Session) WireAgentTool()
- type SessionCompressor
- type SessionConvention
- type SessionLifecycle
- type SessionMemoryConfig
- type SessionMemoryStrategy
- type SessionOutcome
- type SessionReflection
- type SessionServices
- type SessionSummary
- type SignatureChange
- type SimilarIssue
- type SingleFileWatcher
- type Skill
- type SkillDistillerAdapter
- type SkillRegistry
- type SkillResult
- type SkillStep
- type SkillStoreInterface
- type SmartCompactStrategy
- type SnapshotCache
- type SnapshotTracker
- type Solution
- type SolutionReviewer
- type SourceRoot
- type SourceRoots
- type SpawnDecision
- type SpawnStrategy
- type Spec
- type StagedChange
- type StagedHunk
- type StagingArea
- type StallDetector
- type StallEntry
- type StallResult
- type SteeringMessage
- type SteeringQueue
- type Step
- type StepResult
- type StrategyRegistry
- type StreamEvent
- type StreamOptimizer
- type StreamStats
- type StreamUsage
- type StructuredLogger
- type SubAgentBudget
- type SubAgentConfig
- type SubAgentMode
- type SubTask
- type Subtask
- type SuggestedTask
- type SuggestionEngine
- type SuggestionRule
- type SumMessage
- type Summarizer
- type Summary
- type SummaryLevel
- type SystemPromptBuilder
- func (b *SystemPromptBuilder) AdaptForModel(model string) *SystemPromptBuilder
- func (b *SystemPromptBuilder) AdaptForTask(task string) *SystemPromptBuilder
- func (b *SystemPromptBuilder) AddSection(section PromptSection)
- func (b *SystemPromptBuilder) Build(ctx PromptBuildContext) string
- func (b *SystemPromptBuilder) RemoveSection(name string)
- type Task
- type TaskContext
- type TaskDecomposer
- type TaskPlan
- type TaskQueue
- type TaskScale
- type TeachConfig
- type Template
- type TemplateFile
- type TemplateVariable
- type TestLoop
- type TestResult
- type TestSelector
- type ThinkingPhase
- type ThinkingProtocol
- type ThinkingStep
- type Timeline
- type TimelineEvent
- type TimeoutConfig
- type Timer
- type TokenEntry
- type TokenPredictor
- type TokenReporter
- type ToolCallInfo
- type ToolConfirmationRouter
- type ToolInfo
- type ToolInspector
- type ToolRisk
- type ToolSelection
- type ToolSelector
- type TrajectoryDistiller
- type TrajectoryEvent
- type TrajectoryInspector
- type TrajectoryRun
- type TransferLearning
- type TransferPattern
- type TruncateStrategy
- type URLScraper
- type UndoEntry
- type UndoManager
- func (um *UndoManager) BeforeModify(path string) error
- func (um *UndoManager) Clear()
- func (um *UndoManager) DiffEntry(entry *UndoEntry) string
- func (um *UndoManager) FormatHistory(entries []UndoEntry) string
- func (um *UndoManager) History(limit int) []UndoEntry
- func (um *UndoManager) Peek() *UndoEntry
- func (um *UndoManager) RecordChange(description, toolName string, toolArgs map[string]interface{}, paths []string) string
- func (um *UndoManager) Size() int
- func (um *UndoManager) Undo() (*UndoEntry, error)
- func (um *UndoManager) UndoN(n int) ([]*UndoEntry, error)
- func (um *UndoManager) UndoTo(entryID string) ([]*UndoEntry, error)
- type UpdatePlan
- type ValidationError
- type ValidationResult
- type Violation
- type WatcherConfig
- type WindowMessage
- type WindowResult
- type Workflow
- type WorkflowEngine
- type WorkflowResult
- type WorkflowStep
- type WorkspaceDiffReport
- type WorkspaceState
Constants ¶
const ( SubAgentExplore = agent.SubAgentExplore SubAgentGeneral = agent.SubAgentGeneral DefaultExploreTurns = agent.DefaultExploreTurns DefaultGeneralTurns = agent.DefaultGeneralTurns MaxAgentDepth = agent.MaxAgentDepth )
const ( CompactBase = compact.CompactBase CompactPartial = compact.CompactPartial CompactUpTo = compact.CompactUpTo )
const ( AutonomySupervised = safety.AutonomySupervised AutonomyBasic = safety.AutonomyBasic AutonomySemi = safety.AutonomySemi AutonomyFull = safety.AutonomyFull AutonomyYOLO = safety.AutonomyYOLO PermissionModeDefault = safety.PermissionModeDefault PermissionModeAcceptEdits = safety.PermissionModeAcceptEdits PermissionModeBypassPermissions = safety.PermissionModeBypassPermissions PermissionModeDontAsk = safety.PermissionModeDontAsk PermissionModePlan = safety.PermissionModePlan )
const ConfidenceThreshold = 0.7
ConfidenceThreshold is the minimum confidence score for auto-approval. Below this, the review will not approve even if no issues are found.
const DefaultMaxEntries = streaming.DefaultMaxEntries
const DefaultSnapshotTTL = 10 * time.Second
DefaultSnapshotTTL is the default time-to-live for snapshot cache entries.
const DoomLoopThreshold = control.DoomLoopThreshold
const MaxAutoFixRetries = 3
MaxAutoFixRetries is the maximum number of times to retry auto-fixing a file.
const SynthesisPrompt = "" /* 131-byte string literal not displayed */
SynthesisPrompt is appended when forcing a sub-agent to summarize.
Variables ¶
var ( ExploreTools = agent.ExploreTools ModeToolAllowlist = agent.ModeToolAllowlist )
var ( NewLoopDetector = control.NewLoopDetector NewStallDetector = control.NewStallDetector NewBacktrackEngine = control.NewBacktrackEngine )
var ( NewDiffSandbox = diff.NewDiffSandbox NewStagingArea = diff.NewStagingArea NewDiffPreview = diff.NewDiffPreview NewDiffSummarizer = diff.NewDiffSummarizer NewTestSelector = diff.NewTestSelector ComputeDiff = diff.ComputeDiff ComputeMyersDiff = diff.ComputeMyersDiff RenderUnified = diff.RenderUnified Merge3 = diff.Merge3 MergeClean = diff.MergeClean FormatConflictMarkers = diff.FormatConflictMarkers LCS = diff.LCS EditScript = diff.EditScript BuildDependencyGraph = diff.BuildDependencyGraph GenerateTestCommand = diff.GenerateTestCommand )
var ( NewCommandHistory = history.NewCommandHistory NewConversationSummarizer = history.NewConversationSummarizer NewDistillationPipeline = history.NewDistillationPipeline NewHeadTailWindow = history.NewHeadTailWindow AdaptiveSizes = history.AdaptiveSizes PreserveToolPairs = history.PreserveToolPairs FormatWindow = history.FormatWindow ShouldApply = history.ShouldApply NewFileMentionDetector = history.NewFileMentionDetector NewAnnotationManager = history.NewAnnotationManager StripAnnotations = history.StripAnnotations DetectAnnotations = history.DetectAnnotations FormatAnnotations = history.FormatAnnotations )
var ( NewIntentClassifier = intelligence.NewIntentClassifier FormatIntent = intelligence.FormatIntent NewCapabilityRegistry = intelligence.NewCapabilityRegistry NewLanguageRegistry = intelligence.NewLanguageRegistry FormatLanguages = intelligence.FormatLanguages NewToolSelector = intelligence.NewToolSelector FormatToolSelection = intelligence.FormatToolSelection NewSuggestionEngine = intelligence.NewSuggestionEngine FormatCommandSuggestions = intelligence.FormatCommandSuggestions )
var ( NewClipboardMonitor = io.NewClipboardMonitor ReadClipboard = io.ReadClipboard WriteClipboard = io.WriteClipboard DetectContentType = io.DetectContentType DetectLanguage = io.DetectLanguage NewAIWatcher = io.NewAIWatcher ScanFile = io.ScanFile ScanDirectory = io.ScanDirectory BuildPrompt = io.BuildPrompt RemoveComment = io.RemoveComment NewFileWatcher = io.NewFileWatcher WatchSingle = io.WatchSingle DefaultIgnorePatterns = io.DefaultIgnorePatterns MatchesPattern = io.MatchesPattern DedupEvents = io.DedupEvents FormatEvents = io.FormatEvents NewCronScheduler = io.NewCronScheduler ParseCron = io.ParseCron IsDue = io.IsDue NextRunTime = io.NextRunTime SummarizeClipboard = io.SummarizeClipboard FormatForContext = io.FormatForContext )
var ( ParseAndApplyMemoryOps = lifecycle.ParseAndApplyMemoryOps NewLimitTracker = lifecycle.NewLimitTracker DefaultLimits = lifecycle.DefaultLimits VibeLimits = lifecycle.VibeLimits ResearchLimits = lifecycle.ResearchLimits DefaultTimeoutConfig = lifecycle.DefaultTimeoutConfig WithTimeout = lifecycle.WithTimeout RemainingTime = lifecycle.RemainingTime TimeoutMessage = lifecycle.TimeoutMessage )
var ( NewKnowledgeBase = memory.NewKnowledgeBase NewExperienceStore = memory.NewExperienceStore NewMemoryConsolidator = memory.NewMemoryConsolidator )
var ( NewProfiler = observability.NewProfiler NewDebugRecorder = observability.NewDebugRecorder NewStructuredLogger = observability.NewStructuredLogger ParseLevel = observability.ParseLevel NewRotatingWriter = observability.NewRotatingWriter NewFeedbackCollector = observability.NewFeedbackCollector )
var ( NewExecutionPlanner = planning.NewExecutionPlanner NewTaskDecomposer = planning.NewTaskDecomposer NewPlanState = planning.NewPlanState DecomposePrompt = planning.DecomposePrompt ParseSubtasks = planning.ParseSubtasks WithPriority = planning.WithPriority WithBudget = planning.WithBudget WithDependencies = planning.WithDependencies WithTags = planning.WithTags NewGoalTracker = planning.NewGoalTracker NewTaskQueue = planning.NewTaskQueue ScanGitTasks = planning.ScanGitTasks ScanTODOs = planning.ScanTODOs ScanTestFailures = planning.ScanTestFailures FormatTasks = planning.FormatTasks NewActionManager = planning.NewActionManager Validate = planning.Validate BuildFormPrompt = planning.BuildFormPrompt FormatResponse = planning.FormatResponse )
var ( NewProjectAnalyzer = project.NewProjectAnalyzer DetectArchitecture = project.DetectArchitecture DetectPatterns = project.DetectPatterns GenerateOnboardingDoc = project.GenerateOnboardingDoc FormatAnalysis = project.FormatAnalysis NewProjectContext = project.NewProjectContext NewProjectSnapshotCache = project.NewProjectSnapshotCache NewImpactAnalyzer = project.NewImpactAnalyzer BuildImportGraph = project.BuildImportGraph FormatImpact = project.FormatImpact NewDependencyUpdater = project.NewDependencyUpdater ClassifyUpdate = project.ClassifyUpdate ParseSemver = project.ParseSemver FormatOutdated = project.FormatOutdated FormatPlan = project.FormatPlan NewMigrationPlanner = project.NewMigrationPlanner NewReleaseManager = project.NewReleaseManager ParseConventionalCommit = project.ParseConventionalCommit BumpVersion = project.BumpVersion GenerateChangelog = project.GenerateChangelog FormatReleaseNotes = project.FormatReleaseNotes UpdateVersionFile = project.UpdateVersionFile NewConventionSet = project.NewConventionSet FormatViolations = project.FormatViolations )
var ( NewReviewBot = review.NewReviewBot NewCritic = review.NewCritic NewSelfAssessor = review.NewSelfAssessor NewConsensusSampler = review.NewConsensusSampler NewQualityScorer = review.NewQualityScorer NewSolutionReviewer = review.NewSolutionReviewer DefaultWeights = review.DefaultWeights FormatSelfAssessment = review.FormatSelfAssessment FormatConsensus = review.FormatConsensus CompareApproaches = review.CompareApproaches FormatReview = review.FormatReview ShouldRetry = review.ShouldRetry FormatReport = review.FormatReport FormatInline = review.FormatInline FilterBySeverity = review.FilterBySeverity )
var ( NewHallucinationGuard = safety.NewHallucinationGuard BuildRejectionMessage = safety.BuildRejectionMessage FormatGroundingResult = safety.FormatGroundingResult NewOutputRedactor = safety.NewOutputRedactor NewPermissionMemory = safety.NewPermissionMemory NewPermissionEngine = safety.NewPermissionEngine NewProtectedPaths = safety.NewProtectedPaths NewRiskAssessor = safety.NewRiskAssessor GenerateMitigations = safety.GenerateMitigations FormatAssessment = safety.FormatAssessment ShouldProceed = safety.ShouldProceed PresetConfig = safety.PresetConfig ParseAutonomyLevel = safety.ParseAutonomyLevel ToolSummary = safety.ToolSummary ToolNeedsPermission = safety.ToolNeedsPermission )
var ( NewURLScraper = search.NewURLScraper NewIssueIndex = search.NewIssueIndex NewResearchAgent = search.NewResearchAgent ExtractHTML = search.ExtractHTML ExtractJSON = search.ExtractJSON ExtractMarkdown = search.ExtractMarkdown ExtractCode = search.ExtractCode SuggestResolution = search.SuggestResolution FormatIssueResults = search.FormatIssueResults BuildSearchContext = search.BuildSearchContext )
var ( NewResponseCache = streaming.NewResponseCache NewResponseFormatter = streaming.NewResponseFormatter NewStreamOptimizer = streaming.NewStreamOptimizer NewThinkingProtocol = streaming.NewThinkingProtocol NewSteeringQueue = streaming.NewSteeringQueue HashPrompt = streaming.HashPrompt ShouldCache = streaming.ShouldCache FixCodeFences = streaming.FixCodeFences RemoveFluff = streaming.RemoveFluff FixMarkdown = streaming.FixMarkdown )
var ( NewWorkflowEngine = workflow.NewWorkflowEngine NewWorkspaceState = workflow.NewWorkspaceState NewDiffReporter = workflow.NewDiffReporter NewTrajectoryInspector = workflow.NewTrajectoryInspector SubstituteVars = workflow.SubstituteVars EvalCondition = workflow.EvalCondition ValidateWorkflow = workflow.ValidateWorkflow BuiltinWorkflows = workflow.BuiltinWorkflows FormatAsMarkdown = workflow.FormatAsMarkdown FormatAsTerminal = workflow.FormatAsTerminal FormatForCommit = workflow.FormatForCommit CompareReports = workflow.CompareReports )
var BuiltinPersonas = []Persona{
{Code: "architect", Name: "Winston", Title: "System Architect", Icon: "🏗️", Style: "Measured, trade-offs over verdicts, boring technology for stability"},
{Code: "developer", Name: "Amelia", Title: "Senior Engineer", Icon: "💻", Style: "Precise, test-first, commit-message brevity, every statement citable"},
{Code: "reviewer", Name: "Marcus", Title: "Code Reviewer", Icon: "🔍", Style: "Adversarial, must find issues, no rubber-stamping"},
{Code: "pm", Name: "John", Title: "Product Manager", Icon: "📋", Style: "User value first, asks why, short questions sharp follow-ups"},
{Code: "security", Name: "Kai", Title: "Security Engineer", Icon: "🛡️", Style: "Paranoid, assumes breach, checks every input/output boundary"},
{Code: "devops", Name: "Riley", Title: "DevOps Engineer", Icon: "⚙️", Style: "Automation-first, infrastructure as code, observability obsessed"},
}
BuiltinPersonas are the default personas available in party mode.
var HintsFilenames = []string{".hawkhints", "AGENTS.md", ".hawk/AGENTS.md"}
HintsFilenames are the files hawk auto-loads for project context.
var ReviewCategories = []string{
"edge-cases",
"error-handling",
"security",
"performance",
"logic",
}
ReviewCategories are the areas the adversarial reviewer must check.
var ScaleBehaviors = map[TaskScale]ScaleBehavior{ ScalePatch: {Scale: ScalePatch, MaxTurns: 3, PlanRequired: false, AutoApprove: true, ScanScope: "file"}, ScaleMinor: {Scale: ScaleMinor, MaxTurns: 10, PlanRequired: false, AutoApprove: false, ScanScope: "module"}, ScaleMajor: {Scale: ScaleMajor, MaxTurns: 20, PlanRequired: true, AutoApprove: false, ScanScope: "module"}, ScaleEpic: {Scale: ScaleEpic, MaxTurns: 50, PlanRequired: true, AutoApprove: false, ScanScope: "repo"}, }
ScaleBehaviors maps each scale to its behavior config.
Functions ¶
func AdjustIndexToPreserveAPIInvariants ¶
func AdjustIndexToPreserveAPIInvariants(msgs []types.EyrieMessage, startIdx int) int
func AutoFixPrompt ¶
func AutoFixPrompt(path, content string, errors []ValidationError) string
AutoFixPrompt returns a prompt instructing the LLM to fix syntax errors in a file.
func BrainstormPrompt ¶
func BrainstormPrompt(phase BrainstormPhase, topic string, context string) string
BrainstormPrompt returns the facilitation prompt for each phase.
func BuildCompactPrompt ¶
func BuildCompactPrompt(variant CompactVariant) string
func BuildEditorPrompt ¶
func BuildEditorPrompt(plan *ArchitectPlan, step PlanStep) string
BuildEditorPrompt formats a focused prompt for the editor model to implement a specific step from the architect's plan.
func CheckpointPrompts ¶
func CheckpointPrompts(phase CheckpointPhase, files []string) string
CheckpointPrompts returns the system prompt for each checkpoint phase.
func ClassifyRisk ¶
func ClassifyRisk(changes []SemanticChange) string
ClassifyRisk determines the overall risk level based on a set of semantic changes.
func ClassifyTaskComplexity ¶
func CorrectCoursePrompt ¶
CorrectCoursePrompt generates a prompt to diagnose where things went wrong.
func CountTokens ¶
func CountTokensFast ¶
func DefaultCouncilModels ¶
func DefaultCouncilModels() []string
DefaultCouncilModels returns one catalog-backed default model per provider (dynamic).
func DefaultSoulPath ¶
func DefaultSoulPath() string
DefaultSoulPath returns the path to the soul file.
func DefaultValidateCmd ¶
DefaultValidateCmd detects the project type and returns the appropriate test command.
func DegradationTimeout ¶
DegradationTimeout returns a suggested timeout based on turn count.
func DetectGenerated ¶
DetectGenerated returns true if the path matches known generated/lock file patterns.
func DiffPrompts ¶
DiffPrompts shows what changed between two prompt versions line by line.
func DirectivePrompt ¶
DirectivePrompt formats a directive as a prompt for the LLM.
func DynamicMaxTokens ¶
func DynamicMaxTokens(messages []types.EyrieMessage, contextSize int, taskType string) int
func EditStrategyPrompt ¶
func EditStrategyPrompt(strategy EditStrategy) string
EditStrategyPrompt returns instructions for the LLM based on the selected strategy.
func EstimateDiffTokens ¶
EstimateDiffTokens provides a rough token count for a diff string. Uses the heuristic of ~4 characters per token (common for code).
func EstimateMessageTokens ¶
func EstimateMessageTokens(m types.EyrieMessage) int
func EstimateSavings ¶
func EstimateSavings(plan *ArchitectPlan, architectCost, editorCost float64) string
EstimateSavings calculates the estimated cost savings of using the architect/editor pipeline versus using the expensive model for everything. The architectCost and editorCost are per-million-token input prices.
func EstimateStringTokens ¶
EstimateStringTokens provides a rough token count for content using the ~4 chars per token heuristic. This avoids external dependencies and is suitable for budget estimation.
func EstimateTokens ¶
func EstimateTokens(msgs []types.EyrieMessage) int
func ExperimentPrompt ¶
func ExperimentPrompt(iteration int, validateCmd string, history []ExperimentResult, lastOutput string) string
ExperimentPrompt generates the prompt for the LLM to suggest the next change.
func ExtractPattern ¶
func FilterToolsForMode ¶
func FilterToolsForMode(mode SubAgentMode, available []string) []string
func FormatCompactSummary ¶
func FormatCompressedPR ¶
func FormatCompressedPR(pr *CompressedPR) string
FormatCompressed produces a human-readable summary of the compressed PR diff.
func FormatCostDisplay ¶
func FormatError ¶
func FormatError(enriched *EnrichedError) string
func FormatGateResults ¶
func FormatGateResults(results []GateResult) string
FormatGateResults renders gate results for display.
func FormatHealResult ¶
func FormatHealResult(result *HealResult) string
FormatResult produces a human-readable summary of a healing session.
func FormatPartyTurn ¶
FormatTurn renders a persona's contribution.
func FormatPattern ¶
func FormatPattern(p *PromptPattern) string
func FormatPrediction ¶
func FormatPrediction(pred *Prediction, model string) string
func FormatPrompt ¶
func FormatPrompt(base string, sections []PromptSection) string
FormatPrompt assembles the base prompt and included sections into a final string.
func FormatResults ¶
func FormatResults(results []BackgroundResult) string
func FormatSkill ¶
func FormatTeachingMoment ¶
FormatTeachingMoment wraps agent output with teaching context.
func GenerateAwaySummary ¶
func GenerateAwaySummary(ctx context.Context, session *Session, cfg AwaySummaryConfig, agentFn func(ctx context.Context, prompt string) (string, error)) (string, error)
GenerateAwaySummary creates a brief "while you were away" recap. Uses the cheapest model via cascade for cost efficiency.
func GenerateSummary ¶
func GenerateSummary(diff *SemanticDiff) string
GenerateSummary produces a human-readable summary of a semantic diff analysis.
func HasTextContent ¶
func HasTextContent(m types.EyrieMessage) bool
func ImplementFromSpecPrompt ¶
ImplementFromSpecPrompt generates the implementation prompt constrained by the spec.
func InitSoulPrompt ¶
func InitSoulPrompt() string
InitSoulPrompt returns a prompt to generate an initial soul.md.
func InvestigatePrompt ¶
func InvestigatePrompt(phase InvestigatePhase, context string) string
InvestigatePrompt returns the prompt for each investigation phase.
func IsCompactableTool ¶
func LearnPrompt ¶
LearnPrompt generates a prompt to extract lessons from a failed interaction.
func ListPersonas ¶
func ListPersonas() string
ListPersonas returns a formatted list of available personas.
func LoadCostHistory ¶
func MergeSynthesisPrompt ¶
MergeSynthesisPrompt generates a prompt to merge results from parallel agents.
func ModelPricing ¶
func NormalizeError ¶
func QuickDevClarifyPrompt ¶
QuickDevClarifyPrompt returns the prompt for intent clarification.
func QuickDevPresentPrompt ¶
func QuickDevPresentPrompt() string
QuickDevPresentPrompt returns the prompt for presenting results.
func QuickDevReviewPrompt ¶
QuickDevReviewPrompt returns the prompt for self-review after implementation.
func RebuildSessionTransport ¶
func RebuildSessionTransport(ctx context.Context, s *Session, useDeploymentRouting bool, legacyProvider string) error
RebuildSessionTransport rebuilds the LLM client from current settings and provider.json.
func ReflectPrompt ¶
ReflectPrompt generates a prompt for session self-assessment.
func ReviewPrompt ¶
ReviewPrompt generates the adversarial review system prompt.
func ShouldShowAwaySummary ¶
func ShouldShowAwaySummary(lastActivity time.Time, cfg AwaySummaryConfig) bool
ShouldShowAwaySummary checks if enough time has passed to warrant a summary.
func ShouldUseArchitect ¶
ShouldUseArchitect applies heuristics to decide whether the architect/editor pipeline should be used for this request. It returns true for complex tasks that benefit from planning.
func SpecGeneratePrompt ¶
SpecGeneratePrompt creates the prompt to generate a spec from user intent.
func SummarizeTrajectory ¶
func SummarizeTrajectory(messages []types.EyrieMessage) string
SummarizeTrajectory extracts a concise summary from a sequence of messages: what was attempted, what failed, key decisions made, and files touched.
func SynthesizeSubAgent ¶
func SynthesizeSubAgent(ctx context.Context, llm LLMClient, model string, conversationSoFar []types.EyrieMessage) (string, error)
SynthesizeSubAgent forces a final response from a sub-agent with tools disabled. Used when ShouldSynthesize() returns true. Returns the synthesized summary text.
The function builds messages from the conversation so far, appends a user message with SynthesisPrompt, and calls the provider with Tools=nil (disabled) to force a text-only response.
func TeachPromptAugment ¶
TeachPromptAugment returns a system prompt addition that instructs the agent to explain its reasoning at the given depth level.
func TruncateHunks ¶
TruncateHunks keeps the first and last hunks of a diff and drops the middle, inserting a note about omitted hunks.
func WarnIfExpensive ¶
func WarnIfExpensive(pred *Prediction, budgetUSD float64) string
Types ¶
type APICompactConfig ¶
type APICompactConfig = compact.APICompactConfig
func DefaultAPICompactConfig ¶
func DefaultAPICompactConfig() APICompactConfig
type APICompactStrategy ¶
type APICompactStrategy struct{}
func (*APICompactStrategy) Compact ¶
func (s *APICompactStrategy) Compact(ctx context.Context, sess *Session) (*CompactResult, error)
func (*APICompactStrategy) Name ¶
func (s *APICompactStrategy) Name() string
func (*APICompactStrategy) ShouldTrigger ¶
func (s *APICompactStrategy) ShouldTrigger(msgs []types.EyrieMessage, tokenCount, threshold int) bool
type ActionManager ¶
type ActionManager = planning.ActionManager
type ActionRequired ¶
type ActionRequired = planning.ActionRequired
type AdaptivePrompt ¶
type AdaptivePrompt struct {
// contains filtered or unexported fields
}
AdaptivePrompt adjusts system prompt sections based on user corrections. When the user says "don't do X" or "always do Y", the adaptive prompt system records it and injects it into future sessions.
func NewAdaptivePrompt ¶
func NewAdaptivePrompt() *AdaptivePrompt
NewAdaptivePrompt creates an adaptive prompt backed by ~/.hawk/adaptive_prompt.json.
func (*AdaptivePrompt) Count ¶
func (ap *AdaptivePrompt) Count() int
Count returns the number of active adjustments.
func (*AdaptivePrompt) FormatForPrompt ¶
func (ap *AdaptivePrompt) FormatForPrompt() string
FormatForPrompt returns active adjustments as system prompt rules.
func (*AdaptivePrompt) LearnFromFeedback ¶
func (ap *AdaptivePrompt) LearnFromFeedback(userMessage string)
LearnFromFeedback extracts prompt adjustments from user corrections.
type AdversarialReview ¶
type AdversarialReview struct {
Findings []ReviewFinding
}
AdversarialReview holds the review configuration and results.
func (*AdversarialReview) FormatFindings ¶
func (ar *AdversarialReview) FormatFindings() string
FormatFindings renders findings as a readable report.
type AgentIntelligence ¶
AgentIntelligence provides smart routing, auto-spawning, and synthesis for agents.
func NewAgentIntelligence ¶
func NewAgentIntelligence() *AgentIntelligence
NewAgentIntelligence creates the intelligence layer.
func (*AgentIntelligence) AnalyzeForParallelism ¶
func (ai *AgentIntelligence) AnalyzeForParallelism(prompt string) SpawnDecision
AnalyzeForParallelism determines if a task should be split into parallel subtasks.
func (*AgentIntelligence) ExecuteWithIntelligence ¶
func (ai *AgentIntelligence) ExecuteWithIntelligence(ctx context.Context, prompt string, execFn func(context.Context, string, SubAgentMode) (string, error)) (string, error)
ExecuteWithIntelligence runs a task with smart agent routing.
func (*AgentIntelligence) SelectMode ¶
func (ai *AgentIntelligence) SelectMode(subtask string) SubAgentMode
SelectMode picks the optimal agent mode for a subtask.
type AgentLogger ¶
type AgentLogger = observability.AgentLogger
type AliasSuggestion ¶
type AliasSuggestion = history.AliasSuggestion
type Allocation ¶
type Allocation struct {
Name string
MinTokens int
MaxTokens int // 0 or negative means unlimited
CurrentTokens int
Priority int // 1 = highest priority
Flexible bool // can tokens be stolen from this allocation?
Usage float64 // 0.0 to 1.0, fraction of CurrentTokens actually used
}
Allocation represents a single named budget category with bounds and priority.
type Annotation ¶
type Annotation = history.Annotation
type AnnotationManager ¶
type AnnotationManager = history.AnnotationManager
type Architect ¶
type Architect struct {
Config ArchitectConfig
ChatFn func(ctx context.Context, model string, messages []ArchitectMessage) (string, error)
}
Architect coordinates the two-model pipeline: a cheap model plans, then an expensive model executes each step.
type ArchitectConfig ¶
type ArchitectConfig struct {
ArchitectModel string // cheap/fast model for planning, e.g., "haiku"
EditorModel string // expensive/precise model for edits, e.g., "sonnet"
PlanTokenBudget int // max tokens for architect's plan, default 4096
Enabled bool
}
ArchitectConfig configures the two-model architect/editor pipeline. A cheap model (architect) plans the changes, then an expensive model (editor) executes them precisely. This is a cost-saving pattern: the architect uses fewer tokens to plan, allowing the editor to focus on precise implementation.
type ArchitectMessage ¶
Message is a lightweight chat message used by the architect pipeline. This avoids coupling to external message types from eyrie.
type ArchitectPlan ¶
type ArchitectPlan struct {
Goal string
Steps []PlanStep
FilesToModify []string
EstimatedComplexity string // "trivial", "simple", "moderate", "complex"
RawPlan string
}
ArchitectPlan represents the structured output from the architect model.
func ParsePlan ¶
func ParsePlan(response string) (*ArchitectPlan, error)
ParsePlan extracts GOAL, COMPLEXITY, FILES, and STEPS from the architect's response. It handles variations in formatting gracefully.
type Assessment ¶
type Assessment = review.Assessment
type Assumption ¶
type Assumption struct {
Text string
Status AssumptionStatus
Proof string // evidence for/against
}
Assumption is a single assumption the agent is making.
type AssumptionStatus ¶
type AssumptionStatus int
AssumptionStatus tracks whether an assumption has been verified.
const ( AssumptionUnverified AssumptionStatus = iota AssumptionConfirmed AssumptionFailed )
type AssumptionTracker ¶
type AssumptionTracker struct {
Assumptions []Assumption
// contains filtered or unexported fields
}
AssumptionTracker logs and verifies agent assumptions.
func NewAssumptionTracker ¶
func NewAssumptionTracker() *AssumptionTracker
NewAssumptionTracker creates a tracker.
func (*AssumptionTracker) Add ¶
func (at *AssumptionTracker) Add(text string)
Add logs a new assumption.
func (*AssumptionTracker) Failed ¶
func (at *AssumptionTracker) Failed() []Assumption
Failed returns all assumptions that were proven wrong.
func (*AssumptionTracker) Reset ¶
func (at *AssumptionTracker) Reset()
Reset clears all assumptions (e.g., for new task).
func (*AssumptionTracker) Summary ¶
func (at *AssumptionTracker) Summary() string
Summary returns a formatted summary of all assumptions.
func (*AssumptionTracker) VerifyCommandSucceeds ¶
func (at *AssumptionTracker) VerifyCommandSucceeds(text, cmd string)
VerifyCommandSucceeds checks if a command-based assumption holds.
func (*AssumptionTracker) VerifyFileExists ¶
func (at *AssumptionTracker) VerifyFileExists(text, path string)
VerifyFileExists checks if a file assumption is correct.
type AutoCommitter ¶
AutoCommitter automatically commits changes after every successful edit. Never lose work — every change is a git commit you can undo.
func NewAutoCommitter ¶
func NewAutoCommitter(repoDir string) *AutoCommitter
NewAutoCommitter creates an auto-committer for the given repo.
func (*AutoCommitter) CommitIfChanged ¶
func (ac *AutoCommitter) CommitIfChanged(description string) error
CommitIfChanged stages and commits any uncommitted changes with a smart message.
func (*AutoCommitter) Undo ¶
func (ac *AutoCommitter) Undo() error
Undo reverts the last auto-commit.
type AutoCompactor ¶
type AutoCompactor struct {
// contains filtered or unexported fields
}
AutoCompactor orchestrates compaction with circuit breaker protection.
func NewAutoCompactor ¶
func NewAutoCompactor(config CompactConfig) *AutoCompactor
NewAutoCompactor creates an auto-compactor with the given config.
func (*AutoCompactor) AutoCompactIfNeeded ¶
AutoCompactIfNeeded runs compaction if threshold is met. Returns the strategy name used and whether compaction occurred.
func (*AutoCompactor) GetAutoCompactThreshold ¶
func (ac *AutoCompactor) GetAutoCompactThreshold() int
GetAutoCompactThreshold returns the token count at which auto-compaction triggers.
func (*AutoCompactor) LastStrategy ¶
func (ac *AutoCompactor) LastStrategy() string
LastStrategy returns the name of the last strategy used.
func (*AutoCompactor) ResetFailures ¶
func (ac *AutoCompactor) ResetFailures()
ResetFailures resets the circuit breaker failure count.
func (*AutoCompactor) RunCompaction ¶
RunCompaction selects and executes the best compaction strategy.
func (*AutoCompactor) ShouldAutoCompact ¶
func (ac *AutoCompactor) ShouldAutoCompact(sess *Session) bool
ShouldAutoCompact determines if compaction is needed based on current state.
type AutonomyConfig ¶
type AutonomyConfig = safety.AutonomyConfig
type AutonomyLevel ¶
type AutonomyLevel = safety.AutonomyLevel
type AwaySummaryConfig ¶
type AwaySummaryConfig struct {
Enabled bool
IdleThreshold time.Duration // minimum idle time to trigger summary
MaxMessages int // number of recent messages to include in context
}
AwaySummaryConfig controls away summary behavior.
func DefaultAwaySummaryConfig ¶
func DefaultAwaySummaryConfig() AwaySummaryConfig
DefaultAwaySummaryConfig returns sensible defaults.
type BackgroundAgentPool ¶
type BackgroundAgentPool = agent.BackgroundAgentPool
func NewBackgroundAgentPool ¶
func NewBackgroundAgentPool() *BackgroundAgentPool
type BackgroundResult ¶
type BackgroundResult = agent.BackgroundResult
type BackgroundRunner ¶
type BackgroundRunner struct {
// contains filtered or unexported fields
}
BackgroundRunner manages async subagent tasks that run while the user keeps chatting.
func NewBackgroundRunner ¶
func NewBackgroundRunner() *BackgroundRunner
NewBackgroundRunner creates a new background task runner.
func (*BackgroundRunner) Collect ¶
func (br *BackgroundRunner) Collect(id string) *BackgroundTask
Collect returns and removes a completed task's result. Returns nil if still running.
func (*BackgroundRunner) Delegate ¶
func (br *BackgroundRunner) Delegate(ctx context.Context, prompt string, execFn func(context.Context, string) (string, error)) string
Delegate starts a background task. Returns the task ID immediately.
func (*BackgroundRunner) ListActive ¶
func (br *BackgroundRunner) ListActive() []*BackgroundTask
ListActive returns all currently running tasks.
func (*BackgroundRunner) PendingCount ¶
func (br *BackgroundRunner) PendingCount() int
PendingCount returns the number of tasks still running.
func (*BackgroundRunner) Status ¶
func (br *BackgroundRunner) Status(id string) *BackgroundTask
Status returns the current state of a background task.
type BackgroundTask ¶
type BackgroundTask struct {
ID string
Prompt string
Status string // "running", "done", "failed"
Result string
Error string
StartedAt time.Time
DoneAt time.Time
}
BackgroundTask represents an async subagent task running in the background.
type BacktrackEngine ¶
type BacktrackEngine = control.BacktrackEngine
type Belief ¶
type Belief struct {
ID string
Category string // "file_purpose", "function_behavior", "dependency", "architecture"
Subject string // file or symbol name
Content string // what we believe about it
Confidence float64 // 0-1
DiscoveredAt int // turn index when discovered
LastVerified int // turn index when last confirmed
}
Belief represents a single piece of discovered knowledge about the codebase.
type BeliefState ¶
type BeliefState struct {
// contains filtered or unexported fields
}
BeliefState tracks what the agent has discovered about the codebase to prevent forgetting across long conversations. Beliefs are keyed by a generated ID.
func NewBeliefState ¶
func NewBeliefState() *BeliefState
NewBeliefState creates an empty belief state.
func (*BeliefState) FormatForPrompt ¶
func (bs *BeliefState) FormatForPrompt() string
FormatForPrompt returns a formatted string summarizing all current beliefs, suitable for injection into the system prompt.
func (*BeliefState) Get ¶
func (bs *BeliefState) Get(subject string) []*Belief
Get returns all beliefs about a given subject.
func (*BeliefState) Invalidate ¶
func (bs *BeliefState) Invalidate(subject string)
Invalidate marks all beliefs about a subject as stale by halving their confidence. This should be called when a file is modified, since our beliefs about it may no longer hold.
func (*BeliefState) Prune ¶
func (bs *BeliefState) Prune(currentTurn int)
Prune removes beliefs that have not been verified in the last 20 turns, keeping the belief state manageable in long conversations.
func (*BeliefState) Record ¶
func (bs *BeliefState) Record(category, subject, content string, turn int)
Record adds or updates a belief. If a belief with the same category and subject already exists, it is updated with the new content and turn index.
func (*BeliefState) Size ¶
func (bs *BeliefState) Size() int
Size returns the number of active beliefs.
type BrainstormPhase ¶
type BrainstormPhase int
BrainstormPhase represents a step in guided brainstorming.
const ( BrainstormSetup BrainstormPhase = iota // define the problem space BrainstormDiverge // generate ideas (quantity over quality) BrainstormOrganize // cluster and categorize BrainstormEvaluate // score and prioritize BrainstormConverge // select and refine top ideas )
func (BrainstormPhase) String ¶
func (p BrainstormPhase) String() string
type BrainstormSession ¶
type BrainstormSession struct {
Topic string
Phase BrainstormPhase
Ideas []string
Clusters map[string][]string
TopPicks []string
}
BrainstormSession tracks a brainstorming session.
func NewBrainstormSession ¶
func NewBrainstormSession(topic string) *BrainstormSession
NewBrainstormSession starts a new brainstorming session.
type BudgetAlert ¶
type BudgetAlert = token.BudgetAlert
type BudgetAllocator ¶
type BudgetAllocator struct {
TotalBudget int
OutputReserve int
Allocations map[string]*Allocation
Priority []string // allocation names sorted by priority (1=highest first)
// contains filtered or unexported fields
}
BudgetAllocator dynamically distributes context window space across named allocations. It respects per-allocation min/max bounds, priority ordering, and supports runtime rebalancing when usage patterns shift.
func NewBudgetAllocator ¶
func NewBudgetAllocator(totalBudget, outputReserve int) *BudgetAllocator
NewBudgetAllocator creates a new allocator with the given total budget and output reserve. The distributable budget is TotalBudget - OutputReserve.
func (*BudgetAllocator) Allocate ¶
func (ba *BudgetAllocator) Allocate() map[string]int
Allocate distributes the available budget (TotalBudget - OutputReserve) across all registered allocations. It first satisfies minimums, then distributes remaining tokens by priority order (lowest number = highest priority), respecting max caps. Any tokens that cannot be assigned (because all allocations hit their max) remain unallocated. Returns a map of allocation name to assigned token count.
func (*BudgetAllocator) DefaultAllocations ¶
func (ba *BudgetAllocator) DefaultAllocations()
DefaultAllocations registers the standard allocation categories for a coding agent.
func (*BudgetAllocator) FormatBudget ¶
func (ba *BudgetAllocator) FormatBudget() string
FormatBudget returns a formatted table showing all allocations, their bounds, current assignment, usage, and priority.
func (*BudgetAllocator) GetAvailable ¶
func (ba *BudgetAllocator) GetAvailable() int
GetAvailable returns the number of tokens not currently assigned to any allocation.
func (*BudgetAllocator) Rebalance ¶
func (ba *BudgetAllocator) Rebalance()
Rebalance shrinks allocations with low usage and grows allocations that are at capacity. An allocation is considered underutilized if its Usage < 0.5 and it has more than its minimum. An allocation needs growth if its Usage >= 0.9.
func (*BudgetAllocator) Register ¶
func (ba *BudgetAllocator) Register(name string, min, max, priority int, flexible bool)
Register adds a new allocation category to the budget allocator. Priority 1 is the highest priority. If maxTokens <= 0, it is treated as unlimited.
func (*BudgetAllocator) Release ¶
func (ba *BudgetAllocator) Release(name string, amount int)
Release returns tokens from an allocation back to the pool (reduces CurrentTokens). It will not reduce below the allocation's minimum.
func (*BudgetAllocator) RequestMore ¶
func (ba *BudgetAllocator) RequestMore(name string, needed int) int
RequestMore attempts to acquire additional tokens for the named allocation by stealing from lower-priority flexible allocations. Returns the number of tokens actually granted (may be less than needed).
func (*BudgetAllocator) SuggestCompaction ¶
func (ba *BudgetAllocator) SuggestCompaction() string
SuggestCompaction analyzes current allocations and suggests which categories should be compacted to free space, based on usage and priority.
func (*BudgetAllocator) WouldExceed ¶
func (ba *BudgetAllocator) WouldExceed(name string, additional int) bool
WouldExceed returns true if adding 'additional' tokens to the named allocation would cause it to exceed its maximum.
type CacheEntry ¶
type CacheEntry = streaming.CacheEntry
type CacheStats ¶
type CacheStats = streaming.CacheStats
type Capability ¶
type Capability = intelligence.Capability
type CapabilityRegistry ¶
type CapabilityRegistry = intelligence.CapabilityRegistry
type ChangeEntry ¶
type ChangeEntry = project.ChangeEntry
type ChangeStats ¶
type ChangeStats = diff.ChangeStats
type ChatClient ¶
type ChatClient interface {
Chat(ctx context.Context, messages []types.EyrieMessage, opts types.ChatOptions) (*types.EyrieResponse, error)
StreamChatContinue(ctx context.Context, messages []types.EyrieMessage, opts types.ChatOptions, cfg types.ContinuationConfig) (*types.StreamResult, error)
SetAPIKey(provider, apiKey string)
}
ChatClient abstracts the LLM client methods used by Session. The production implementation is *types.EyrieClient; tests can inject a mock.
func BuildChatClient ¶
func BuildChatClient(ctx context.Context, useDeploymentRouting bool, legacyProvider string) (ChatClient, string, bool)
BuildChatClient returns an LLM client and whether deployment routing is active.
func NewMockClientForTest ¶
func NewMockClientForTest() ChatClient
NewMockClientForTest creates a mock ChatClient that returns canned text responses.
func NewProviderChatClient ¶
func NewProviderChatClient(p types.Provider) ChatClient
NewProviderChatClient wraps a catalog-backed provider (e.g. DeploymentRouter) for Session use.
type CheckpointPhase ¶
type CheckpointPhase int
CheckpointPhase represents a step in the pre-commit checkpoint review.
const ( CheckpointOrientation CheckpointPhase = iota // what changed and why CheckpointWalkthrough // file-by-file CheckpointDetail // edge cases, error paths CheckpointTesting // test adequacy CheckpointWrapup // ready to commit? )
type ChunkedResponse ¶
ChunkedResponse holds a paginated response.
func (*ChunkedResponse) FormatPage ¶
func (cr *ChunkedResponse) FormatPage(page int) string
FormatPage returns a chunk with page header/footer for the agent.
type ClassifiedInput ¶
type ClassifiedInput = intelligence.ClassifiedInput
type ClipboardBridge ¶
type ClipboardBridge = io.ClipboardBridge
type ClipboardMonitor ¶
type ClipboardMonitor = io.ClipboardMonitor
type CodingSoul ¶
type CodingSoul struct {
Style string // communication style
Preferences string // coding preferences
Path string
}
CodingSoul defines the persistent coding personality and style preferences. Loaded from .hawk/soul.md — your coding DNA that hawk follows across all sessions.
func LoadCodingSoul ¶
func LoadCodingSoul() *CodingSoul
LoadCodingSoul reads the soul file. Returns empty soul if not found.
func (*CodingSoul) ForPrompt ¶
func (s *CodingSoul) ForPrompt() string
ForPrompt formats the soul as system prompt context.
type CommandFrequency ¶
type CommandFrequency = history.CommandFrequency
type CommandHistory ¶
type CommandHistory = history.CommandHistory
type CommandRecord ¶
type CommandRecord = history.CommandRecord
type CommandSuggestion ¶
type CommandSuggestion = intelligence.CommandSuggestion
type Comment ¶
type Comment = review.ReviewComment
type CompactConfig ¶
type CompactConfig = compact.CompactConfig
func DefaultCompactConfig ¶
func DefaultCompactConfig() CompactConfig
type CompactResult ¶
type CompactResult = compact.CompactResult
type CompactStrategy ¶
type CompactStrategy interface {
Name() string
ShouldTrigger(msgs []types.EyrieMessage, tokenCount, threshold int) bool
Compact(ctx context.Context, s *Session) (*CompactResult, error)
}
type CompactVariant ¶
type CompactVariant = compact.CompactVariant
type CompactionTrigger ¶
type CompactionTrigger = compact.CompactionTrigger
func NewCompactionTrigger ¶
func NewCompactionTrigger(windowSize int) *CompactionTrigger
type CompressMessage ¶
type CompressMessage = session.CompressMessage
type CompressStrategy ¶
type CompressStrategy = session.CompressStrategy
type CompressedBlock ¶
type CompressedBlock = session.CompressedBlock
type CompressedFile ¶
type CompressedFile struct {
Path string
Diff string
Tokens int
Priority float64
Language string
Truncated bool
}
CompressedFile represents a single file's diff after compression.
type CompressedPR ¶
type CompressedPR struct {
Files []CompressedFile
TotalTokens int
OverflowFiles []string
Summary string
}
CompressedPR holds the result of compressing a full PR diff into a token-budget-aware representation.
type CompressionResult ¶
type CompressionResult = session.CompressionResult
type ConsensusResult ¶
type ConsensusResult = review.ConsensusResult
type ConsensusSampler ¶
type ConsensusSampler = review.ConsensusSampler
type ConsolidatedMemory ¶
type ConsolidatedMemory = memory.ConsolidatedMemory
type ConsolidatorStats ¶
type ConsolidatorStats = memory.ConsolidatorStats
type Convention ¶
type Convention = project.Convention
type ConventionSet ¶
type ConventionSet = project.ConventionSet
type ConversationSummarizer ¶
type ConversationSummarizer = history.ConversationSummarizer
type CoreLoop ¶
type CoreLoop struct {
Client ChatClient
Registry *tool.Registry
Messages []types.EyrieMessage
Provider string
Model string
APIKeys map[string]string
System string
Log *logger.Logger
MaxTurns int
}
CoreLoop encapsulates the agent loop: sending messages to the LLM, executing tool calls, and accumulating the conversation history.
type CostOptimizer ¶
type CostOptimizer = cost.CostOptimizer
func NewCostOptimizer ¶
func NewCostOptimizer() *CostOptimizer
type CostTracker ¶
type CostTracker = cost.CostTracker
func NewCostTracker ¶
func NewCostTracker(sessionID string) *CostTracker
type CostTrackerInterface ¶
type CostTrackerInterface = lifecycle.CostTrackerInterface
type CouncilConfig ¶
type CouncilConfig struct {
Models []string // council member model names
Chairman string // chairman model (synthesizer)
}
CouncilConfig controls the Karpathy LLM Council pattern.
type CouncilRanking ¶
CouncilRanking holds one model's ranking of responses.
type CouncilResponse ¶
CouncilResponse holds one model's contribution.
type CouncilResult ¶
type CouncilResult struct {
Responses []CouncilResponse
Rankings []CouncilRanking
Synthesis string
}
CouncilResult holds the full council output.
func RunCouncil ¶
func RunCouncil(ctx context.Context, query string, cfg CouncilConfig, sess *Session) (*CouncilResult, error)
RunCouncil implements Karpathy's 3-stage LLM Council pattern:
- Send query to all models in parallel, collect responses
- Anonymize responses, send ranking prompt to all models in parallel
- Send all responses + rankings to chairman for synthesis
type Counter ¶
type Counter = observability.Counter
type CronScheduler ¶
type CronScheduler = io.CronScheduler
type CrossSessionLearner ¶
type CrossSessionLearner = session.CrossSessionLearner
func NewCrossSessionLearner ¶
func NewCrossSessionLearner(dir string) *CrossSessionLearner
type DebugRecorder ¶
type DebugRecorder = observability.DebugRecorder
type DebugSession ¶
type DebugSession = observability.DebugSession
type DebugStep ¶
type DebugStep = observability.DebugStep
type DecisionPoint ¶
type DecisionPoint = control.DecisionPoint
type DegradationDetector ¶
type DegradationDetector struct {
// contains filtered or unexported fields
}
DegradationDetector monitors agent quality over turns and triggers recovery.
func NewDegradationDetector ¶
func NewDegradationDetector(maxTurns int) *DegradationDetector
NewDegradationDetector creates a detector with default thresholds.
func (*DegradationDetector) IsDegraded ¶
func (dd *DegradationDetector) IsDegraded() bool
IsDegraded returns whether quality has dropped.
func (*DegradationDetector) RecordTurn ¶
func (dd *DegradationDetector) RecordTurn(toolName string, success bool)
RecordTurn logs a turn and checks for degradation.
func (*DegradationDetector) RecoveryAction ¶
func (dd *DegradationDetector) RecoveryAction() string
RecoveryAction returns what to do when degradation is detected.
func (*DegradationDetector) Reset ¶
func (dd *DegradationDetector) Reset()
Reset clears the detector state (e.g., after recovery or new task).
func (*DegradationDetector) Signal ¶
func (dd *DegradationDetector) Signal() DegradationSignal
Signal returns the type of degradation detected.
func (*DegradationDetector) Stats ¶
func (dd *DegradationDetector) Stats() (turns, errors, consecutive int)
Stats returns current metrics.
type DegradationSignal ¶
type DegradationSignal int
DegradationSignal is a type of quality drop indicator.
const ( SignalLooping DegradationSignal = iota // repeated identical tool calls SignalErrorSpike // 3+ consecutive failures SignalContextDrift // referencing non-existent files SignalNoProgress // many turns without meaningful change )
type Dependency ¶
type Dependency = project.Dependency
type DependencyUpdater ¶
type DependencyUpdater = project.DependencyUpdater
type Diff3Conflict ¶
type Diff3Conflict = diff.Diff3Conflict
type Diff3Region ¶
type Diff3Region = diff.Diff3Region
type Diff3Result ¶
type Diff3Result = diff.Diff3Result
type Diff3Stats ¶
type Diff3Stats = diff.Diff3Stats
type DiffPreview ¶
type DiffPreview = diff.DiffPreview
type DiffReporter ¶
type DiffReporter = workflow.DiffReporter
type DiffSandbox ¶
type DiffSandbox = diff.DiffSandbox
type DiffSummarizer ¶
type DiffSummarizer = diff.DiffSummarizer
type DiffSummary ¶
type DiffSummary = diff.DiffSummary
type Directive ¶
Directive is a parsed hawk: comment from source code.
func ScanDirectives ¶
ScanDirectives finds all `// hawk: <command>` comments in source files.
type DistillExample ¶
type DistillExample = history.DistillExample
type DistillStats ¶
type DistillStats = history.DistillStats
type DistillationPipeline ¶
type DistillationPipeline = history.DistillationPipeline
type EditStrategy ¶
type EditStrategy int
EditStrategy selects the best edit format based on the task.
const ( EditWholeFile EditStrategy = iota // replace entire file (small files <100 lines) EditSearchReplace // precise search-and-replace blocks EditDiff // unified diff format EditAppend // append to end of file EditInsert // insert at specific location )
func SelectEditStrategy ¶
func SelectEditStrategy(fileLines int, changeDescription string) EditStrategy
SelectEditStrategy picks the optimal edit approach based on file size and change type.
type EfficientPrompter ¶
type EfficientPrompter struct {
Strategies []PromptOpt
Stats EfficientStats
// contains filtered or unexported fields
}
EfficientPrompter implements a token-efficient prompting system that minimizes token usage while maintaining output quality through various text optimization strategies.
func NewEfficientPrompter ¶
func NewEfficientPrompter() *EfficientPrompter
NewEfficientPrompter creates a new EfficientPrompter with all default strategies enabled.
func (*EfficientPrompter) DisableStrategy ¶
func (ep *EfficientPrompter) DisableStrategy(name string)
DisableStrategy disables the named strategy.
func (*EfficientPrompter) EnableStrategy ¶
func (ep *EfficientPrompter) EnableStrategy(name string)
EnableStrategy enables the named strategy.
func (*EfficientPrompter) EstimateSavings ¶
func (ep *EfficientPrompter) EstimateSavings(prompt string) int
EstimateSavings returns the estimated number of tokens that would be saved by optimizing the given prompt, without actually modifying stats.
func (*EfficientPrompter) FormatEfficientStats ¶
func (ep *EfficientPrompter) FormatEfficientStats() string
FormatEfficientStats returns a human-readable summary of token savings.
func (*EfficientPrompter) Optimize ¶
func (ep *EfficientPrompter) Optimize(prompt string) *OptimizedResult
Optimize applies all enabled strategies to the given prompt and returns an OptimizedResult.
func (*EfficientPrompter) OptimizeMessages ¶
func (ep *EfficientPrompter) OptimizeMessages(messages []PromptMsg) []PromptMsg
OptimizeMessages compresses older messages more aggressively while keeping recent messages mostly intact.
func (*EfficientPrompter) OptimizeOutput ¶
func (ep *EfficientPrompter) OptimizeOutput(output string) string
OptimizeOutput removes noise from tool outputs and collapses repeated lines.
type EfficientStats ¶
type EfficientStats struct {
OriginalTokens int
OptimizedTokens int
TotalSavings int
CallCount int
}
EfficientStats tracks cumulative token savings across all optimization calls.
type Engine ¶
type Engine = workflow.WorkflowEngine
type EnrichedError ¶
type EnrichedError = errs.EnrichedError
type ErrorContext ¶
type ErrorContext = errs.ErrorContext
func NewErrorContext ¶
func NewErrorContext() *ErrorContext
type ErrorGroup ¶
type ErrorGroup = errs.ErrorGroup
type ErrorGrouper ¶
type ErrorGrouper = errs.ErrorGrouper
func NewErrorGrouper ¶
func NewErrorGrouper() *ErrorGrouper
type ErrorInstance ¶
type ErrorInstance = errs.ErrorInstance
type ErrorLearner ¶
type ErrorLearner = errs.ErrorLearner
func NewErrorLearner ¶
func NewErrorLearner() *ErrorLearner
type ErrorLearnerStats ¶
type ErrorLearnerStats = errs.ErrorLearnerStats
type ErrorPattern ¶
type ErrorPattern = errs.ErrorPattern
type ErrorPatternDB ¶
type ErrorPatternDB = errs.ErrorPatternDB
func NewErrorPatternDB ¶
func NewErrorPatternDB() *ErrorPatternDB
type ErrorRecovery ¶
type ErrorRecovery = errs.ErrorRecovery
func NewErrorRecovery ¶
func NewErrorRecovery() *ErrorRecovery
type Event ¶
type Event struct {
Type EventType
Payload interface{}
}
Event is a typed event in the system.
type EventBus ¶
type EventBus struct {
// contains filtered or unexported fields
}
EventBus is a lightweight pub/sub system for decoupling hawk components.
func (*EventBus) Unsubscribe ¶
Unsubscribe removes a channel from receiving events.
type EventType ¶
type EventType string
EventType identifies the kind of event.
const ( EventFileChanged EventType = "file.changed" EventToolStarted EventType = "tool.started" EventToolCompleted EventType = "tool.completed" EventToolFailed EventType = "tool.failed" EventSessionStart EventType = "session.start" EventSessionEnd EventType = "session.end" EventStreamChunk EventType = "stream.chunk" EventStreamDone EventType = "stream.done" EventPermission EventType = "permission.ask" EventError EventType = "error" )
type EvolvingMemoryAdapter ¶
type EvolvingMemoryAdapter = lifecycle.EvolvingMemoryAdapter
type EvolvingMemoryInterface ¶
type EvolvingMemoryInterface = lifecycle.EvolvingMemoryInterface
type ExecutionPlan ¶
type ExecutionPlan = planning.ExecutionPlan
type ExecutionPlanner ¶
type ExecutionPlanner = planning.ExecutionPlanner
type ExecutionStep ¶
type ExecutionStep = planning.ExecutionStep
type Experience ¶
type Experience = memory.Experience
type ExperienceStats ¶
type ExperienceStats = memory.ExperienceStats
type ExperienceStore ¶
type ExperienceStore = memory.ExperienceStore
type ExperimentLoop ¶
type ExperimentLoop struct {
WorkDir string
MaxIters int
Timeout time.Duration // per-iteration timeout
ValidateCmd string // command to validate (e.g. "go test ./...")
Results []ExperimentResult
}
ExperimentLoop runs autonomous iterations: modify → validate → keep/discard.
func NewExperimentLoop ¶
func NewExperimentLoop(workDir, validateCmd string, maxIters int) *ExperimentLoop
NewExperimentLoop creates a loop with sensible defaults for coding.
func (*ExperimentLoop) Run ¶
func (el *ExperimentLoop) Run(ctx context.Context, modifyFn func(ctx context.Context, iteration int, history []ExperimentResult) (change string, err error)) error
Run executes the autonomous loop. For each iteration: 1. Call modifyFn to get a code change (via LLM) 2. Apply the change 3. Run validation 4. If passes → keep. If fails → revert. 5. Repeat until maxIters or all passing.
func (*ExperimentLoop) Summary ¶
func (el *ExperimentLoop) Summary() string
Summary returns a formatted summary of all experiments.
type ExperimentResult ¶
type ExperimentResult struct {
ID int
Change string // description of what was tried
Passed bool
Metric string // validation output
Duration time.Duration
Kept bool
}
ExperimentResult holds the outcome of a single autonomous experiment.
type FailureLayer ¶
type FailureLayer int
FailureLayer identifies where a problem originated.
const ( LayerIntent FailureLayer = iota // user's request was unclear/wrong LayerSpec // spec/plan was flawed LayerImplementation // code is wrong but spec was right )
func (FailureLayer) String ¶
func (l FailureLayer) String() string
type FailurePattern ¶
type FailurePattern = session.FailurePattern
type Feedback ¶
type Feedback = observability.Feedback
type FeedbackCollector ¶
type FeedbackCollector = observability.FeedbackCollector
type FewShotExample ¶
type FewShotExample = scaffold.FewShotExample
type FewShotStore ¶
type FewShotStore = scaffold.FewShotStore
func NewFewShotStore ¶
func NewFewShotStore() *FewShotStore
type FieldSpec ¶
type FieldSpec = validation.FieldSpec
type FileChange ¶
type FileChange = diff.FileChange
type FileDiffReport ¶
type FileDiffReport = workflow.FileDiffReport
type FileFix ¶
type FileFix struct {
File string
Line int
Action string // "replace", "insert", "delete"
OldContent string
NewContent string
}
FileFix represents a single structured fix to apply to a file.
type FileMentionDetector ¶
type FileMentionDetector = history.FileMentionDetector
type FileSnapshot ¶
type FileSnapshot struct {
Path string
OriginalContent []byte
ModifiedContent []byte
OriginalMode os.FileMode
WasNew bool
}
FileSnapshot captures the state of a file before and after modification.
type FileSummary ¶
type FileSummary = diff.FileSummary
type FileTracker ¶
type FileTracker = compact.FileTracker
func NewFileTracker ¶
func NewFileTracker() *FileTracker
type FileWatcher ¶
type FileWatcher = io.FileWatcher
type FormResponse ¶
type FormResponse = planning.FormResponse
type FormatRule ¶
type FormatRule = streaming.FormatRule
type FormattedResponse ¶
type FormattedResponse = streaming.FormattedResponse
type GateResult ¶
GateResult is the outcome of a quality gate check.
func RunQualityGates ¶
func RunQualityGates(gates []QualityGate) ([]GateResult, bool)
QualityGates runs all gates in sequence. Stops at first failure.
type GenCheck ¶
type GenCheck = validation.GenCheck
type GenIssue ¶
type GenIssue = validation.GenIssue
type GenValidation ¶
type GenValidation = validation.GenValidation
type GenValidator ¶
type GenValidator = validation.GenValidator
func NewGenValidator ¶
func NewGenValidator() *GenValidator
type GoalOption ¶
type GoalOption = planning.GoalOption
type GoalStatus ¶
type GoalStatus = planning.GoalStatus
type GoalTracker ¶
type GoalTracker = planning.GoalTracker
type GroundingResult ¶
type GroundingResult = safety.GroundingResult
type HallucinationGuard ¶
type HallucinationGuard = safety.HallucinationGuard
type HeadTailWindow ¶
type HeadTailWindow = history.HeadTailWindow
type HealAttempt ¶
type HealAttempt struct {
Attempt int
Script string
ExitCode int
Output string
Error string
Fix string
Duration time.Duration
Success bool
}
HealAttempt records a single attempt within the healing loop.
type HealResult ¶
type HealResult struct {
Attempts []HealAttempt
FinalSuccess bool
TotalDuration time.Duration
FixesApplied int
}
HealResult summarizes the outcome of a complete healing session.
type HintsLoader ¶
type HintsLoader struct {
// contains filtered or unexported fields
}
HintsLoader discovers and loads project-specific hint files from the working directory and subdirectories the agent explores.
func (*HintsLoader) IsLoaded ¶
func (h *HintsLoader) IsLoaded(dir string) bool
IsLoaded reports whether a directory has already been scanned.
func (*HintsLoader) LoadHints ¶
func (h *HintsLoader) LoadHints(dir string) string
LoadHints scans a directory for hint files and returns their combined content. Tracks which directories have been loaded to avoid re-reading.
func (*HintsLoader) LoadHintsRecursive ¶
func (h *HintsLoader) LoadHintsRecursive(dir string) string
LoadHintsRecursive loads hints from dir and all parent dirs up to root.
func (*HintsLoader) Reset ¶
func (h *HintsLoader) Reset()
Reset clears the loaded state (e.g., on /new session).
type Hypothesis ¶
type Hypothesis = observability.Hypothesis
type ImpactAnalysis ¶
type ImpactAnalysis = project.ImpactAnalysis
type ImpactAnalyzer ¶
type ImpactAnalyzer = project.ImpactAnalyzer
type ImplicitSignal ¶
type ImplicitSignal = observability.ImplicitSignal
type InjectionScanner ¶
type InjectionScanner struct {
Patterns []injectionPattern
// contains filtered or unexported fields
}
InjectionScanner detects potential prompt-injection attempts in user input.
func NewInjectionScanner ¶
func NewInjectionScanner() *InjectionScanner
NewInjectionScanner creates an InjectionScanner with built-in detection patterns.
func (*InjectionScanner) Scan ¶
func (is *InjectionScanner) Scan(input string) *ScanResult
Scan checks the input for injection patterns and returns a risk assessment.
type InspectionAction ¶
type InspectionAction int
InspectionAction is the decision for a tool call.
const ( ActionAllow InspectionAction = iota // execute without asking ActionRequireApproval // ask user with context ActionDeny // block execution )
type InspectionResult ¶
type InspectionResult struct {
Action InspectionAction
Confidence float64 // 0.0-1.0 how confident the decision is
Reason string
ToolName string
}
InspectionResult holds the inspection decision with reasoning.
func (InspectionResult) ShouldExecute ¶
func (r InspectionResult) ShouldExecute() bool
ShouldExecute returns true if the tool can proceed without user input.
type IntegrationPipeline ¶
type IntegrationPipeline struct {
// Pre-query pipeline
IntentClassifier *IntentClassifier
ToolSelector *ToolSelector
ContextDecay *ctxmgr.ContextDecay
BudgetAllocator *BudgetAllocator
TokenPredictor *TokenPredictor
AdaptivePrompt *SystemPromptBuilder
// Post-response pipeline
ResponseFormatter *ResponseFormatter
QualityScorer *QualityScorer
FileMentionDetector *FileMentionDetector
// Post-tool pipeline
LintLoop *LintLoop
TestLoop *TestLoop
StallDetector *StallDetector
ErrorRecovery *ErrorRecovery
// Security pipeline
InjectionScanner *InjectionScanner
OutputRedactor *OutputRedactor
// Learning pipeline
ExperienceStore *ExperienceStore
KnowledgeBase *KnowledgeBase
FeedbackCollector *FeedbackCollector
SelfAssessor *SelfAssessor
// Session management
Timeline *Timeline
TokenReporter *TokenReporter
WorkspaceState *WorkspaceState
CommandHistory *CommandHistory
ResponseCache *ResponseCache
// contains filtered or unexported fields
}
IntegrationPipeline holds references to all subsystems and orchestrates them through the request lifecycle.
func NewIntegrationPipeline ¶
func NewIntegrationPipeline() *IntegrationPipeline
NewIntegrationPipeline initializes all subsystems and returns a ready-to-use pipeline orchestrator.
func (*IntegrationPipeline) EndSession ¶
func (p *IntegrationPipeline) EndSession(success bool, taskGoal string) *SessionSummary
EndSession runs the session-end pipeline: self-assess, record experience, update knowledge base, collect feedback, and generate a summary.
func (*IntegrationPipeline) FormatPipelineStatus ¶
func (p *IntegrationPipeline) FormatPipelineStatus() string
FormatPipelineStatus returns a human-readable view of which subsystems are active or inactive in the pipeline.
func (*IntegrationPipeline) PostResponse ¶
func (p *IntegrationPipeline) PostResponse(response string, messages []types.EyrieMessage) *PostResponseResult
PostResponse runs the full post-response pipeline: format, score quality, detect file mentions, redact secrets, update timeline, record tokens, cache, and update the experience store.
func (*IntegrationPipeline) PostToolExecution ¶
func (p *IntegrationPipeline) PostToolExecution(toolName string, args map[string]interface{}, output string, err error) *PostToolResult
PostToolExecution runs checks after a tool completes: stall detection, lint, test, error recovery, workspace state update, timeline record, and command history update.
func (*IntegrationPipeline) PreQuery ¶
func (p *IntegrationPipeline) PreQuery(messages []types.EyrieMessage, userInput string) *PreQueryResult
PreQuery runs the full pre-query pipeline: classify intent, select tools, apply context decay, allocate budget, predict cost, build system prompt, scan for injection, and check the response cache.
type Intelligence ¶
type Intelligence struct {
Beliefs *BeliefState
Memory MemoryRecaller
YaadBridge *memory.YaadBridge
Enhanced *memory.EnhancedMemoryManager
FileMentions *FileMentionDetector
Sleeptime *memory.SleeptimeAgent
Activity *memory.ActivityTracker
SkillDistill *memory.SkillDistiller
}
Intelligence groups all knowledge-oriented subsystems that make the agent smarter: persistent memory, belief tracking, file relevance, and skill extraction.
type Intent ¶
type Intent = intelligence.Intent
type IntentClassifier ¶
type IntentClassifier = intelligence.IntentClassifier
type IntentRule ¶
type IntentRule = intelligence.IntentRule
type InvestigatePhase ¶
type InvestigatePhase int
InvestigatePhase represents a step in structured debugging.
const ( InvestigateReproduce InvestigatePhase = iota // reproduce the issue InvestigateIsolate // narrow down the cause InvestigateRootCause // identify root cause InvestigateFix // propose and apply fix InvestigateVerify // confirm fix works )
func (InvestigatePhase) String ¶
func (p InvestigatePhase) String() string
type IssueIndex ¶
type IssueIndex = search.IssueIndex
type KnowledgeBase ¶
type KnowledgeBase = memory.KnowledgeBase
type KnowledgeEntry ¶
type KnowledgeEntry = memory.KnowledgeEntry
type KnowledgeStats ¶
type KnowledgeStats = memory.KnowledgeStats
type LLMClient ¶
type LLMClient interface {
Chat(ctx context.Context, msgs []types.EyrieMessage, opts types.ChatOptions) (*types.EyrieResponse, error)
}
LLMClient is the minimal interface for calling an LLM from engine components.
type LanguageConfig ¶
type LanguageConfig = intelligence.LanguageConfig
type LanguageRegistry ¶
type LanguageRegistry = intelligence.LanguageRegistry
type LargeResponseHandler ¶
type LargeResponseHandler struct {
MaxChunkSize int // max chars per chunk (default 8000)
OverlapLines int // lines of overlap between chunks for context
}
LargeResponseHandler chunks large tool outputs instead of truncating them. Provides pagination so the agent can request more if needed.
func NewLargeResponseHandler ¶
func NewLargeResponseHandler() *LargeResponseHandler
NewLargeResponseHandler creates a handler with defaults tuned for coding.
func (*LargeResponseHandler) Process ¶
func (h *LargeResponseHandler) Process(content string) *ChunkedResponse
Process splits a large response into chunks. Returns the first chunk with metadata.
type LearnedPattern ¶
type LearnedPattern = errs.LearnedPattern
type LearnerStats ¶
type LearnerStats = session.LearnerStats
type LimitTracker ¶
type LimitTracker = lifecycle.LimitTracker
type LintResult ¶
type LintResult = validation.LintResult
type LogEntry ¶
type LogEntry = observability.LogEntry
type LogLevel ¶
type LogLevel = observability.LogLevel
type LoopDetector ¶
type LoopDetector = control.LoopDetector
type MemoryConsolidator ¶
type MemoryConsolidator = memory.MemoryConsolidator
type MemoryRecaller ¶
type MemoryRecaller interface {
Recall(query string, tokenBudget int) (string, error)
Remember(content, category string) error
}
MemoryRecaller abstracts memory recall/remember so engine avoids importing memory directly.
type MicroCompactConfig ¶
type MicroCompactConfig = compact.MicroCompactConfig
func DefaultMicroCompactConfig ¶
func DefaultMicroCompactConfig() MicroCompactConfig
type MicroCompactStrategy ¶
type MicroCompactStrategy struct{}
func (*MicroCompactStrategy) Compact ¶
func (s *MicroCompactStrategy) Compact(ctx context.Context, sess *Session) (*CompactResult, error)
func (*MicroCompactStrategy) Name ¶
func (s *MicroCompactStrategy) Name() string
func (*MicroCompactStrategy) ShouldTrigger ¶
func (s *MicroCompactStrategy) ShouldTrigger(msgs []types.EyrieMessage, tokenCount, threshold int) bool
type MigrationPlan ¶
type MigrationPlan = project.MigrationPlan
type MigrationPlanner ¶
type MigrationPlanner = project.MigrationPlanner
type MigrationResult ¶
type MigrationResult = project.MigrationResult
type MigrationStep ¶
type MigrationStep = project.MigrationStep
type ModelPrice ¶
type ModelPrice = cost.ModelPrice
type ModuleInfo ¶
type ModuleInfo = project.ModuleInfo
type MultiRepoConfig ¶
type MultiRepoConfig struct {
Repos []RepoRelation `yaml:"repos"`
}
MultiRepoConfig is loaded from .hawk/repos.yaml.
type MultiRepoContext ¶
type MultiRepoContext struct {
Config MultiRepoConfig
BaseDir string
}
MultiRepoContext loads and manages cross-repo context.
func LoadMultiRepoConfig ¶
func LoadMultiRepoConfig(projectDir string) *MultiRepoContext
LoadMultiRepoConfig reads .hawk/repos.yaml from the project root.
func (*MultiRepoContext) HasRelatedRepos ¶
func (mrc *MultiRepoContext) HasRelatedRepos() bool
HasRelatedRepos reports whether any related repos are configured.
func (*MultiRepoContext) LoadBoundaryContext ¶
func (mrc *MultiRepoContext) LoadBoundaryContext() string
LoadBoundaryContext loads interface/type definitions from related repos. Only loads public API surfaces (exported types, interfaces, function signatures).
type Observability ¶
Observability groups telemetry and diagnostics so that tracing, metrics, and structured logging are co-located.
type OptimizedResult ¶
OptimizedResult contains the result of optimizing a single prompt.
type Optimizer ¶
type Optimizer struct {
Cost Cost
CostTracker *CostTracker
Cascade *branching.CascadeRouter
Router *modelPkg.Router
MaxBudget float64
}
Optimizer groups cost-related subsystems: tracking spend, routing requests to cheaper models when possible, and enforcing budget ceilings.
func (*Optimizer) WithinBudget ¶
WithinBudget returns true if the session has not exceeded MaxBudget. Nil-safe: returns true (no limit) when Optimizer is nil.
type OutputRedactor ¶
type OutputRedactor = safety.OutputRedactor
type PRCompressor ¶
type PRCompressor struct {
MaxTokens int
LanguagePriority map[string]int
// contains filtered or unexported fields
}
PRCompressor intelligently compresses large PR diffs to fit within a model's context window. Inspired by pr-agent, it prioritizes important source files, truncates oversized diffs, and excludes generated/lock files to maximize signal density per token spent.
func NewPRCompressor ¶
func NewPRCompressor(maxTokens int) *PRCompressor
NewPRCompressor creates a PRCompressor with the given token budget.
func (*PRCompressor) CompressDiff ¶
func (pc *PRCompressor) CompressDiff(fullDiff string, budget int) *CompressedPR
CompressDiff parses a unified diff, scores files by priority, and packs them into the given token budget. Files that don't fit are reported as overflow. Large files are truncated to keep first and last hunks.
func (*PRCompressor) ScoreFile ¶
func (pc *PRCompressor) ScoreFile(path string) float64
ScoreFile assigns a priority score to a file path based on its role. Source code gets highest priority, generated/lock files get lowest.
type PartySession ¶
PartySession manages a multi-persona discussion.
func NewPartySession ¶
func NewPartySession(topic string, personaCodes []string) *PartySession
NewPartySession creates a party mode session with selected personas.
func (*PartySession) GeneratePrompt ¶
func (ps *PartySession) GeneratePrompt(roundNum int) string
GeneratePrompt creates the system prompt for a party mode round.
type PatchVerdict ¶
type PatchVerdict = review.PatchVerdict
type PatternLibrary ¶
type PatternLibrary = scaffold.PatternLibrary
func NewPatternLibrary ¶
func NewPatternLibrary(dir string) *PatternLibrary
type PendingChange ¶
type PendingChange = diff.PendingChange
type PermissionEngine ¶
type PermissionEngine = safety.PermissionEngine
type PermissionMemory ¶
type PermissionMemory = safety.PermissionMemory
type PermissionMode ¶
type PermissionMode = safety.PermissionMode
type PermissionRequest ¶
type PermissionRequest = safety.PermissionRequest
type Persona ¶
type Persona struct {
Code string
Name string
Title string
Icon string
Style string // how this persona communicates
}
Persona represents a specialized agent persona for party mode.
type PlanStep ¶
type PlanStep struct {
Description string
File string
Action string // "create", "modify", "delete"
Details string
}
PlanStep is a single step in the architect's plan.
type PlannedCall ¶
type PlannedCall = planning.PlannedCall
type PostResponseResult ¶
type PostResponseResult struct {
FormattedResponse string
QualityScore float64
MentionedFiles []string
TokensUsed int
}
PostResponseResult holds the aggregated results of the post-response pipeline.
type PostToolResult ¶
type PostToolResult struct {
StallWarning string
LintErrors string
TestFailures string
RecoveryAction string
ShouldRetry bool
}
PostToolResult holds the aggregated results of the post-tool-execution pipeline.
type PreQueryResult ¶
type PreQueryResult struct {
Intent *Intent
SuggestedTools []string
BudgetAllocation map[string]int
PredictedCost float64
SystemPrompt string
CacheHit bool
CachedResponse string
InjectionRisk *ScanResult
}
PreQueryResult holds the aggregated results of the pre-query pipeline.
type Prediction ¶
type Prediction = token.Prediction
type PredictionRecord ¶
type PredictionRecord = token.PredictionRecord
type Preview ¶
type Preview = diff.DiffPreview
type ProfileSpan ¶
type ProfileSpan = observability.ProfileSpan
type Profiler ¶
type Profiler = observability.Profiler
type ProjectAnalysis ¶
type ProjectAnalysis = project.ProjectAnalysis
type ProjectAnalyzer ¶
type ProjectAnalyzer = project.ProjectAnalyzer
type ProjectContext ¶
type ProjectContext = project.ProjectContext
type ProjectSnapshot ¶
type ProjectSnapshot = project.ProjectSnapshot
type ProjectSnapshotCache ¶
type ProjectSnapshotCache = project.ProjectSnapshotCache
type PromptAdjustment ¶
type PromptAdjustment struct {
Rule string `json:"rule"` // "always use tabs" or "never add comments"
Source string `json:"source"` // user message that triggered this
Polarity string `json:"polarity"` // "do" or "dont"
Confidence float64 `json:"confidence"` // increases with reinforcement
Active bool `json:"active"`
CreatedAt time.Time `json:"created_at"`
LastUsed time.Time `json:"last_used"`
}
PromptAdjustment is a user-derived prompt modification.
type PromptBuildContext ¶
type PromptBuildContext struct {
Task string
Language string
ProjectType string
Model string
TurnCount int
HasMemory bool
HasGoals bool
}
PromptBuildContext provides situational context for building a system prompt.
type PromptMsg ¶
PromptMsg represents a message in a conversation with role, content, and token count.
type PromptOpt ¶
PromptOpt represents a single optimization strategy that can be applied to prompts.
type PromptPattern ¶
type PromptPattern = scaffold.PromptPattern
type PromptSection ¶
type PromptSection struct {
Name string
Content string
Priority int // 1 = highest priority, higher numbers = lower priority
Tokens int // pre-computed token count (0 means recalculate)
Conditional func() bool // if non-nil, section is included only when this returns true
Dynamic func() string // if non-nil, content is generated at build time
}
PromptSection represents a named section of the system prompt with priority and optional dynamic generation logic.
func DefaultSections ¶
func DefaultSections(ctx PromptBuildContext) []PromptSection
DefaultSections returns the built-in prompt sections that hawk uses.
type ProtectedPaths ¶
type ProtectedPaths = safety.ProtectedPaths
type QualityGate ¶
type QualityGate struct {
Phase GatePhase
Check func() GateResult
}
QualityGate defines a checkpoint between phases.
func ImplementGate ¶
func ImplementGate(validateCmd string, workDir string) QualityGate
ImplementGate checks that code compiles and basic tests pass.
type QualityScorer ¶
type QualityScorer = review.QualityScorer
type QuickDevPhase ¶
type QuickDevPhase int
QuickDevPhase represents a step in the quick-dev workflow.
const ( QuickDevClarify QuickDevPhase = iota // compress intent into one goal QuickDevRoute // one-shot vs planned QuickDevImplement // execute QuickDevReview // adversarial self-review QuickDevPresent // show results )
func (QuickDevPhase) String ¶
func (p QuickDevPhase) String() string
type QuickDevState ¶
type QuickDevState struct {
Phase QuickDevPhase
Intent string // compressed user intent
IsOneShot bool // true = skip planning
Spec string // frozen spec (if planned path)
FilesChanged []string
}
QuickDevState tracks the current state of a quick-dev workflow.
type RecipeRegistry ¶
type RecipeRegistry = scaffold.RecipeRegistry
func NewRecipeRegistry ¶
func NewRecipeRegistry(dir string) *RecipeRegistry
type Recommendation ¶
type Recommendation = cost.Recommendation
type RecoveryAttempt ¶
type RecoveryAttempt = errs.RecoveryAttempt
type RecoveryContext ¶
type RecoveryContext = errs.RecoveryContext
type RecoveryResult ¶
type RecoveryResult = errs.RecoveryResult
type RecoveryStrategy ¶
type RecoveryStrategy = errs.RecoveryStrategy
type RedactPattern ¶
type RedactPattern = safety.RedactPattern
type RedactStats ¶
type RedactStats = safety.RedactStats
type ReflectionEntry ¶
type ReflectionEntry struct {
Attempt int
TaskGoal string
WhatFailed string
WhyFailed string
WhatToDo string
Timestamp time.Time
}
ReflectionEntry records a single reflection.
type Reflector ¶
type Reflector struct {
// contains filtered or unexported fields
}
Reflector provides verbal self-reflection on agent actions.
func NewReflector ¶
NewReflector creates a reflector with the given LLM client.
func (*Reflector) History ¶
func (r *Reflector) History() []ReflectionEntry
History returns all reflection entries.
func (*Reflector) InjectReflections ¶
InjectReflections formats reflection history as a string for system prompt injection.
type ReleaseManager ¶
type ReleaseManager = project.ReleaseManager
type ReleaseStats ¶
type ReleaseStats = project.ReleaseStats
type RepoRelation ¶
type RepoRelation struct {
Path string `yaml:"path"`
Relation string `yaml:"relation"` // "dependency", "types", "service", "shared"
}
RepoRelation defines how a related repo connects to the current one.
type Report ¶
type Report = review.ReviewReport
type RequestCost ¶
type RequestCost = cost.RequestCost
type ResearchAgent ¶
type ResearchAgent = search.ResearchAgent
type ResearchFinding ¶
type ResearchFinding = search.ResearchFinding
type ResearchQuery ¶
type ResearchQuery = search.ResearchQuery
type ResearchResult ¶
type ResearchResult = search.ResearchResult
type ResponseCache ¶
type ResponseCache = streaming.ResponseCache
type ResponseContext ¶
type ResponseContext = review.ResponseContext
type ResponseFormatter ¶
type ResponseFormatter = streaming.ResponseFormatter
type Result ¶
type Result = workflow.WorkflowResult
type ReviewComment ¶
type ReviewComment = review.ReviewComment
type ReviewFinding ¶
type ReviewFinding struct {
Severity string // HIGH, MEDIUM, LOW
File string
Line int
Category string // edge-case, error-handling, security, performance, logic
Issue string
Fix string
}
ReviewFinding is a single issue found during adversarial review.
type ReviewReport ¶
type ReviewReport = review.ReviewReport
type ReviewResult ¶
type ReviewResult = review.ReviewResult
type ReviewRule ¶
type ReviewRule = review.ReviewRule
type RiskAssessment ¶
type RiskAssessment = safety.RiskAssessment
type RiskAssessor ¶
type RiskAssessor = safety.RiskAssessor
type RiskContext ¶
type RiskContext = safety.RiskContext
type RiskFactor ¶
type RiskFactor = safety.RiskFactor
type RiskFactorDef ¶
type RiskFactorDef = safety.RiskFactorDef
type RotatingWriter ¶
type RotatingWriter = observability.RotatingWriter
type Rule ¶
type Rule = review.ReviewRule
type SafetyLayer ¶
type SafetyLayer struct {
Perm *PermissionEngine
Sandbox *DiffSandbox
Limits *LimitTracker
Autonomy AutonomyLevel
Protected *ProtectedPaths
}
SafetyLayer groups all mechanisms that prevent the agent from causing harm: permission checks, sandboxed file edits, rate/size limits, and path protection.
func (*SafetyLayer) IsPermitted ¶
func (sl *SafetyLayer) IsPermitted(action string) bool
IsPermitted is a nil-safe convenience that delegates to the PermissionEngine.
type SafetyLimits ¶
type SafetyLimits = lifecycle.SafetyLimits
type Scaffolder ¶
type Scaffolder = scaffold.Scaffolder
func NewScaffolder ¶
func NewScaffolder() *Scaffolder
type ScaleBehavior ¶
type ScaleBehavior struct {
Scale TaskScale
MaxTurns int
PlanRequired bool
AutoApprove bool // auto-approve file edits
ScanScope string // "file", "module", "repo"
}
ScaleBehavior defines how hawk adjusts its behavior per scale.
func GetBehavior ¶
func GetBehavior(scale TaskScale) ScaleBehavior
GetBehavior returns the behavior config for a given scale.
type ScanResult ¶
type ScanResult struct {
IsRisky bool
RiskLevel string // "none", "low", "medium", "high"
Patterns []string
Suggestion string
}
ScanResult describes the outcome of an injection scan.
type Schema ¶
type Schema = validation.Schema
type SchemaValidationError ¶
type SchemaValidationError = validation.SchemaValidationError
type SchemaValidationResult ¶
type SchemaValidationResult = validation.SchemaValidationResult
type SchemaValidator ¶
type SchemaValidator = validation.SchemaValidator
func NewSchemaValidator ¶
func NewSchemaValidator() *SchemaValidator
type ScoreWeights ¶
type ScoreWeights = review.ScoreWeights
type ScoredResponse ¶
type ScoredResponse = review.ScoredResponse
type ScrapeResult ¶
type ScrapeResult = search.ScrapeResult
type SelectedTests ¶
type SelectedTests = diff.SelectedTests
type SelfAssessor ¶
type SelfAssessor = review.SelfAssessor
type SelfAwareness ¶
type SelfAwareness struct {
MaxComplexity TaskScale // tasks above this get delegated
Specialties []string // what this agent is good at
}
SelfAwareness allows an agent to recognize its own limitations.
func (*SelfAwareness) DelegationPrompt ¶
func (sa *SelfAwareness) DelegationPrompt(prompt string, reason string) string
DelegationPrompt generates a prompt explaining why delegation is needed.
func (*SelfAwareness) ShouldDelegate ¶
func (sa *SelfAwareness) ShouldDelegate(prompt string, currentScale TaskScale) bool
ShouldDelegate returns true if the agent should pass this task to a more capable agent.
type SelfHealer ¶
type SelfHealer struct {
// MaxAttempts is the maximum number of heal attempts before giving up.
// Default is 5.
MaxAttempts int
// Timeout is the maximum time allowed for each script execution.
// Default is 60s.
Timeout time.Duration
// History stores all healing attempts for inspection.
History []HealAttempt
// ChatFn is the LLM chat function used to generate fixes.
ChatFn func(ctx context.Context, prompt string) (string, error)
// contains filtered or unexported fields
}
SelfHealer implements a wolverine-inspired self-healing execution loop. It runs a script, captures crash output, sends it to an LLM for a fix, applies the patch, and re-runs until success or max attempts.
func NewSelfHealer ¶
NewSelfHealer creates a SelfHealer with sensible defaults.
func (*SelfHealer) ApplyFixes ¶
func (sh *SelfHealer) ApplyFixes(fixes []FileFix) error
ApplyFixes applies a slice of file fixes to disk.
func (*SelfHealer) BuildFixPrompt ¶
func (sh *SelfHealer) BuildFixPrompt(script, output, errorMsg string, attempt int) string
BuildFixPrompt constructs the prompt sent to the LLM, including script content, error output, and previous attempt context.
func (*SelfHealer) Heal ¶
func (sh *SelfHealer) Heal(ctx context.Context, scriptPath string) (*HealResult, error)
Heal runs a script and iteratively fixes it until it succeeds or max attempts are exhausted.
func (*SelfHealer) HealCommand ¶
func (sh *SelfHealer) HealCommand(ctx context.Context, command string) (*HealResult, error)
HealCommand runs an arbitrary shell command and iteratively fixes related files until the command succeeds or max attempts are exhausted.
type SelfImproveEntry ¶
type SelfImproveEntry struct {
Timestamp time.Time `json:"timestamp"`
What string `json:"what"` // what went wrong
Why string `json:"why"` // root cause
Lesson string `json:"lesson"` // what to do differently
Category string `json:"category"` // code, test, design, communication
}
SelfImproveEntry records a lesson learned from a mistake.
type SelfImprover ¶
type SelfImprover struct {
Path string
Entries []SelfImproveEntry
}
SelfImprover tracks mistakes and lessons across sessions.
func NewSelfImprover ¶
func NewSelfImprover() *SelfImprover
NewSelfImprover loads or creates the improvement log.
func (*SelfImprover) ForPrompt ¶
func (si *SelfImprover) ForPrompt(maxEntries int) string
ForPrompt formats recent lessons as context for the system prompt.
func (*SelfImprover) Learn ¶
func (si *SelfImprover) Learn(what, why, lesson, category string)
Learn records a new lesson.
func (*SelfImprover) Lessons ¶
func (si *SelfImprover) Lessons(category string) []SelfImproveEntry
Lessons returns all lessons, optionally filtered by category.
type SelfReviewResult ¶
type SelfReviewResult struct {
Approved bool // whether the change should be applied
Issues []string // problems found during review
Suggestions []string // improvements that could be made
Confidence float64 // 0.0-1.0: how confident the reviewer is in its assessment
}
SelfReviewResult holds the outcome of an LLM self-review of a proposed change.
func ReviewBeforeWrite ¶
func ReviewBeforeWrite(ctx context.Context, llm LLMClient, model string, intent string, filePath string, oldContent string, newContent string, ) (*SelfReviewResult, error)
ReviewBeforeWrite asks the model to review its own proposed changes before they are applied to a file. It compares old and new content in the context of the user's original intent and returns approval or a list of issues.
If confidence is below ConfidenceThreshold (0.7), the review will suggest fixes rather than approving, regardless of whether explicit issues were found.
type SemanticAnalyzer ¶
type SemanticAnalyzer struct {
// contains filtered or unexported fields
}
SemanticAnalyzer performs semantic diff analysis on Go source code.
func NewSemanticAnalyzer ¶
func NewSemanticAnalyzer() *SemanticAnalyzer
NewSemanticAnalyzer creates a new SemanticAnalyzer instance.
func (*SemanticAnalyzer) AnalyzeDiff ¶
func (sa *SemanticAnalyzer) AnalyzeDiff(diff string) (*SemanticDiff, error)
AnalyzeDiff parses a unified diff and performs semantic analysis on Go code changes.
func (*SemanticAnalyzer) FindAffectedAPIs ¶
func (sa *SemanticAnalyzer) FindAffectedAPIs(changes []SemanticChange, content string) []string
FindAffectedAPIs traces changed functions to HTTP handlers/routes in the content.
type SemanticChange ¶
type SemanticChange struct {
File string
Type string // "function_added", "function_removed", "function_modified", "type_changed", "import_added", "import_removed", "signature_changed", "behavior_changed"
Name string
Description string
Breaking bool
Risk string
}
SemanticChange describes a single semantic change detected in a diff.
func DetectBehaviorChanges ¶
func DetectBehaviorChanges(oldContent, newContent string) []SemanticChange
DetectBehaviorChanges detects changes in code behavior such as error handling, nil checks, loop bounds, and conditional logic.
func DetectBreakingChanges ¶
func DetectBreakingChanges(oldContent, newContent string) []SemanticChange
DetectBreakingChanges compares old and new Go source content and returns semantic changes that represent breaking API changes.
type SemanticDiff ¶
type SemanticDiff struct {
Changes []SemanticChange
Summary string
RiskLevel string
AffectedAPIs []string
}
SemanticDiff holds the result of semantic analysis of a diff.
type ServiceOption ¶
type ServiceOption func(*SessionServices)
ServiceOption configures a SessionServices during construction.
func WithCascade ¶
func WithCascade(cascade *branching.CascadeRouter) ServiceOption
WithCascade sets the CascadeRouter on the Optimizer.
func WithGuardian ¶
func WithGuardian(guardian *permissions.Guardian) ServiceOption
WithGuardian configures the SafetyLayer with a permissions.Guardian. It wraps the Guardian into the existing PermissionEngine structure.
func WithLogger ¶
func WithLogger(log *logger.Logger) ServiceOption
WithLogger sets the logger on both CoreLoop and Observability.
func WithMaxBudget ¶
func WithMaxBudget(budget float64) ServiceOption
WithMaxBudget sets the maximum budget on the Optimizer.
func WithMemory ¶
func WithMemory(mem MemoryRecaller) ServiceOption
WithMemory sets the MemoryRecaller on the Intelligence service.
func WithProvider ¶
func WithProvider(provider, model string) ServiceOption
WithProvider sets the LLM provider and model on the CoreLoop.
func WithSandbox ¶
func WithSandbox(sandbox *DiffSandbox) ServiceOption
WithSandbox sets the DiffSandbox on the SafetyLayer.
func WithTools ¶
func WithTools(registry *tool.Registry) ServiceOption
WithTools sets the tool registry on the CoreLoop.
func WithTracing ¶
func WithTracing(tracer *oteltrace.Tracer) ServiceOption
WithTracing sets the Tracer on the Observability service.
type Session ¶
type Session struct {
Cost Cost
Router *modelPkg.Router
// DeploymentRouting is true when the chat client is catalog-backed (e.g. DeploymentRouter).
DeploymentRouting bool
// ContainerExecutor runs Bash in an isolated container when set (no API keys in container env).
ContainerExecutor tool.ContainerExecutor
Perm *PermissionEngine // extracted permission subsystem
// Backward-compatible accessors below (will be removed after full migration)
Permissions *PermissionMemory // use Perm.Memory
AutoMode *permissions.AutoModeState // use Perm.AutoMode
Classifier *permissions.Classifier // use Perm.Classifier
BypassKill *permissions.BypassKillswitch // use Perm.BypassKill
Mode PermissionMode // use Perm.Mode
MaxTurns int
MaxBudgetUSD float64
AllowedDirs []string
PermissionFn func(PermissionRequest) // use Perm.PromptFn
AgentSpawnFn func(ctx context.Context, prompt string) (string, error)
AskUserFn func(question string) (string, error)
Memory MemoryRecaller
YaadBridge *memory.YaadBridge
EnhancedMemory *memory.EnhancedMemoryManager
SettingsGet func(key string) (string, bool)
SettingsSet func(key, value string) error
PinnedMessages int // messages to protect from compaction (from /pin)
AutoCompactThresholdPct int // token % to trigger auto-compact (default 85)
// Cost optimization
Cascade *branching.CascadeRouter // cascade.go — model tier routing
Lifecycle *SessionLifecycle // lifecycle.go — self-improvement loop
Reflector *Reflector // reflect.go — verbal self-reflection
CostTracker *CostTracker // cost_tracker.go — per-request cost persistence
// Advanced features
Autonomy AutonomyLevel // autonomy.go — permission level
Sandbox *DiffSandbox // diffsandbox.go — staged file changes
Plan *PlanState // subtask.go — user-activated plan
Beliefs *BeliefState // belief.go — discovered knowledge
Critic *Critic // critic.go — patch pre-screening
Backtrack *BacktrackEngine // backtrack.go — decision recording
Limits *LimitTracker // limits.go — safety limits
Teach TeachConfig // teach.go — explanation depth
Trajectory *TrajectoryDistiller // trajectory.go — multi-run distillation
Shadow *branching.ShadowWorkspace // shadow.go — edit pre-validation
Snapshots SnapshotTracker // snapshot integration for auto-tracking
ConvoDAG *storage.DAG // conversation DAG for branching/forking
Sleeptime *memory.SleeptimeAgent // sleeptime.go — background memory consolidation
Activity *memory.ActivityTracker // activity.go — memory save nudging (Engram pattern)
SkillDistiller *memory.SkillDistiller // skill_distill.go — auto-skill extraction
Tracer *oteltrace.Tracer // oteltrace.go — distributed tracing spans
LintLoop *LintLoop // lint_loop.go — auto lint-fix reflected messages
TestLoop *TestLoop // test_loop.go — auto test-fix loop
FileMentions *FileMentionDetector // file_mentions.go — detect referenced files
ResponseCache *ResponseCache // response_cache.go — cache similar prompts
Pipeline *IntegrationPipeline // integration.go — unified feature orchestration
Files *FileTracker // compact_files.go — cumulative file tracking across compactions
Steering *SteeringQueue // steering.go — user guidance injection between tool batches
// contains filtered or unexported fields
}
Session manages a conversation with an LLM via eyrie. NOTE: Session is NOT thread-safe. All mutation must happen from the agent loop goroutine. SetProvider/SetAPIKey are called during initialization only. If concurrent access is needed in the future (e.g. daemon handling concurrent requests), add a sync.RWMutex.
func NewHawkSession ¶
func NewHawkSession(ctx context.Context, useDeploymentRouting bool, provider, model, systemPrompt string, registry *tool.Registry) *Session
NewHawkSession constructs a Session using deployment routing when configured.
func NewSession ¶
NewSession creates a new conversation session with a legacy string-named provider.
func NewSessionWithClient ¶
func NewSessionWithClient(chat ChatClient, provider, model, systemPrompt string, registry *tool.Registry, deploymentRouting bool) *Session
NewSessionWithClient constructs a session with an explicit LLM client (e.g. deployment router).
func (*Session) AddAssistant ¶
func (*Session) AppendSystemContext ¶
AppendSystemContext adds runtime context, such as /add-dir, to future model calls.
func (*Session) AutoCompactIfNeeded ¶
AutoCompactIfNeeded runs compaction when the conversation exceeds the threshold.
func (*Session) Compact ¶
func (s *Session) Compact()
Compact reduces conversation history (boundary-aware truncation).
func (*Session) ForkConversation ¶
ForkConversation creates a new branch from a specific point in history. Returns the fork node ID and the messages up to that point.
func (*Session) ListBranches ¶
ListBranches returns child nodes (alternative branches) from a given node.
func (*Session) LoadMessages ¶
func (s *Session) LoadMessages(msgs []types.EyrieMessage)
func (*Session) MessageCount ¶
func (*Session) RawMessages ¶
func (s *Session) RawMessages() []types.EyrieMessage
RawMessages returns the conversation messages for persistence.
func (*Session) ReattachTransport ¶
func (s *Session) ReattachTransport(chat ChatClient, provider string, deploymentRouting bool)
ReattachTransport swaps the LLM client after deployment routing or provider.json changes.
func (*Session) RemoveLastExchange ¶
func (s *Session) RemoveLastExchange()
RemoveLastExchange removes the last user+assistant message pair.
func (*Session) ReplaceSystemContextSection ¶
ReplaceSystemContextSection replaces the content of a system prompt section identified by its header. If the header is not found, appends the content as a new section.
func (*Session) Services ¶
func (s *Session) Services() *SessionServices
Services returns a SessionServices view of the existing Session struct. This bridges legacy code (which manipulates Session fields directly) with new code (which prefers the composed service interface).
The returned *SessionServices references the same underlying objects as Session, so mutations are visible in both directions.
func (*Session) SetAPIKeys ¶
SetAPIKeys updates all known provider API keys for subsequent requests.
func (*Session) SetAllowedDirs ¶
SetAllowedDirs sets directories that file tools are allowed to access.
func (*Session) SetMaxBudgetUSD ¶
func (*Session) SetMaxTurns ¶
func (*Session) SetPermissionMode ¶
func (*Session) SetProvider ¶
SetProvider updates the active provider for subsequent requests.
func (*Session) SetTestClient ¶
func (s *Session) SetTestClient(c ChatClient)
SetTestClient replaces the session's LLM client. For testing only.
func (*Session) ShouldAutoCompact ¶
ShouldAutoCompact returns true if the conversation is approaching context limits.
func (*Session) SmartCompact ¶
func (s *Session) SmartCompact()
SmartCompact reduces conversation history using LLM-generated summaries.
func (*Session) SplitTurnNeeded ¶
SplitTurnNeeded checks if any single turn in the recent messages exceeds the given token budget. The budget is defined as the average token count of the keepCount messages multiplied by 3 (a single message uses more than 3x the average of the kept tail).
func (*Session) Stream ¶
func (s *Session) Stream(ctx context.Context) (<-chan StreamEvent, error)
Stream runs the agentic loop: LLM → tool_use → execute → loop.
func (*Session) SubSession ¶
SubSession clones transport and routing mode for explore/general sub-agents.
func (*Session) SwitchBranch ¶
SwitchBranch navigates to a different branch point and rebuilds messages.
func (*Session) WireAgentTool ¶
func (s *Session) WireAgentTool()
WireAgentTool sets up sub-agent spawning with two modes:
- explore: fast/cheap model, read-only tools, higher turn budget
- general: full model, all tools, standard budget
type SessionCompressor ¶
type SessionCompressor = session.SessionCompressor
func NewSessionCompressor ¶
func NewSessionCompressor(strategy CompressStrategy) *SessionCompressor
type SessionConvention ¶
type SessionConvention = session.SessionConvention
type SessionLifecycle ¶
type SessionLifecycle = lifecycle.SessionLifecycle
type SessionMemoryConfig ¶
type SessionMemoryConfig = compact.SessionMemoryConfig
func DefaultSessionMemoryConfig ¶
func DefaultSessionMemoryConfig() SessionMemoryConfig
type SessionMemoryStrategy ¶
type SessionMemoryStrategy struct{}
func (*SessionMemoryStrategy) Compact ¶
func (s *SessionMemoryStrategy) Compact(ctx context.Context, sess *Session) (*CompactResult, error)
func (*SessionMemoryStrategy) Name ¶
func (s *SessionMemoryStrategy) Name() string
func (*SessionMemoryStrategy) ShouldTrigger ¶
func (s *SessionMemoryStrategy) ShouldTrigger(msgs []types.EyrieMessage, tokenCount, threshold int) bool
type SessionOutcome ¶
type SessionOutcome = lifecycle.SessionOutcome
type SessionReflection ¶
type SessionReflection struct {
WentWell string
WentBadly string
ToImprove string
Confidence int
Lesson string
}
SessionReflection holds the structured output of a reflection.
type SessionServices ¶
type SessionServices struct {
Core *CoreLoop
Safety *SafetyLayer
Intel *Intelligence
Optim *Optimizer
Observe *Observability
// Advanced features (optional, nil when unused)
Lifecycle *SessionLifecycle
Reflector *Reflector
Critic *Critic
Backtrack *BacktrackEngine
Shadow *branching.ShadowWorkspace
ConvoDAG *storage.DAG
Plan *PlanState
Teach TeachConfig
Trajectory *TrajectoryDistiller
Snapshots SnapshotTracker
LintLoop *LintLoop
}
SessionServices is the new composed container that groups Session's 30+ fields into coherent sub-services. Use Session.Services() to obtain this view from existing code.
func NewSessionServices ¶
func NewSessionServices(opts ...ServiceOption) *SessionServices
NewSessionServices creates a SessionServices with defaults and applies the given functional options.
type SessionSummary ¶
type SessionSummary struct {
Assessment *Assessment
Experience *Experience
Summary string
TokensTotal int
Duration time.Duration
FilesModified []string
}
SessionSummary captures the final assessment when a session ends.
type SignatureChange ¶
type SignatureChange struct {
Name string
ParamsAdded []string
ParamsRemoved []string
ParamsReordered bool
ReturnChanged bool
OldReturn string
NewReturn string
ReceiverChanged bool
OldReceiver string
NewReceiver string
}
SignatureChange describes how a function signature changed between versions.
func CompareSignatures ¶
func CompareSignatures(oldSig, newSig string) *SignatureChange
CompareSignatures compares two function signature strings and returns the differences.
type SimilarIssue ¶
type SimilarIssue = search.SimilarIssue
type SingleFileWatcher ¶
type SingleFileWatcher = io.SingleFileWatcher
type SkillDistillerAdapter ¶
type SkillDistillerAdapter = lifecycle.SkillDistillerAdapter
type SkillRegistry ¶
type SkillRegistry = scaffold.SkillRegistry
func NewSkillRegistry ¶
func NewSkillRegistry(dir string) *SkillRegistry
type SkillResult ¶
type SkillResult = scaffold.SkillResult
type SkillStoreInterface ¶
type SkillStoreInterface = lifecycle.SkillStoreInterface
type SmartCompactStrategy ¶
type SmartCompactStrategy struct{}
SmartCompactStrategy uses LLM to generate a conversation summary.
func (*SmartCompactStrategy) Compact ¶
func (s *SmartCompactStrategy) Compact(ctx context.Context, sess *Session) (*CompactResult, error)
func (*SmartCompactStrategy) Name ¶
func (s *SmartCompactStrategy) Name() string
func (*SmartCompactStrategy) ShouldTrigger ¶
func (s *SmartCompactStrategy) ShouldTrigger(msgs []types.EyrieMessage, tokenCount, threshold int) bool
type SnapshotCache ¶
type SnapshotCache struct {
// contains filtered or unexported fields
}
SnapshotCache is a TTL-based cache for project snapshots with LRU eviction.
func NewSnapshotCache ¶
func NewSnapshotCache(ttl time.Duration) *SnapshotCache
NewSnapshotCache creates a new SnapshotCache with the given TTL. If ttl is zero, DefaultSnapshotTTL is used.
func (*SnapshotCache) Get ¶
func (sc *SnapshotCache) Get(key string) (string, bool)
Get returns the cached value for the key if it exists and has not expired. Promotes the entry to most recently used on hit.
func (*SnapshotCache) GetOrCompute ¶
GetOrCompute returns the cached value for the key, or computes and caches it using the provided function if the value is missing or expired.
func (*SnapshotCache) Set ¶
func (sc *SnapshotCache) Set(key, value string)
Set stores a value in the cache with the configured TTL. Evicts the least recently used entry if the cache exceeds its maximum size.
type SnapshotTracker ¶
SnapshotTracker abstracts the snapshot system so engine doesn't import snapshot directly.
type SolutionReviewer ¶
type SolutionReviewer = review.SolutionReviewer
type SourceRoot ¶
SourceRoot tracks a directory the agent has explored.
type SourceRoots ¶
type SourceRoots struct {
// contains filtered or unexported fields
}
SourceRoots tracks which directories the agent has explored to avoid re-scanning.
func NewSourceRoots ¶
func NewSourceRoots() *SourceRoots
NewSourceRoots creates a source root tracker.
func (*SourceRoots) Invalidate ¶
func (sr *SourceRoots) Invalidate(path string)
Invalidate removes a root (e.g., after files changed).
func (*SourceRoots) IsExplored ¶
func (sr *SourceRoots) IsExplored(path string) bool
IsExplored reports whether a directory has been explored.
func (*SourceRoots) List ¶
func (sr *SourceRoots) List() []*SourceRoot
List returns all explored roots.
func (*SourceRoots) Mark ¶
func (sr *SourceRoots) Mark(path string, fileCount int)
Mark records that a directory has been explored.
func (*SourceRoots) Stale ¶
func (sr *SourceRoots) Stale(maxAge time.Duration) []*SourceRoot
Stale returns roots explored more than maxAge ago.
type SpawnDecision ¶
type SpawnDecision struct {
ShouldParallelize bool
SubTasks []SubTask
Strategy SpawnStrategy
}
SpawnDecision determines whether and how to parallelize a task.
type SpawnStrategy ¶
type SpawnStrategy int
SpawnStrategy defines how agents coordinate.
const ( StrategySequential SpawnStrategy = iota // one after another StrategyParallel // all at once, merge results StrategyPipeline // output of one feeds next StrategySingle // no decomposition needed )
type Spec ¶
type Spec struct {
Title string
Goal string
Files []string
Criteria []string // acceptance criteria
Assumptions []string
OutOfScope []string
CreatedAt time.Time
Approved bool
}
Spec is a frozen specification that defines what to build.
type StagedChange ¶
type StagedChange = diff.StagedChange
type StagedHunk ¶
type StagedHunk = diff.StagedHunk
type StagingArea ¶
type StagingArea = diff.StagingArea
type StallDetector ¶
type StallDetector = control.StallDetector
type StallEntry ¶
type StallEntry = control.StallEntry
type StallResult ¶
type StallResult = control.StallResult
type SteeringMessage ¶
type SteeringMessage = streaming.SteeringMessage
type SteeringQueue ¶
type SteeringQueue = streaming.SteeringQueue
type Step ¶
type Step = workflow.WorkflowStep
type StepResult ¶
type StepResult = workflow.StepResult
type StrategyRegistry ¶
type StrategyRegistry struct {
// contains filtered or unexported fields
}
func NewStrategyRegistry ¶
func NewStrategyRegistry(config CompactConfig) *StrategyRegistry
func (*StrategyRegistry) SelectStrategy ¶
func (r *StrategyRegistry) SelectStrategy(msgs []types.EyrieMessage, tokenCount int) CompactStrategy
type StreamEvent ¶
type StreamEvent struct {
Type string // content, thinking, tool_use, tool_result, usage, done, error
Content string
ToolName string
ToolID string
Usage *StreamUsage // usage data for this event
}
StreamEvent is sent from the engine to the TUI.
type StreamOptimizer ¶
type StreamOptimizer = streaming.StreamOptimizer
type StreamStats ¶
type StreamStats = streaming.StreamStats
type StreamUsage ¶
type StreamUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
CacheReadTokens int `json:"cache_read_tokens,omitempty"`
CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
}
StreamUsage tracks token usage for a single stream event.
type StructuredLogger ¶
type StructuredLogger = observability.StructuredLogger
type SubAgentBudget ¶
type SubAgentBudget = agent.SubAgentBudget
func NewSubAgentBudget ¶
func NewSubAgentBudget(mode SubAgentMode, cfg SubAgentConfig) *SubAgentBudget
type SubAgentConfig ¶
type SubAgentConfig = agent.SubAgentConfig
func DefaultSubAgentConfig ¶
func DefaultSubAgentConfig() SubAgentConfig
type SubAgentMode ¶
type SubAgentMode = agent.SubAgentMode
type SubTask ¶
type SubTask struct {
ID string
Prompt string
Mode SubAgentMode
Priority int // higher = run first
DependsOn []string // IDs of tasks this depends on
}
SubTask is a decomposed piece of work for a sub-agent.
type SuggestedTask ¶
type SuggestedTask = planning.SuggestedTask
type SuggestionEngine ¶
type SuggestionEngine = intelligence.SuggestionEngine
type SuggestionRule ¶
type SuggestionRule = intelligence.SuggestionRule
type SumMessage ¶
type SumMessage = history.SumMessage
type Summarizer ¶
type Summarizer = diff.DiffSummarizer
type SummaryLevel ¶
type SummaryLevel = history.SummaryLevel
type SystemPromptBuilder ¶
type SystemPromptBuilder struct {
BasePrompt string
Sections []PromptSection
MaxTokens int
// contains filtered or unexported fields
}
SystemPromptBuilder constructs a system prompt by assembling prioritized sections within a token budget. It complements AdaptivePrompt by handling structural composition rather than learned user preferences.
func NewSystemPromptBuilder ¶
func NewSystemPromptBuilder(basePrompt string, maxTokens int) *SystemPromptBuilder
NewSystemPromptBuilder creates a SystemPromptBuilder with a base prompt and token limit.
func (*SystemPromptBuilder) AdaptForModel ¶
func (b *SystemPromptBuilder) AdaptForModel(model string) *SystemPromptBuilder
AdaptForModel adjusts verbosity and section limits based on the target model.
func (*SystemPromptBuilder) AdaptForTask ¶
func (b *SystemPromptBuilder) AdaptForTask(task string) *SystemPromptBuilder
AdaptForTask adjusts section priorities based on the task type, returning the builder for method chaining. Modifies the builder in place.
func (*SystemPromptBuilder) AddSection ¶
func (b *SystemPromptBuilder) AddSection(section PromptSection)
AddSection appends a prompt section. If a section with the same name exists, it is replaced.
func (*SystemPromptBuilder) Build ¶
func (b *SystemPromptBuilder) Build(ctx PromptBuildContext) string
Build assembles the final system prompt by evaluating conditionals, calling dynamic generators, sorting by priority, and fitting sections within the token budget.
func (*SystemPromptBuilder) RemoveSection ¶
func (b *SystemPromptBuilder) RemoveSection(name string)
RemoveSection removes a section by name.
type TaskContext ¶
type TaskContext = review.TaskContext
type TaskDecomposer ¶
type TaskDecomposer = planning.TaskDecomposer
type TaskScale ¶
type TaskScale int
TaskScale represents the complexity/scope of a user request.
func ClassifyScale ¶
ClassifyScale determines the task scale from user input.
type TeachConfig ¶
TeachConfig controls explanation depth.
type TemplateFile ¶
type TemplateFile = scaffold.TemplateFile
type TemplateVariable ¶
type TemplateVariable = scaffold.TemplateVariable
type TestResult ¶
type TestResult = validation.TestResult
type TestSelector ¶
type TestSelector = diff.TestSelector
type ThinkingPhase ¶
type ThinkingPhase = streaming.ThinkingPhase
type ThinkingProtocol ¶
type ThinkingProtocol = streaming.ThinkingProtocol
type ThinkingStep ¶
type ThinkingStep = streaming.ThinkingStep
type Timeline ¶
func NewTimeline ¶
type TimelineEvent ¶
type TimelineEvent = session.TimelineEvent
type TimeoutConfig ¶
type TimeoutConfig = lifecycle.TimeoutConfig
type Timer ¶
type Timer = observability.Timer
type TokenEntry ¶
type TokenEntry = token.TokenEntry
type TokenPredictor ¶
type TokenPredictor = token.TokenPredictor
func NewTokenPredictor ¶
func NewTokenPredictor() *TokenPredictor
type TokenReporter ¶
type TokenReporter = token.TokenReporter
func NewTokenReporter ¶
func NewTokenReporter(sessionBudget int) *TokenReporter
type ToolCallInfo ¶
type ToolCallInfo = safety.ToolCallInfo
type ToolConfirmationRouter ¶
type ToolConfirmationRouter struct {
// Override allows per-tool risk overrides (tool name → risk level)
Override map[string]ToolRisk
}
ToolConfirmationRouter decides whether a tool call needs user approval based on the tool name and arguments. Designed for individual devs who want fast iteration without constant y/n prompts for safe operations.
func NewToolConfirmationRouter ¶
func NewToolConfirmationRouter() *ToolConfirmationRouter
NewToolConfirmationRouter creates a router with sensible defaults for coding.
func (*ToolConfirmationRouter) Classify ¶
func (r *ToolConfirmationRouter) Classify(toolName string, args map[string]interface{}) ToolRisk
Classify determines the risk level of a tool call.
func (*ToolConfirmationRouter) NeedsConfirmation ¶
func (r *ToolConfirmationRouter) NeedsConfirmation(toolName string, args map[string]interface{}) bool
NeedsConfirmation returns true if the tool call should prompt the user.
type ToolInfo ¶
type ToolInfo = intelligence.ToolInfo
type ToolInspector ¶
type ToolInspector struct {
Router *ToolConfirmationRouter
}
ToolInspector inspects tool calls before execution with confidence-based decisions. More nuanced than binary allow/deny — provides Allow, Deny, or RequireApproval.
func NewToolInspector ¶
func NewToolInspector() *ToolInspector
NewToolInspector creates an inspector backed by the confirmation router.
func (*ToolInspector) Inspect ¶
func (ti *ToolInspector) Inspect(toolName string, args map[string]interface{}) InspectionResult
Inspect analyzes a tool call and returns a decision with confidence.
type ToolSelection ¶
type ToolSelection = intelligence.ToolSelection
type ToolSelector ¶
type ToolSelector = intelligence.ToolSelector
type TrajectoryDistiller ¶
type TrajectoryDistiller struct {
// contains filtered or unexported fields
}
TrajectoryDistiller runs a task multiple times, summarizing what worked, and retrying with distilled knowledge from previous attempts.
func NewTrajectoryDistiller ¶
func NewTrajectoryDistiller(session *Session, maxRuns int) *TrajectoryDistiller
NewTrajectoryDistiller creates a new distiller wrapping the given session.
func (*TrajectoryDistiller) BestRun ¶
func (td *TrajectoryDistiller) BestRun(runs []TrajectoryRun) *TrajectoryRun
BestRun returns the run with Success=true (preferring earlier), or the highest-quality failure (most messages, fewest errors).
func (*TrajectoryDistiller) RunWithDistillation ¶
func (td *TrajectoryDistiller) RunWithDistillation(ctx context.Context, prompt string) (string, error)
RunWithDistillation executes the prompt, and if it fails, retries with accumulated trajectory summaries from prior attempts. Returns the best result.
type TrajectoryEvent ¶
type TrajectoryEvent = workflow.TrajectoryEvent
type TrajectoryInspector ¶
type TrajectoryInspector = workflow.TrajectoryInspector
type TrajectoryRun ¶
type TrajectoryRun struct {
ID int
Messages []types.EyrieMessage
Success bool
Summary string // distilled lessons from this run
Tokens int
}
TrajectoryRun records a single attempt at completing a task.
type TransferLearning ¶
type TransferLearning struct {
// contains filtered or unexported fields
}
TransferLearning enables cross-session knowledge transfer. Extracts generalizable patterns from completed sessions and applies them to new sessions on similar codebases.
func NewTransferLearning ¶
func NewTransferLearning() *TransferLearning
NewTransferLearning creates a store backed by ~/.hawk/transfer.json.
func (*TransferLearning) Apply ¶
func (tl *TransferLearning) Apply(language, taskDescription string) []TransferPattern
Apply finds patterns relevant to the current task.
func (*TransferLearning) FormatForPrompt ¶
func (tl *TransferLearning) FormatForPrompt(language, task string) string
FormatForPrompt returns transfer patterns as system prompt context.
func (*TransferLearning) Learn ¶
func (tl *TransferLearning) Learn(language, category, pattern, approach string)
Learn extracts a transferable pattern from a successful session.
type TransferPattern ¶
type TransferPattern struct {
Language string `json:"language"` // go, python, typescript, etc.
Category string `json:"category"` // "fix", "refactor", "feature", "test"
Pattern string `json:"pattern"` // generalized description
Approach string `json:"approach"` // what worked
Confidence float64 `json:"confidence"` // based on success rate
UsedCount int `json:"used_count"`
SuccessRate float64 `json:"success_rate"`
CreatedAt time.Time `json:"created_at"`
}
TransferPattern is a reusable pattern extracted from a successful session.
type TruncateStrategy ¶
type TruncateStrategy struct{}
TruncateStrategy is the fallback that does boundary-aware truncation.
func (*TruncateStrategy) Compact ¶
func (s *TruncateStrategy) Compact(ctx context.Context, sess *Session) (*CompactResult, error)
func (*TruncateStrategy) Name ¶
func (s *TruncateStrategy) Name() string
func (*TruncateStrategy) ShouldTrigger ¶
func (s *TruncateStrategy) ShouldTrigger(_ []types.EyrieMessage, tokenCount, threshold int) bool
type URLScraper ¶
type URLScraper = search.URLScraper
type UndoEntry ¶
type UndoEntry struct {
ID string
Timestamp time.Time
Description string
Files []FileSnapshot
ToolName string
ToolArgs map[string]interface{}
}
UndoEntry represents a single undoable operation that modified one or more files.
type UndoManager ¶
type UndoManager struct {
Stack []UndoEntry
MaxEntries int
// contains filtered or unexported fields
}
UndoManager tracks file modifications and allows granular rollback of changes.
func NewUndoManager ¶
func NewUndoManager() *UndoManager
NewUndoManager creates a new UndoManager with a default capacity of 100 entries.
func (*UndoManager) BeforeModify ¶
func (um *UndoManager) BeforeModify(path string) error
BeforeModify captures the current file state before modification. If the file does not exist, it marks the capture as WasNew so that undo will delete it.
func (*UndoManager) DiffEntry ¶
func (um *UndoManager) DiffEntry(entry *UndoEntry) string
DiffEntry shows what changed in the entry using a unified diff-like format.
func (*UndoManager) FormatHistory ¶
func (um *UndoManager) FormatHistory(entries []UndoEntry) string
FormatHistory formats undo entries for terminal display with relative timestamps and change statistics.
func (*UndoManager) History ¶
func (um *UndoManager) History(limit int) []UndoEntry
History returns the most recent entries up to limit, ordered from newest to oldest. If limit <= 0 or exceeds the stack size, all entries are returned.
func (*UndoManager) Peek ¶
func (um *UndoManager) Peek() *UndoEntry
Peek returns the last entry without removing it, or nil if the stack is empty.
func (*UndoManager) RecordChange ¶
func (um *UndoManager) RecordChange(description, toolName string, toolArgs map[string]interface{}, paths []string) string
RecordChange creates an UndoEntry from previously captured states, reads the new file content for each path, and appends the entry to the stack. It returns the generated entry ID. The stack is trimmed if it exceeds MaxEntries.
func (*UndoManager) Size ¶
func (um *UndoManager) Size() int
Size returns the number of entries currently on the stack.
func (*UndoManager) Undo ¶
func (um *UndoManager) Undo() (*UndoEntry, error)
Undo pops the last entry from the stack and restores all files to their original state. If a file WasNew, it is deleted. Returns the undone entry.
type UpdatePlan ¶
type UpdatePlan = project.UpdatePlan
type ValidationError ¶
ValidationError represents a single validation issue.
type ValidationResult ¶
type ValidationResult struct {
Valid bool
Errors []ValidationError
}
ValidationResult holds the outcome of validating a file.
func ValidateFile ¶
func ValidateFile(path string) *ValidationResult
ValidateFile determines the language from the file extension and runs the appropriate syntax checker.
type WatcherConfig ¶
type WatcherConfig = io.WatcherConfig
type WindowMessage ¶
type WindowMessage = history.WindowMessage
type WindowResult ¶
type WindowResult = history.WindowResult
type WorkflowEngine ¶
type WorkflowEngine = workflow.WorkflowEngine
type WorkflowResult ¶
type WorkflowResult = workflow.WorkflowResult
type WorkflowStep ¶
type WorkflowStep = workflow.WorkflowStep
type WorkspaceDiffReport ¶
type WorkspaceDiffReport = workflow.WorkspaceDiffReport
type WorkspaceState ¶
type WorkspaceState = workflow.WorkspaceState
Source Files
¶
- adaptive_prompt.go
- adaptive_system_prompt.go
- adversarial_review.go
- agent_intelligence.go
- agent_reexports.go
- agent_session_tool.go
- architect.go
- assumptions.go
- auto_commit.go
- away_summary.go
- background_runner.go
- belief.go
- brainstorm.go
- budget_allocator.go
- checkpoint.go
- client_interface.go
- coding_soul.go
- compact.go
- compact_api_engine.go
- compact_auto.go
- compact_micro_engine.go
- compact_reexports.go
- compact_session_memory_engine.go
- compact_split.go
- compact_strategy_engine.go
- control_reexports.go
- correct_course.go
- cost_reexports.go
- council.go
- degradation.go
- diff_reexports.go
- directive_scanner.go
- edit_strategy.go
- efficient_prompt.go
- engine.go
- engine_stage2_test_helpers.go
- engine_token_helpers.go
- errs_reexports.go
- event_bus.go
- experiment_loop.go
- hints_loader.go
- history_reexports.go
- integration.go
- intelligence_reexports.go
- investigate.go
- io_reexports.go
- large_response.go
- lifecycle_reexports.go
- llm_client.go
- memory_reexports.go
- multi_repo.go
- observability_reexports.go
- party_mode.go
- permission_session_methods.go
- planning_reexports.go
- pr_compression.go
- project_reexports.go
- provider_chat_client.go
- quality_gate.go
- quick_dev.go
- reflect.go
- review_reexports.go
- safety_reexports.go
- scaffold_reexports.go
- scale_adaptive.go
- search_reexports.go
- self_heal.go
- self_improve.go
- self_review.go
- semantic_diff.go
- session.go
- session_factory.go
- session_reexports.go
- session_services.go
- snapshot_cache.go
- source_roots.go
- spec.go
- stream.go
- stream_helpers.go
- stream_tool_exec.go
- streaming_reexports.go
- subagent_synthesis.go
- teach.go
- token_reexports.go
- tool_confirmation.go
- tool_inspector.go
- trajectory.go
- transfer.go
- undo.go
- validate.go
- validation_reexports.go
- workflow_reexports.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agent is the namespace for sub-agent orchestration types.
|
Package agent is the namespace for sub-agent orchestration types. |
|
Package code provides code-aware features: context extraction, lenses, actions, and explainer.
|
Package code provides code-aware features: context extraction, lenses, actions, and explainer. |
|
Package compact provides compaction strategies, types, and helpers for context-window management.
|
Package compact provides compaction strategies, types, and helpers for context-window management. |
|
Package control provides engine control-flow safety types — loop detection, stall detection, and backtracking.
|
Package control provides engine control-flow safety types — loop detection, stall detection, and backtracking. |
|
Package cost provides cost tracking, optimisation, and display for the hawk engine.
|
Package cost provides cost tracking, optimisation, and display for the hawk engine. |
|
Package ctxmgr is the namespace for context budget, decay, packing, providers, visualisation, and read-only context.
|
Package ctxmgr is the namespace for context budget, decay, packing, providers, visualisation, and read-only context. |
|
Package diff is the Stage-1 namespace for diff sandbox, staging, preview, summariser, test selector, and 3-way merge.
|
Package diff is the Stage-1 namespace for diff sandbox, staging, preview, summariser, test selector, and 3-way merge. |
|
Package docs provides documentation generation, external docs fetching, and doc updating types.
|
Package docs provides documentation generation, external docs fetching, and doc updating types. |
|
Package errs provides error context enrichment, grouping, learning, patterns, and recovery for the hawk engine.
|
Package errs provides error context enrichment, grouping, learning, patterns, and recovery for the hawk engine. |
|
Package git provides git-context enrichment and remote-forge integration.
|
Package git provides git-context enrichment and remote-forge integration. |
|
Package intelligence is the Stage-1 namespace for intent classification, capabilities, language support, tool selection.
|
Package intelligence is the Stage-1 namespace for intent classification, capabilities, language support, tool selection. |
|
Package io provides clipboard, AI watcher, file watcher, and cron scheduler types.
|
Package io provides clipboard, AI watcher, file watcher, and cron scheduler types. |
|
Package lifecycle is the Stage-1 namespace for session lifecycle, limits, timeouts, and sleep-time operations.
|
Package lifecycle is the Stage-1 namespace for session lifecycle, limits, timeouts, and sleep-time operations. |
|
Package memory provides knowledge, experience, and memory consolidation types.
|
Package memory provides knowledge, experience, and memory consolidation types. |
|
Package observability is the Stage-1 namespace for profiling, debug recording, structured logging, feedback.
|
Package observability is the Stage-1 namespace for profiling, debug recording, structured logging, feedback. |
|
Package planning is the Stage-1 namespace for task planning, decomposition, goals, and suggested tasks.
|
Package planning is the Stage-1 namespace for task planning, decomposition, goals, and suggested tasks. |
|
Package project is the Stage-1 namespace for project analysis, snapshots, impact analysis, dep updates, migrations, releases.
|
Package project is the Stage-1 namespace for project analysis, snapshots, impact analysis, dep updates, migrations, releases. |
|
Package prompt provides prompt-construction and prompt-optimisation types.
|
Package prompt provides prompt-construction and prompt-optimisation types. |
|
Package retry provides retry-queue and smart-retry types for the engine package.
|
Package retry provides retry-queue and smart-retry types for the engine package. |
|
Package review is the Stage-1 namespace for self-review / critique / quality scoring types in package engine.
|
Package review is the Stage-1 namespace for self-review / critique / quality scoring types in package engine. |
|
Package scaffold is the Stage-1 namespace for scaffolding, recipes, patterns, skills, and few-shot types.
|
Package scaffold is the Stage-1 namespace for scaffolding, recipes, patterns, skills, and few-shot types. |
|
Package search provides URL scraping, issue search, and research agent types.
|
Package search provides URL scraping, issue search, and research agent types. |
|
Package session is the Stage-1 namespace for session-lifecycle types in package engine.
|
Package session is the Stage-1 namespace for session-lifecycle types in package engine. |
|
Package streaming is the Stage-1 namespace for response caching, formatting, stream optimisation, thinking protocol, and steering.
|
Package streaming is the Stage-1 namespace for response caching, formatting, stream optimisation, thinking protocol, and steering. |
|
Package token is the Stage-1 namespace for token-related types and functions in package engine.
|
Package token is the Stage-1 namespace for token-related types and functions in package engine. |
|
Package validation is the Stage-1 namespace for generated-code validation, schema validation, test loops, and lint loops.
|
Package validation is the Stage-1 namespace for generated-code validation, schema validation, test loops, and lint loops. |
|
Package workflow is the Stage-1 namespace for workflow + workspace + trajectory types in package engine.
|
Package workflow is the Stage-1 namespace for workflow + workspace + trajectory types in package engine. |