engine

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 49 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultExploreTurns = 15
	DefaultGeneralTurns = 20
	MaxAgentDepth       = 2
)

Sub-agent budget defaults per mode.

View Source
const (
	IntentCodeWrite  = "code_write"
	IntentCodeFix    = "code_fix"
	IntentCodeReview = "code_review"
	IntentExplain    = "explain"
	IntentRefactor   = "refactor"
	IntentTest       = "test"
	IntentSearch     = "search"
	IntentConfig     = "config"
	IntentGit        = "git"
	IntentQuestion   = "question"
)

Intent category constants.

View Source
const (
	FieldTool     = "tool"
	FieldFile     = "file"
	FieldDuration = "duration"
	FieldTokens   = "tokens"
	FieldModel    = "model"
	FieldProvider = "provider"
	FieldError    = "error"
	FieldCost     = "cost"
)

Predefined field keys for structured logging.

View Source
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.

View Source
const DefaultMaxAge = 24 * time.Hour

DefaultMaxAge is the default maximum age of cache entries.

View Source
const DefaultMaxEntries = 1000

DefaultMaxEntries is the default maximum number of cache entries.

View Source
const DefaultProjectSnapshotTTL = 10 * time.Second

DefaultProjectSnapshotTTL is the default time-to-live for a cached project snapshot. Matches herm's 10s TTL to avoid redundant shell commands when spawning multiple sub-agents against an unchanged repo.

View Source
const DefaultSnapshotTTL = 10 * time.Second

DefaultSnapshotTTL is the default time-to-live for snapshot cache entries.

View Source
const DoomLoopThreshold = 3

DoomLoopThreshold is the number of repeated patterns before escalation (matches OpenCode).

View Source
const MaxAutoFixRetries = 3

MaxAutoFixRetries is the maximum number of times to retry auto-fixing a file.

View Source
const SynthesisPrompt = "" /* 131-byte string literal not displayed */

SynthesisPrompt is appended when forcing a sub-agent to summarize.

Variables

View Source
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.

View Source
var ExploreTools = []string{
	"Glob", "Grep", "Read", "Bash", "LS",
}

ExploreTools are the read-only tools available to explore-mode sub-agents.

View Source
var HintsFilenames = []string{".hawkhints", "AGENTS.md", ".hawk/AGENTS.md"}

HintsFilenames are the files hawk auto-loads for project context.

View Source
var ModeToolAllowlist = map[SubAgentMode][]string{
	SubAgentExplore: {
		"Read",
		"Grep",
		"Glob",
		"LS",
		"Bash",
	},
	SubAgentGeneral: {
		"Read",
		"Grep",
		"Glob",
		"LS",
		"Bash",
		"Write",
		"Edit",
		"Agent",
		"MultiAgent",
	},
}

ModeToolAllowlist maps each sub-agent mode to the tool names it can use. Explore mode is restricted to read-only tools; general mode has full access.

View Source
var ProjectContextFiles = []string{
	".hawk/project-context.md",
	".hawk/conventions.md",
	".hawk/architecture.md",
	".hawk/debt.md",
}

ProjectContextFiles are the files hawk auto-loads for project context.

View Source
var ReviewCategories = []string{
	"edge-cases",
	"error-handling",
	"security",
	"performance",
	"logic",
}

ReviewCategories are the areas the adversarial reviewer must check.

View Source
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.

View Source
var TaskToolMap = map[string][]string{
	"read code":  {"Read", "Grep", "Glob", "LS"},
	"write code": {"Read", "Edit", "Write", "Bash"},
	"debug":      {"Read", "Grep", "Bash", "Edit"},
	"search":     {"Grep", "Glob", "WebSearch"},
	"test":       {"Bash", "Read", "Write"},
	"review":     {"Read", "Grep", "Glob"},
	"refactor":   {"Read", "Edit", "Write", "Grep", "Bash"},
	"deploy":     {"Bash", "Read", "Write"},
}

TaskToolMap provides built-in mappings from task intents to tool names.

Functions

func AdaptiveSizes added in v0.2.0

func AdaptiveSizes(messages []WindowMessage, budget int) (head, tail int)

AdaptiveSizes dynamically determines head and tail sizes based on token budget. More budget yields a larger tail (recent context matters more). Always returns at least 2 head + 4 tail.

func ApplyFix added in v0.2.0

func ApplyFix(action CodeAction, content string) (string, error)

ApplyFix applies the suggested fix to the file content at the correct line.

func AutoFix added in v0.2.0

func AutoFix(code string, issues []GenIssue) string

AutoFix applies auto-fixable issues to the code and returns the corrected version.

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 added in v0.2.0

func BrainstormPrompt(phase BrainstormPhase, topic string, context string) string

BrainstormPrompt returns the facilitation prompt for each phase.

func BuildCompactPrompt

func BuildCompactPrompt(variant CompactVariant) string

BuildCompactPrompt constructs the full compaction prompt for LLM-based summarization.

func BuildDependencyGraph added in v0.2.0

func BuildDependencyGraph(projectDir string) map[string][]string

BuildDependencyGraph scans the project directory and builds a reverse import graph mapping packages to their dependents.

func BuildEditorPrompt added in v0.2.0

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 BuildFormPrompt added in v0.2.0

func BuildFormPrompt(action *ActionRequired) string

BuildFormPrompt renders a human-readable form prompt for an ActionRequired.

func BuildImportGraph added in v0.2.0

func BuildImportGraph(projectDir string) map[string][]string

BuildImportGraph parses Go source files to build a reverse dependency graph. Package A imports B means B's map entry includes A.

func BuildPrompt added in v0.2.0

func BuildPrompt(comment AIComment) string

BuildPrompt constructs a prompt for the AI agent based on the detected comment.

func BuildRejectionMessage added in v0.2.0

func BuildRejectionMessage(result *GroundingResult) string

BuildRejectionMessage constructs a human-readable message explaining which claims in the response were not supported by context.

func BuildSchemaPrompt added in v0.2.0

func BuildSchemaPrompt(schema *Schema) string

BuildSchemaPrompt generates LLM instructions describing the expected output format.

func BuildSearchContext added in v0.2.0

func BuildSearchContext(similar []*SimilarIssue) string

BuildSearchContext formats similar issues as context for agent injection. This is suitable for including in LLM prompts to provide relevant historical context.

func BuildTestFeedback added in v0.2.0

func BuildTestFeedback(result *TestResult, editedFiles []string) string

BuildTestFeedback formats test failures into agent-readable feedback that can be injected into the next agent iteration for self-correction.

func BuiltinWorkflows added in v0.2.0

func BuiltinWorkflows() map[string]*Workflow

BuiltinWorkflows returns the built-in workflow templates.

func BumpVersion added in v0.2.0

func BumpVersion(current string, changes []ChangeEntry) string

BumpVersion determines the next version based on the changes. Breaking changes cause a major bump, features cause a minor bump, and fixes/other changes cause a patch bump.

func CheckpointPrompts added in v0.2.0

func CheckpointPrompts(phase CheckpointPhase, files []string) string

CheckpointPrompts returns the system prompt for each checkpoint phase.

func ClassifyRisk added in v0.2.0

func ClassifyRisk(changes []SemanticChange) string

ClassifyRisk determines the overall risk level based on a set of semantic changes.

func ClassifyTaskComplexity added in v0.2.0

func ClassifyTaskComplexity(task string) string

ClassifyTaskComplexity categorizes a task description into a complexity tier.

func ClassifyUpdate added in v0.2.0

func ClassifyUpdate(current, latest string) string

ClassifyUpdate compares two semver strings and returns "major", "minor", or "patch".

func CollapseRepeatedMessages

func CollapseRepeatedMessages(msgs []client.EyrieMessage) []client.EyrieMessage

CollapseRepeatedMessages finds and collapses similar consecutive messages to save context tokens. It collapses:

  • 3+ consecutive tool_results with similar content into a summary
  • Repeated error messages into a count

func CompareApproaches added in v0.2.0

func CompareApproaches(solutions []Solution) string

CompareApproaches analyzes how different attempts approached the problem and returns a human-readable comparison.

func CompareReports added in v0.2.0

func CompareReports(before, after *WorkspaceDiffReport) string

CompareReports shows the differences between two report snapshots.

func CompressForContext

func CompressForContext(text string, budget int) (string, int)

CompressForContext compresses text to fit within a token budget, returning the compressed text and the final token count.

func ComputeGradientPrompt added in v0.2.0

func ComputeGradientPrompt(paramName, currentValue, feedback string, examples []string) string

ComputeGradient generates a textual gradient (improvement direction) for a parameter.

func CorrectCoursePrompt added in v0.2.0

func CorrectCoursePrompt(originalIntent, currentState, problem string) string

CorrectCoursePrompt generates a prompt to diagnose where things went wrong.

func CountTokens

func CountTokens(text string) int

CountTokens returns a precise BPE-based token count for the given text.

func CountTokensFast

func CountTokensFast(text string) int

CountTokensFast returns a fast heuristic token estimate for the given text.

func DecomposePrompt

func DecomposePrompt() string

DecomposePrompt returns a system prompt that instructs the LLM to break a task into numbered subtasks with titles, descriptions, and file lists.

func DefaultCouncilModels

func DefaultCouncilModels() []string

DefaultCouncilModels returns diverse models from different providers.

func DefaultIgnorePatterns added in v0.2.0

func DefaultIgnorePatterns() []string

DefaultIgnorePatterns returns standard patterns to ignore during watching.

func DefaultLintCommands added in v0.2.0

func DefaultLintCommands() map[string]string

DefaultLintCommands returns the standard set of lint commands for common languages.

func DefaultScoreFn added in v0.2.0

func DefaultScoreFn(solution string) float64

DefaultScoreFn combines length and completeness scoring.

func DefaultSoulPath added in v0.2.0

func DefaultSoulPath() string

DefaultSoulPath returns the path to the soul file.

func DefaultTestCommands added in v0.2.0

func DefaultTestCommands() map[string]string

DefaultTestCommands returns the standard set of test commands for common project types.

func DefaultValidateCmd added in v0.2.0

func DefaultValidateCmd(dir string) string

DefaultValidateCmd detects the project type and returns the appropriate test command.

func DegradationTimeout added in v0.2.0

func DegradationTimeout(turnCount int) time.Duration

DegradationTimeout returns a suggested timeout based on turn count.

func DescribeControlFlow added in v0.2.0

func DescribeControlFlow(funcBody string) string

DescribeControlFlow analyzes function body text and returns a human-readable description of its control flow pattern.

func DetectArchitecture added in v0.2.0

func DetectArchitecture(dir string) string

DetectArchitecture determines the architectural style of a project by examining its directory structure.

func DetectContentType added in v0.2.0

func DetectContentType(content string) string

DetectContentType classifies clipboard content into a category. Returns one of: "code", "diff", "url", "path", "error", "text".

func DetectGenerated added in v0.2.0

func DetectGenerated(path string) bool

DetectGenerated returns true if the path matches known generated/lock file patterns.

func DetectLanguage added in v0.2.0

func DetectLanguage(code string) string

DetectLanguage performs heuristic language detection from code content. Returns the detected language name or "" if unknown.

func DetectProvider added in v0.2.0

func DetectProvider(projectDir string) (string, string, string)

DetectProvider parses .git/config or uses gh to detect provider/owner/repo.

func DetectSideEffects added in v0.2.0

func DetectSideEffects(funcBody string) []string

DetectSideEffects analyzes function body text and returns a list of detected side effects such as file I/O, network calls, goroutine spawning, etc.

func DetectTestCommand added in v0.2.0

func DetectTestCommand(projectDir string) string

DetectTestCommand inspects the project directory for known build/config files and returns the appropriate test command. Returns "" if no project type is detected.

func DiffPrompts added in v0.2.0

func DiffPrompts(old, new string) string

DiffPrompts shows what changed between two prompt versions line by line.

func DirectivePrompt added in v0.2.0

func DirectivePrompt(d Directive) string

DirectivePrompt formats a directive as a prompt for the LLM.

func DynamicMaxTokens

func DynamicMaxTokens(messages []client.EyrieMessage, contextSize int, taskType string) int

DynamicMaxTokens calculates the optimal max_tokens for a request based on: - Whether the last few turns were tool-call-heavy (reduce to 4096) - Whether the user asked a question expecting text (8192) - Whether this is a code generation task (16384) - The remaining context budget (don't exceed model's limit)

Research basis: Output tokens are 3-5x more expensive than input tokens. Most tool-call turns only need 200-2000 tokens of output.

func EditStrategyPrompt added in v0.2.0

func EditStrategyPrompt(strategy EditStrategy) string

EditStrategyPrompt returns instructions for the LLM based on the selected strategy.

func EstimateDiffTokens added in v0.2.0

func EstimateDiffTokens(diff string) int

EstimateDiffTokens provides a rough token count for a diff string. Uses the heuristic of ~4 characters per token (common for code).

func EstimateSavings added in v0.2.0

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 added in v0.2.0

func EstimateStringTokens(content string) int

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 EstimateTimeSaved added in v0.2.0

func EstimateTimeSaved(totalTests, selectedTests int) string

EstimateTimeSaved returns a human-readable string estimating time savings.

func EstimateTokenSavings added in v0.2.0

func EstimateTokenSavings(original, formatted string) int

EstimateTokenSavings estimates the difference in token count between original and formatted text. Uses a simple ~4 chars per token heuristic.

func EstimateTokens

func EstimateTokens(msgs []client.EyrieMessage) int

EstimateTokens provides a rough token estimate for messages.

func EstimateTokensFromContent added in v0.2.0

func EstimateTokensFromContent(content string) int

EstimateTokensFromContent provides a quick token estimate for content. Uses len/4 for English text, len/3 for code-heavy content.

func EvalCondition added in v0.2.0

func EvalCondition(condition string, vars map[string]string) bool

EvalCondition evaluates a simple condition expression with variable substitution. Supports: == != > < >= <= comparisons after substitution.

func ExperimentPrompt added in v0.2.0

func ExperimentPrompt(iteration int, validateCmd string, history []ExperimentResult, lastOutput string) string

ExperimentPrompt generates the prompt for the LLM to suggest the next change.

func ExtractCode added in v0.2.0

func ExtractCode(body string, rawURL string) string

ExtractCode wraps raw code content in a fenced code block with language detection.

func ExtractCodeFromOutput added in v0.2.0

func ExtractCodeFromOutput(text string, language string) (string, error)

ExtractCodeFromOutput finds code blocks in LLM output.

func ExtractHTML added in v0.2.0

func ExtractHTML(body string) (title, content string)

ExtractHTML strips tags and extracts readable text from HTML.

func ExtractJSON added in v0.2.0

func ExtractJSON(body string) string

ExtractJSON pretty-prints JSON and truncates arrays to 5 elements.

func ExtractJSONFromOutput added in v0.2.0

func ExtractJSONFromOutput(text string) (string, error)

ExtractJSONFromOutput finds JSON content in LLM output text.

func ExtractKeyFacts added in v0.2.0

func ExtractKeyFacts(messages []CompressMessage) []string

ExtractKeyFacts pulls out important facts from a group of messages: decisions made, files modified, errors encountered and resolved, conventions established.

func ExtractMarkdown added in v0.2.0

func ExtractMarkdown(body string) string

ExtractMarkdown returns the markdown body, truncated if too long.

func ExtractPattern added in v0.2.0

func ExtractPattern(errorMsg string) string

ExtractPattern generalizes a specific error message into a regex pattern.

func FilterRelevantOutput added in v0.2.0

func FilterRelevantOutput(output string, maxChars int) string

FilterRelevantOutput keeps only failure-related lines from test output, removes noise (progress bars, timing info, success messages), and truncates to maxChars.

func FilterToolsForMode added in v0.2.0

func FilterToolsForMode(mode SubAgentMode, available []string) []string

FilterToolsForMode returns only the tool names from available that are permitted for the given mode. Tools not in the allowlist are excluded.

func FixCodeFences added in v0.2.0

func FixCodeFences(text string) string

FixCodeFences counts opening/closing ``` and adds missing ones. It also ensures language labels on opening fences.

func FixMarkdown added in v0.2.0

func FixMarkdown(text string) string

FixMarkdown fixes broken markdown links and unclosed bold/italic.

func FormatAnalysis added in v0.2.0

func FormatAnalysis(analysis *ProjectAnalysis) string

FormatAnalysis produces a concise summary string from a ProjectAnalysis.

func FormatAnnotations added in v0.2.0

func FormatAnnotations(annotations []*Annotation) string

FormatAnnotations formats annotations for display.

func FormatAsMarkdown added in v0.2.0

func FormatAsMarkdown(report *WorkspaceDiffReport) string

FormatAsMarkdown renders the report as a markdown document suitable for PR descriptions.

func FormatAsTerminal added in v0.2.0

func FormatAsTerminal(report *WorkspaceDiffReport) string

FormatAsTerminal renders the report with ANSI color codes for terminal display.

func FormatAssessment added in v0.2.0

func FormatAssessment(assessment *RiskAssessment) string

FormatAssessment produces a human-readable formatted string of the assessment.

func FormatCIStatus added in v0.2.0

func FormatCIStatus(status *CIStatus) string

FormatCIStatus formats a CIStatus for terminal display.

func FormatChanges added in v0.2.0

func FormatChanges(result *FormattedResponse) string

FormatChanges returns a human-readable summary of the changes made.

func FormatCommandSuggestions added in v0.2.0

func FormatCommandSuggestions(suggestions []*CommandSuggestion) string

FormatCommandSuggestions formats a list of command suggestions for display.

func FormatCompactSummary

func FormatCompactSummary(raw string) string

FormatCompactSummary strips the <analysis> drafting block and extracts the <summary> content.

func FormatCompressed added in v0.2.0

func FormatCompressed(result *CompressionResult) string

FormatCompressed produces a human-readable summary of the compression result.

func FormatCompressedPR added in v0.2.0

func FormatCompressedPR(pr *CompressedPR) string

FormatCompressed produces a human-readable summary of the compressed PR diff.

func FormatConflictMarkers added in v0.2.0

func FormatConflictMarkers(conflict Diff3Conflict) string

FormatConflictMarkers formats a conflict with standard diff3 markers.

func FormatConsensus added in v0.2.0

func FormatConsensus(result *ConsensusResult) string

FormatConsensus produces a human-readable summary of the consensus result.

func FormatContext added in v0.2.0

func FormatContext(ctx *CodeContext) string

FormatContext produces a markdown-formatted representation of the code context.

func FormatContextItems added in v0.2.0

func FormatContextItems(items []ContextItem) string

FormatContextItems formats context items into a system prompt section.

func FormatCostDisplay

func FormatCostDisplay(totalUSD float64) string

FormatCostDisplay returns a compact cost string for the status bar.

func FormatDiff3Result added in v0.2.0

func FormatDiff3Result(result *Diff3Result) string

FormatDiff3Result produces a human-readable summary of a Diff3Result.

func FormatError added in v0.2.0

func FormatError(enriched *EnrichedError) string

FormatError formats an EnrichedError into a human-readable multi-line string with visual separators and structured sections.

func FormatEvents added in v0.2.0

func FormatEvents(events []FileEvent) string

FormatEvents produces a human-readable summary of file events.

func FormatExplanation added in v0.2.0

func FormatExplanation(exp *CodeExplanation) string

FormatExplanation renders a CodeExplanation into a human-readable markdown-style string.

func FormatForCommit added in v0.2.0

func FormatForCommit(report *WorkspaceDiffReport) string

FormatForCommit renders the report in a compact format suitable for a commit message body.

func FormatForContext added in v0.2.0

func FormatForContext(content string, contentType string) string

FormatForContext wraps content appropriately for injection into agent context based on its detected content type.

func FormatGateResults added in v0.2.0

func FormatGateResults(results []GateResult) string

FormatGateResults renders gate results for display.

func FormatGroundingResult added in v0.2.0

func FormatGroundingResult(result *GroundingResult) string

FormatGroundingResult returns a human-readable summary of the grounding analysis.

func FormatHealResult added in v0.2.0

func FormatHealResult(result *HealResult) string

FormatResult produces a human-readable summary of a healing session.

func FormatImpact added in v0.2.0

func FormatImpact(analysis *ImpactAnalysis) string

FormatImpact produces a human-readable formatted report of the impact analysis.

func FormatInline added in v0.2.0

func FormatInline(comments []ReviewComment) string

FormatInline produces GitHub-style inline review comments.

func FormatIntent added in v0.2.0

func FormatIntent(intent *Intent) string

FormatIntent returns a human-readable summary of the classified intent.

func FormatIssueResults added in v0.2.0

func FormatIssueResults(similar []*SimilarIssue) string

FormatIssueResults produces a human-readable summary of similar issue search results.

func FormatIssues added in v0.2.0

func FormatIssues(issues []GitIssue) string

FormatIssues formats a slice of issues for terminal display.

func FormatLanguages added in v0.2.0

func FormatLanguages(configs []*LanguageConfig) string

FormatLanguages produces a human-readable summary of detected languages. The first language is marked as "(primary)".

func FormatLenses added in v0.2.0

func FormatLenses(file string, lenses []CodeLens) string

FormatLenses produces a human-readable summary of code lenses.

func FormatOutdated added in v0.2.0

func FormatOutdated(deps []Dependency) string

FormatOutdated formats a list of outdated dependencies into a human-readable report.

func FormatPRs added in v0.2.0

func FormatPRs(prs []PullRequest) string

FormatPRs formats a slice of pull requests for terminal display.

func FormatPartyTurn added in v0.2.0

func FormatPartyTurn(p Persona, content string) string

FormatTurn renders a persona's contribution.

func FormatPattern added in v0.2.0

func FormatPattern(p *PromptPattern) string

FormatPattern returns a human-readable string representation of a pattern.

func FormatPlan added in v0.2.0

func FormatPlan(plan *UpdatePlan) string

FormatPlan formats an UpdatePlan into a human-readable string.

func FormatPrediction added in v0.2.0

func FormatPrediction(pred *Prediction, model string) string

FormatPrediction returns a human-readable summary of a token prediction.

func FormatPrompt added in v0.2.0

func FormatPrompt(base string, sections []PromptSection) string

FormatPrompt assembles the base prompt and included sections into a final string.

func FormatPromptExamples added in v0.2.0

func FormatPromptExamples(examples []PromptExample) string

FormatPromptExamples renders selected examples as prompt context.

func FormatReleaseNotes added in v0.2.0

func FormatReleaseNotes(release *Release) string

FormatReleaseNotes produces GitHub-style release notes with sections.

func FormatReport added in v0.2.0

func FormatReport(report *ReviewReport) string

FormatReport produces a human-readable summary of a review report.

func FormatResponse added in v0.2.0

func FormatResponse(response *FormResponse) string

FormatResponse renders a FormResponse as a human-readable string.

func FormatResult added in v0.2.0

func FormatResult(result *WorkflowResult) string

FormatResult produces a human-readable summary of a workflow result.

func FormatResults

func FormatResults(results []BackgroundResult) string

FormatResults formats background results for injection into the agent context.

func FormatReview added in v0.2.0

func FormatReview(result *ReviewResult) string

FormatReview produces a formatted summary of the review result.

func FormatSelection added in v0.2.0

func FormatSelection(selected *SelectedTests, changedFiles []string, language string, totalTests int) string

FormatSelection produces a human-readable summary of the test selection.

func FormatSelfAssessment added in v0.2.0

func FormatSelfAssessment(a *Assessment) string

FormatSelfAssessment produces a human-readable summary of an assessment.

func FormatSkill added in v0.2.0

func FormatSkill(skill *Skill) string

FormatSkill produces a human-readable representation of a skill.

func FormatSuggestions added in v0.2.0

func FormatSuggestions(actions []CodeAction, maxDisplay int) string

FormatSuggestions formats code actions for display.

func FormatTasks added in v0.2.0

func FormatTasks(tasks []*SuggestedTask) string

FormatTasks formats a list of suggested tasks for display.

func FormatTeachingMoment

func FormatTeachingMoment(action, reasoning string) string

FormatTeachingMoment wraps agent output with teaching context.

func FormatToolSelection added in v0.2.0

func FormatToolSelection(task string, selection *ToolSelection) string

FormatToolSelection returns a formatted string representation of a ToolSelection.

func FormatValidation added in v0.2.0

func FormatValidation(v *GenValidation) string

FormatValidation renders a GenValidation into a human-readable string.

func FormatViolations added in v0.2.0

func FormatViolations(violations []Violation) string

FormatViolations formats a list of violations for display.

func FormatWindow added in v0.2.0

func FormatWindow(result *WindowResult) string

FormatWindow returns a human-readable representation of the window result.

func GenerateChangelog added in v0.2.0

func GenerateChangelog(release *Release) string

GenerateChangelog produces a markdown-formatted changelog for a release.

func GenerateMitigations added in v0.2.0

func GenerateMitigations(assessment *RiskAssessment) []string

GenerateMitigations produces mitigation suggestions based on the assessment.

func GenerateOnboardingDoc added in v0.2.0

func GenerateOnboardingDoc(analysis *ProjectAnalysis) string

GenerateOnboardingDoc produces a human-readable onboarding document from the analysis.

func GenerateREADME added in v0.2.0

func GenerateREADME(doc *ProjectDoc) string

GenerateREADME generates a README.md with description, install, quick start, and API overview.

func GenerateSummary added in v0.2.0

func GenerateSummary(diff *SemanticDiff) string

GenerateSummary produces a human-readable summary of a semantic diff analysis.

func GenerateTestCommand added in v0.2.0

func GenerateTestCommand(selected *SelectedTests, language string) string

GenerateTestCommand produces a runnable test command for the selected tests.

func HashPrompt added in v0.2.0

func HashPrompt(prompt string) string

HashPrompt returns a SHA-256 hash of the normalized prompt. Normalization: lowercase, collapse whitespace.

func ImplementFromSpecPrompt added in v0.2.0

func ImplementFromSpecPrompt(spec *Spec) string

ImplementFromSpecPrompt generates the implementation prompt constrained by the spec.

func InferPurpose added in v0.2.0

func InferPurpose(name string, params, returns []string) string

InferPurpose infers the purpose of a function from its name, parameter types, and return types using heuristic pattern matching.

func InitSoulPrompt added in v0.2.0

func InitSoulPrompt() string

InitSoulPrompt returns a prompt to generate an initial soul.md.

func InvestigatePrompt added in v0.2.0

func InvestigatePrompt(phase InvestigatePhase, context string) string

InvestigatePrompt returns the prompt for each investigation phase.

func IsDue added in v0.2.0

func IsDue(job *CronJob, now time.Time) bool

IsDue returns true if the given job should run at the specified time.

func LCS added in v0.2.0

func LCS(a, b []string) []string

LCS computes the Longest Common Subsequence of two string slices.

func LearnPrompt added in v0.2.0

func LearnPrompt(context string) string

LearnPrompt generates a prompt to extract lessons from a failed interaction.

func ListPersonas added in v0.2.0

func ListPersonas() string

ListPersonas returns a formatted list of available personas.

func LoadCostHistory

func LoadCostHistory() ([]analytics.CostEntry, error)

LoadHistory reads all historical cost entries from the JSONL file.

func MatchesPattern added in v0.2.0

func MatchesPattern(path string, patterns []string) bool

MatchesPattern checks if a path matches any of the given glob patterns.

func MergeClean added in v0.2.0

func MergeClean(base, ours, theirs string) (string, bool)

MergeClean performs a three-way merge and returns the merged string and whether the merge was clean (no conflicts).

func MergeSynthesisPrompt added in v0.2.0

func MergeSynthesisPrompt(subtasks []SubTask, results map[string]string) string

MergeSynthesisPrompt generates a prompt to merge results from parallel agents.

func ModelPricing

func ModelPricing(modelName string) (inputPricePerM, outputPricePerM float64)

ModelPricing returns input/output price per million tokens for a model.

func NextRunTime added in v0.2.0

func NextRunTime(expr *CronExpr, after time.Time) time.Time

NextRunTime calculates the next time after `after` that matches the cron expression.

func NormalizeError added in v0.2.0

func NormalizeError(msg string) string

NormalizeError strips file paths, line numbers, and specific values from an error message, keeping only the structural pattern.

func NormalizeLists added in v0.2.0

func NormalizeLists(text string) string

NormalizeLists converts mixed bullet styles to consistent dashes and ensures proper indentation.

func OptimizePrompt added in v0.2.0

func OptimizePrompt(ctx context.Context, llm LLMClient, model string, po *PromptOptimizer, paramName, feedback string) (string, error)

OptimizePrompt is the main entry point — given a failing parameter, generate an improved version.

func PackingReport added in v0.2.0

func PackingReport(result *PackingResult, strategy PackingStrategy, totalMessages int, mustKeepCount int) string

PackingReport generates a human-readable report of the packing result.

func PairwiseSimilarity added in v0.2.0

func PairwiseSimilarity(a, b string) float64

PairwiseSimilarity computes the Jaccard similarity between two strings based on their word sets.

func ParseFailedTests added in v0.2.0

func ParseFailedTests(output string, language string) []string

ParseFailedTests extracts failed test names from test output based on language.

func ParseSemver added in v0.2.0

func ParseSemver(version string) (major, minor, patch int, err error)

ParseSemver parses a version string into major, minor, patch components. It handles versions with or without a "v" prefix.

func QuickDevClarifyPrompt added in v0.2.0

func QuickDevClarifyPrompt(userInput string) string

QuickDevClarifyPrompt returns the prompt for intent clarification.

func QuickDevPresentPrompt added in v0.2.0

func QuickDevPresentPrompt() string

QuickDevPresentPrompt returns the prompt for presenting results.

func QuickDevReviewPrompt added in v0.2.0

func QuickDevReviewPrompt(filesChanged []string) string

QuickDevReviewPrompt returns the prompt for self-review after implementation.

func ReadClipboard added in v0.2.0

func ReadClipboard() (string, error)

ReadClipboard reads the current system clipboard content. It uses platform-specific commands:

  • macOS: pbpaste
  • Linux: xclip -selection clipboard -o (falls back to xsel)
  • Windows: powershell Get-Clipboard

func ReflectPrompt added in v0.2.0

func ReflectPrompt(sessionSummary string) string

ReflectPrompt generates a prompt for session self-assessment.

func RemainingTime

func RemainingTime(ctx context.Context) string

RemainingTime returns a formatted remaining-time string derived from the context deadline set by WithTimeout. If no deadline is set it returns an empty string.

func RemoveComment added in v0.2.0

func RemoveComment(file string, line int, marker string) error

RemoveComment removes the AI comment from the specified file at the given line. It matches the marker string to ensure the correct line is removed.

func RemoveFluff added in v0.2.0

func RemoveFluff(text string) string

RemoveFluff strips filler phrases that waste tokens.

func RenderHTML added in v0.2.0

func RenderHTML(doc *ProjectDoc) string

RenderHTML generates a styled HTML document with navigation sidebar.

func RenderMarkdown added in v0.2.0

func RenderMarkdown(doc *ProjectDoc) string

RenderMarkdown generates a full markdown document from a ProjectDoc.

func RenderTree added in v0.2.0

func RenderTree(files []string) string

RenderTree creates an ASCII tree visualization from a list of file paths.

func RenderUnified added in v0.2.0

func RenderUnified(change *FileChange) string

RenderUnified renders a single FileChange in standard unified diff format.

func RepairJSON added in v0.2.0

func RepairJSON(broken string) (string, error)

RepairJSON attempts to fix common LLM JSON mistakes.

func ReviewPrompt added in v0.2.0

func ReviewPrompt(files []string) string

ReviewPrompt generates the adversarial review system prompt.

func ScoreByCompleteness added in v0.2.0

func ScoreByCompleteness(content string) float64

ScoreByCompleteness scores based on structural indicators: code blocks, file mentions, numbered steps.

func ScoreByLength added in v0.2.0

func ScoreByLength(content string) float64

ScoreByLength scores content based on reasonable length. Too short or too long content gets penalized.

func ScoreImportance added in v0.2.0

func ScoreImportance(msg CompressMessage, position int, total int) float64

ScoreImportance assigns an importance score to a message based on its content and position.

func ShouldApply added in v0.2.0

func ShouldApply(messages []WindowMessage, maxTokens int) bool

ShouldApply returns true if the total token count of messages exceeds maxTokens, indicating the window strategy should be applied.

func ShouldCache added in v0.2.0

func ShouldCache(prompt string) bool

ShouldCache determines whether a prompt should be cached. It skips prompts referencing current time, volatile file contents, or one-off questions.

func ShouldProceed added in v0.2.0

func ShouldProceed(assessment *RiskAssessment) bool

ShouldProceed returns false for "critical" risk level, indicating the change should not proceed without further review.

func ShouldRetry added in v0.2.0

func ShouldRetry(solutions []Solution) bool

ShouldRetry determines whether additional attempts should be made. Returns true if the best score so far is below 0.7.

func ShouldUseArchitect added in v0.2.0

func ShouldUseArchitect(prompt string, messageCount int) bool

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 added in v0.2.0

func SpecGeneratePrompt(intent string) string

SpecGeneratePrompt creates the prompt to generate a spec from user intent.

func StripAnnotations added in v0.2.0

func StripAnnotations(content string) string

StripAnnotations removes all [hawk:*] comment lines from content. Used before commit/save to keep annotations agent-only.

func SubstituteVars added in v0.2.0

func SubstituteVars(template string, vars map[string]string) string

SubstituteVars replaces {{.varName}} placeholders in the template with values from vars.

func SuggestFiles added in v0.2.0

func SuggestFiles(projectDir string) []string

SuggestFiles returns a list of commonly useful context files that exist in the given directory.

func SuggestResolution added in v0.2.0

func SuggestResolution(similar []*SimilarIssue) string

SuggestResolution generates a resolution suggestion based on similar closed issues.

func SummarizeClipboard added in v0.2.0

func SummarizeClipboard(content string, maxChars int) string

SummarizeClipboard truncates large clipboard content for display, showing the first and last few lines with an omission indicator.

func SummarizeDropped added in v0.2.0

func SummarizeDropped(dropped []ScoredMessage) string

SummarizeDropped creates a brief summary of what was dropped.

func SummarizeTrajectory

func SummarizeTrajectory(messages []client.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 added in v0.2.0

func SynthesizeSubAgent(ctx context.Context, llm LLMClient, model string, conversationSoFar []client.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

func TeachPromptAugment(depth int) string

TeachPromptAugment returns a system prompt addition that instructs the agent to explain its reasoning at the given depth level.

func TimeoutMessage

func TimeoutMessage(elapsed time.Duration) string

TimeoutMessage returns a user-friendly message when the time budget is exhausted.

func TokenEstimate added in v0.2.0

func TokenEstimate(content string) int

TokenEstimate provides a quick token count approximation: len(content) / 4.

func TruncateHunks added in v0.2.0

func TruncateHunks(diff string, maxTokens int) string

TruncateHunks keeps the first and last hunks of a diff and drops the middle, inserting a note about omitted hunks.

func UpdateVersionFile added in v0.2.0

func UpdateVersionFile(version, filePath string) error

UpdateVersionFile updates the version string in the given file. Supports Go constant files, package.json, and Cargo.toml formats.

func Validate added in v0.2.0

func Validate(action *ActionRequired, response *FormResponse) []string

Validate checks a FormResponse against the ActionRequired field specs. It returns a slice of validation error strings (empty if valid).

func ValidateWorkflow added in v0.2.0

func ValidateWorkflow(wf *Workflow) []string

ValidateWorkflow checks the workflow for issues and returns a list of warnings.

func WarnIfExpensive added in v0.2.0

func WarnIfExpensive(pred *Prediction, budgetUSD float64) string

WarnIfExpensive returns a warning string if the predicted cost exceeds 10% of the remaining budget. Returns empty string if within budget.

func WithTimeout

WithTimeout wraps a context with the total timeout and stores the deadline so that RemainingTime can report it.

func WriteClipboard added in v0.2.0

func WriteClipboard(content string) error

WriteClipboard writes the given content to the system clipboard. It uses platform-specific commands:

  • macOS: pipe to pbcopy
  • Linux: pipe to xclip -selection clipboard (falls back to xsel)
  • Windows: pipe to powershell Set-Clipboard

Types

type AIComment added in v0.2.0

type AIComment struct {
	File     string // relative file path
	Line     int    // 1-based line number
	Comment  string // the instruction text after "ai:"
	Language string // detected language (go, python, js, etc.)
	Context  string // surrounding 10 lines of code (5 before, 5 after)
	Marker   string // the full comment line for removal after completion
}

AIComment represents a detected AI instruction comment in a source file.

func ScanDirectory added in v0.2.0

func ScanDirectory(dir string, patterns []string) []AIComment

ScanDirectory walks a directory tree and scans all files matching the given patterns for AI comments.

func ScanFile added in v0.2.0

func ScanFile(path string) []AIComment

ScanFile scans a single file for AI comments and returns all found. The path should be an absolute or relative path to the file.

type AIWatcher added in v0.2.0

type AIWatcher struct {
	RootDir   string
	Patterns  []string // file glob patterns to watch (e.g., "*.go", "*.py")
	Debounce  time.Duration
	OnComment func(comment AIComment)
	// contains filtered or unexported fields
}

AIWatcher monitors a directory tree for AI instruction comments and fires a callback when new ones are detected.

func NewAIWatcher added in v0.2.0

func NewAIWatcher(rootDir string, patterns []string) *AIWatcher

NewAIWatcher creates a new AIWatcher for the given directory and file patterns. If patterns is empty, defaults to common source file patterns.

func (*AIWatcher) Start added in v0.2.0

func (w *AIWatcher) Start(ctx context.Context) error

Start begins watching the directory for AI comments. It uses filesystem polling at the configured Debounce interval. It blocks until ctx is cancelled or Stop is called.

func (*AIWatcher) Stop added in v0.2.0

func (w *AIWatcher) Stop()

Stop signals the watcher to stop polling.

type APICompactConfig

type APICompactConfig struct {
	TriggerTokens    int
	KeepTargetTokens int
	ClearToolInputs  bool
	ClearThinking    bool
	PreserveMutating bool
}

APICompactConfig controls API-level compaction.

func DefaultAPICompactConfig

func DefaultAPICompactConfig() APICompactConfig

DefaultAPICompactConfig returns defaults matching the archive.

type APICompactStrategy

type APICompactStrategy struct{}

APICompactStrategy uses API-level context edits to clear thinking blocks and old tool inputs without mutating local message content.

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 []client.EyrieMessage, tokenCount, threshold int) bool

type ActionDetector added in v0.2.0

type ActionDetector struct {
	Rules []ActionRule
	// contains filtered or unexported fields
}

ActionDetector scans code content and produces CodeAction suggestions.

func NewActionDetector added in v0.2.0

func NewActionDetector() *ActionDetector

NewActionDetector creates an ActionDetector pre-loaded with 25+ built-in rules.

func (*ActionDetector) Detect added in v0.2.0

func (ad *ActionDetector) Detect(path, content string) []CodeAction

Detect runs all matching rules against the content and returns actions sorted by priority.

func (*ActionDetector) DetectForDiff added in v0.2.0

func (ad *ActionDetector) DetectForDiff(diff string) []CodeAction

DetectForDiff only checks added lines in a unified diff.

type ActionManager added in v0.2.0

type ActionManager struct {
	Pending  []*ActionRequired
	History  []*ActionRequired
	PromptFn func(action *ActionRequired) (*FormResponse, error)
	// contains filtered or unexported fields
}

ActionManager coordinates action-required requests, managing pending and historical forms and delegating presentation to the configured PromptFn.

func NewActionManager added in v0.2.0

func NewActionManager(promptFn func(*ActionRequired) (*FormResponse, error)) *ActionManager

NewActionManager creates an ActionManager with the given prompt function.

func (*ActionManager) Cancel added in v0.2.0

func (am *ActionManager) Cancel(id string)

Cancel removes a pending action-required by ID and marks it resolved.

func (*ActionManager) GetPending added in v0.2.0

func (am *ActionManager) GetPending() []*ActionRequired

GetPending returns the currently pending action-required requests.

func (*ActionManager) Request added in v0.2.0

func (am *ActionManager) Request(action *ActionRequired) (*FormResponse, error)

Request presents an action-required form to the user via PromptFn, waits for a response or timeout, validates the response, and returns it.

func (*ActionManager) RequestChoice added in v0.2.0

func (am *ActionManager) RequestChoice(title string, choices []string) (string, error)

RequestChoice is a convenience method that requests a single choice from the user.

func (*ActionManager) RequestConfirm added in v0.2.0

func (am *ActionManager) RequestConfirm(title string) (bool, error)

RequestConfirm is a convenience method that requests a yes/no confirmation from the user.

func (*ActionManager) RequestText added in v0.2.0

func (am *ActionManager) RequestText(title, description string) (string, error)

RequestText is a convenience method that requests a single text input from the user.

type ActionRequired added in v0.2.0

type ActionRequired struct {
	ID          string
	Title       string
	Description string
	Fields      []FormField
	Timeout     time.Duration
	Required    bool
	CreatedAt   time.Time
	Response    *FormResponse
	Resolved    bool
}

ActionRequired represents a structured mid-task data collection request presented to the user during agent execution.

type ActionRule added in v0.2.0

type ActionRule struct {
	ID          string
	Name        string
	Category    string
	Language    string
	Pattern     *regexp.Regexp
	Antipattern *regexp.Regexp
	Priority    int
	Message     string
	FixTemplate string // Go template for generating fix
}

ActionRule defines a pattern-based detection rule for code actions.

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 added in v0.2.0

type AdversarialReview struct {
	Findings []ReviewFinding
}

AdversarialReview holds the review configuration and results.

func (*AdversarialReview) FormatFindings added in v0.2.0

func (ar *AdversarialReview) FormatFindings() string

FormatFindings renders findings as a readable report.

type AgentIntelligence added in v0.2.0

type AgentIntelligence struct {
	ScaleClassifier func(string) TaskScale
}

AgentIntelligence provides smart routing, auto-spawning, and synthesis for agents.

func NewAgentIntelligence added in v0.2.0

func NewAgentIntelligence() *AgentIntelligence

NewAgentIntelligence creates the intelligence layer.

func (*AgentIntelligence) AnalyzeForParallelism added in v0.2.0

func (ai *AgentIntelligence) AnalyzeForParallelism(prompt string) SpawnDecision

AnalyzeForParallelism determines if a task should be split into parallel subtasks.

func (*AgentIntelligence) ExecuteWithIntelligence added in v0.2.0

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 added in v0.2.0

func (ai *AgentIntelligence) SelectMode(subtask string) SubAgentMode

SelectMode picks the optimal agent mode for a subtask.

type AgentLogger added in v0.2.0

type AgentLogger struct {
	Logger *StructuredLogger
	Turn   int
	Model  string
}

AgentLogger wraps a StructuredLogger with automatic agent context.

func (*AgentLogger) LogAPICall added in v0.2.0

func (a *AgentLogger) LogAPICall(model string, tokens int, cost float64, duration time.Duration)

LogAPICall logs an LLM API call with token usage and cost.

func (*AgentLogger) LogCompaction added in v0.2.0

func (a *AgentLogger) LogCompaction(before, after int)

LogCompaction logs a context compaction event.

func (*AgentLogger) LogPermission added in v0.2.0

func (a *AgentLogger) LogPermission(tool string, granted bool)

LogPermission logs a permission request and its outcome.

func (*AgentLogger) LogToolCall added in v0.2.0

func (a *AgentLogger) LogToolCall(tool, file string, duration time.Duration, err error)

LogToolCall logs a tool invocation with duration and optional error.

type AliasSuggestion added in v0.2.0

type AliasSuggestion struct {
	Command string `json:"command"`
	Alias   string `json:"alias"`
	Count   int    `json:"count"`
	Reason  string `json:"reason"`
}

AliasSuggestion proposes an alias for a frequently used command.

type Allocation added in v0.2.0

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 added in v0.2.0

type Annotation struct {
	ID        string
	File      string
	Line      int
	Content   string
	Type      string // "note", "todo", "question", "warning", "context"
	Author    string // "agent", "user"
	CreatedAt time.Time
	Resolved  bool
}

Annotation represents a temporary inline annotation added to a file during agent work.

func DetectAnnotations added in v0.2.0

func DetectAnnotations(content string) []*Annotation

DetectAnnotations finds existing hawk annotations in file content and parses them.

type AnnotationManager added in v0.2.0

type AnnotationManager struct {
	Annotations map[string][]*Annotation // file → annotations
	// contains filtered or unexported fields
}

AnnotationManager manages temporary annotations across files.

func NewAnnotationManager added in v0.2.0

func NewAnnotationManager() *AnnotationManager

NewAnnotationManager creates a new AnnotationManager.

func (*AnnotationManager) Add added in v0.2.0

func (am *AnnotationManager) Add(file string, line int, content, annotationType, author string) *Annotation

Add creates a new annotation for the given file and line.

func (*AnnotationManager) BuildContextFromAnnotations added in v0.2.0

func (am *AnnotationManager) BuildContextFromAnnotations(file string) string

BuildContextFromAnnotations formats annotations for a file for injection into agent context.

func (*AnnotationManager) GetAll added in v0.2.0

func (am *AnnotationManager) GetAll() []*Annotation

GetAll returns all annotations across all files.

func (*AnnotationManager) GetForFile added in v0.2.0

func (am *AnnotationManager) GetForFile(file string) []*Annotation

GetForFile returns all annotations for a given file.

func (*AnnotationManager) GetUnresolved added in v0.2.0

func (am *AnnotationManager) GetUnresolved() []*Annotation

GetUnresolved returns all unresolved annotations.

func (*AnnotationManager) InjectAnnotations added in v0.2.0

func (am *AnnotationManager) InjectAnnotations(file, content string) string

InjectAnnotations inserts annotation comments into file content at appropriate lines. Annotations are inserted ABOVE the target line using the correct comment syntax based on file extension.

func (*AnnotationManager) Remove added in v0.2.0

func (am *AnnotationManager) Remove(id string)

Remove deletes an annotation by ID.

func (*AnnotationManager) Resolve added in v0.2.0

func (am *AnnotationManager) Resolve(id string)

Resolve marks an annotation as resolved.

func (*AnnotationManager) Summary added in v0.2.0

func (am *AnnotationManager) Summary() string

Summary returns a brief summary of all annotations.

type Architect added in v0.2.0

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.

func (*Architect) Plan added in v0.2.0

func (a *Architect) Plan(ctx context.Context, goal string, repoContext string) (*ArchitectPlan, error)

Plan sends the goal and repo context to the architect model and returns a structured plan.

type ArchitectConfig added in v0.2.0

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 added in v0.2.0

type ArchitectMessage struct {
	Role    string // "system", "user", "assistant"
	Content string
}

Message is a lightweight chat message used by the architect pipeline. This avoids coupling to external message types from eyrie.

type ArchitectPlan added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

type Assessment struct {
	Score        float64            // overall score 0.0 - 1.0
	Dimensions   map[string]float64 // per-dimension scores
	Strengths    []string           // things that went well
	Weaknesses   []string           // things that went poorly
	Improvements []string           // actionable suggestions for next time
	TaskType     string             // classification of the task
	Timestamp    time.Time          // when the assessment was made
}

Assessment captures the result of a self-evaluation after completing a task.

type Assumption added in v0.2.0

type Assumption struct {
	Text   string
	Status AssumptionStatus
	Proof  string // evidence for/against
}

Assumption is a single assumption the agent is making.

type AssumptionStatus added in v0.2.0

type AssumptionStatus int

AssumptionStatus tracks whether an assumption has been verified.

const (
	AssumptionUnverified AssumptionStatus = iota
	AssumptionConfirmed
	AssumptionFailed
)

type AssumptionTracker added in v0.2.0

type AssumptionTracker struct {
	Assumptions []Assumption
	// contains filtered or unexported fields
}

AssumptionTracker logs and verifies agent assumptions.

func NewAssumptionTracker added in v0.2.0

func NewAssumptionTracker() *AssumptionTracker

NewAssumptionTracker creates a tracker.

func (*AssumptionTracker) Add added in v0.2.0

func (at *AssumptionTracker) Add(text string)

Add logs a new assumption.

func (*AssumptionTracker) Failed added in v0.2.0

func (at *AssumptionTracker) Failed() []Assumption

Failed returns all assumptions that were proven wrong.

func (*AssumptionTracker) Reset added in v0.2.0

func (at *AssumptionTracker) Reset()

Reset clears all assumptions (e.g., for new task).

func (*AssumptionTracker) Summary added in v0.2.0

func (at *AssumptionTracker) Summary() string

Summary returns a formatted summary of all assumptions.

func (*AssumptionTracker) VerifyCommandSucceeds added in v0.2.0

func (at *AssumptionTracker) VerifyCommandSucceeds(text, cmd string)

VerifyCommandSucceeds checks if a command-based assumption holds.

func (*AssumptionTracker) VerifyFileExists added in v0.2.0

func (at *AssumptionTracker) VerifyFileExists(text, path string)

VerifyFileExists checks if a file assumption is correct.

type AutoCommitter added in v0.2.0

type AutoCommitter struct {
	Enabled bool
	RepoDir string
}

AutoCommitter automatically commits changes after every successful edit. Never lose work — every change is a git commit you can undo.

func NewAutoCommitter added in v0.2.0

func NewAutoCommitter(repoDir string) *AutoCommitter

NewAutoCommitter creates an auto-committer for the given repo.

func (*AutoCommitter) CommitIfChanged added in v0.2.0

func (ac *AutoCommitter) CommitIfChanged(description string) error

CommitIfChanged stages and commits any uncommitted changes with a smart message.

func (*AutoCommitter) Undo added in v0.2.0

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

func (ac *AutoCompactor) AutoCompactIfNeeded(ctx context.Context, sess *Session) (string, bool)

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

func (ac *AutoCompactor) RunCompaction(ctx context.Context, sess *Session) (string, error)

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 struct {
	Level           AutonomyLevel
	AutoContinue    bool
	AutoApplyEdits  bool
	AutoExecuteBash bool
	AutoCommit      bool
}

AutonomyConfig holds the derived permission flags for an autonomy level.

func PresetConfig

func PresetConfig(level AutonomyLevel) AutonomyConfig

PresetConfig returns the AutonomyConfig for a given level.

func (AutonomyConfig) NeedsPermission

func (c AutonomyConfig) NeedsPermission(toolName string, isSafe bool) bool

NeedsPermission returns true when the tool call should prompt the user. isSafe indicates whether the specific invocation has been classified as safe (e.g. a non-destructive bash command).

type AutonomyLevel

type AutonomyLevel int

AutonomyLevel controls how much the agent can do without asking the user.

const (
	// AutonomySupervised asks for permission on every tool call.
	AutonomySupervised AutonomyLevel = 0
	// AutonomyBasic auto-allows read-only tools.
	AutonomyBasic AutonomyLevel = 1
	// AutonomySemi auto-allows reads and writes, asks for Bash.
	AutonomySemi AutonomyLevel = 2
	// AutonomyFull auto-allows everything except destructive commands.
	AutonomyFull AutonomyLevel = 3
	// AutonomyYOLO never asks for permission.
	AutonomyYOLO AutonomyLevel = 4
)

func ParseAutonomyLevel

func ParseAutonomyLevel(s string) AutonomyLevel

ParseAutonomyLevel converts a string name or number to an AutonomyLevel.

func (AutonomyLevel) String

func (l AutonomyLevel) String() string

String returns the human-readable name of an autonomy level.

type BackgroundAgentPool

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

BackgroundAgentPool manages async sub-agents that run in the background. When background agents finish, their results are collected for re-injection into the main agent loop (inspired by herm's completion cycles).

func NewBackgroundAgentPool

func NewBackgroundAgentPool() *BackgroundAgentPool

NewBackgroundAgentPool creates a pool with configurable wait limits.

func (*BackgroundAgentPool) AllResults

func (p *BackgroundAgentPool) AllResults() []BackgroundResult

AllResults returns all results collected so far (completed background tasks).

func (*BackgroundAgentPool) Collect

func (p *BackgroundAgentPool) Collect() []BackgroundResult

Collect gathers all completed background results without blocking. Returns immediately with whatever results are available.

func (*BackgroundAgentPool) HasPending

func (p *BackgroundAgentPool) HasPending() bool

HasPending returns true if background agents are still running.

func (*BackgroundAgentPool) PendingCount

func (p *BackgroundAgentPool) PendingCount() int

PendingCount returns the number of in-flight background agents.

func (*BackgroundAgentPool) Submit

func (p *BackgroundAgentPool) Submit(id, prompt string, spawn func(ctx context.Context, prompt string) (string, error))

Submit launches a background sub-agent. The spawn function runs asynchronously.

func (*BackgroundAgentPool) WaitAll

func (p *BackgroundAgentPool) WaitAll() []BackgroundResult

WaitAll blocks until all pending tasks complete or timeout.

type BackgroundResult

type BackgroundResult struct {
	ID      string
	Prompt  string
	Output  string
	Error   error
	Elapsed time.Duration
}

BackgroundResult holds the output of a completed background agent.

type BackgroundRunner added in v0.2.0

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

BackgroundRunner manages async subagent tasks that run while the user keeps chatting.

func NewBackgroundRunner added in v0.2.0

func NewBackgroundRunner() *BackgroundRunner

NewBackgroundRunner creates a new background task runner.

func (*BackgroundRunner) Collect added in v0.2.0

func (br *BackgroundRunner) Collect(id string) *BackgroundTask

Collect returns and removes a completed task's result. Returns nil if still running.

func (*BackgroundRunner) Delegate added in v0.2.0

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 added in v0.2.0

func (br *BackgroundRunner) ListActive() []*BackgroundTask

ListActive returns all currently running tasks.

func (*BackgroundRunner) PendingCount added in v0.2.0

func (br *BackgroundRunner) PendingCount() int

PendingCount returns the number of tasks still running.

func (*BackgroundRunner) Status added in v0.2.0

func (br *BackgroundRunner) Status(id string) *BackgroundTask

Status returns the current state of a background task.

type BackgroundTask added in v0.2.0

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 struct {
	// contains filtered or unexported fields
}

BacktrackEngine records decision points during agent execution and provides the ability to identify the most recent failure and generate a retry prompt with alternative approaches.

func NewBacktrackEngine

func NewBacktrackEngine() *BacktrackEngine

NewBacktrackEngine creates a new backtrack engine that retains at most 50 decision points.

func (*BacktrackEngine) FindBacktrackPoint

func (be *BacktrackEngine) FindBacktrackPoint() *DecisionPoint

FindBacktrackPoint returns the most recent failed decision point that has alternative approaches available, or nil if none exists.

func (*BacktrackEngine) GenerateRetryPrompt

func (be *BacktrackEngine) GenerateRetryPrompt(dp *DecisionPoint) string

GenerateRetryPrompt builds a prompt that tells the agent what failed and suggests alternative approaches.

func (*BacktrackEngine) MarkOutcome

func (be *BacktrackEngine) MarkOutcome(turnIdx int, outcome string)

MarkOutcome sets the outcome ("success" or "failure") for the decision at the given turn index. If multiple decisions exist at the same turn index, the most recent one is updated.

func (*BacktrackEngine) RecordDecision

func (be *BacktrackEngine) RecordDecision(turnIdx int, desc string, alternatives []string, msgs []client.EyrieMessage)

RecordDecision saves a decision point with the current conversation state. If the number of recorded points exceeds the maximum, the oldest point is removed.

func (*BacktrackEngine) RestoreState

func (be *BacktrackEngine) RestoreState(dp *DecisionPoint) []client.EyrieMessage

RestoreState returns the conversation messages captured at the given decision point, representing the state just before (not including) the failed decision. This allows the agent to retry from that point.

func (*BacktrackEngine) Size

func (be *BacktrackEngine) Size() int

Size returns the number of recorded decision points.

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 BlameLine added in v0.2.0

type BlameLine struct {
	LineNo int
	Author string
	Date   time.Time
	Commit string
}

BlameLine represents blame info for a single line.

type BrainstormPhase added in v0.2.0

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 added in v0.2.0

func (p BrainstormPhase) String() string

type BrainstormSession added in v0.2.0

type BrainstormSession struct {
	Topic    string
	Phase    BrainstormPhase
	Ideas    []string
	Clusters map[string][]string
	TopPicks []string
}

BrainstormSession tracks a brainstorming session.

func NewBrainstormSession added in v0.2.0

func NewBrainstormSession(topic string) *BrainstormSession

NewBrainstormSession starts a new brainstorming session.

type BranchManager added in v0.2.0

type BranchManager struct {
	Branches     map[string]*ConversationBranch `json:"branches"`
	ActiveBranch string                         `json:"active_branch"`
	RootBranch   string                         `json:"root_branch"`
	// contains filtered or unexported fields
}

BranchManager manages conversation branches and switching between them.

func NewBranchManager added in v0.2.0

func NewBranchManager() *BranchManager

NewBranchManager creates a new BranchManager with a "main" root branch.

func (*BranchManager) Abandon added in v0.2.0

func (bm *BranchManager) Abandon(branchID string) error

Abandon marks a branch as abandoned.

func (*BranchManager) AddMessage added in v0.2.0

func (bm *BranchManager) AddMessage(role, content string, toolUse []string)

AddMessage appends a message to the currently active branch.

func (*BranchManager) BuildBranchContext added in v0.2.0

func (bm *BranchManager) BuildBranchContext() string

BuildBranchContext formats branch info suitable for inclusion in a system prompt.

func (*BranchManager) CompareBranches added in v0.2.0

func (bm *BranchManager) CompareBranches(branchA, branchB string) string

CompareBranches returns a diff-like comparison of two branches showing where they diverged and what each branch did differently.

func (*BranchManager) ExportBranch added in v0.2.0

func (bm *BranchManager) ExportBranch(branchID string) ([]byte, error)

ExportBranch serializes the specified branch as JSON.

func (*BranchManager) Fork added in v0.2.0

func (bm *BranchManager) Fork(name string, atMessage int) (*ConversationBranch, error)

Fork creates a new branch from the current active branch at the specified message index. Messages up to atMessage are copied into the new branch. The new branch becomes active.

func (*BranchManager) GetActiveMessages added in v0.2.0

func (bm *BranchManager) GetActiveMessages() []BranchMessage

GetActiveMessages returns messages from the currently active branch.

func (*BranchManager) GetBranches added in v0.2.0

func (bm *BranchManager) GetBranches() []*ConversationBranch

GetBranches returns all branches.

func (*BranchManager) ImportBranch added in v0.2.0

func (bm *BranchManager) ImportBranch(data []byte) (*ConversationBranch, error)

ImportBranch deserializes a branch from JSON and adds it to the manager. If a branch with the same ID already exists, a new ID is generated.

func (*BranchManager) Merge added in v0.2.0

func (bm *BranchManager) Merge(sourceBranchID string) error

Merge merges the source branch into the currently active branch. Messages after the fork point are appended to the active branch. The source branch is marked as "merged".

func (*BranchManager) Prune added in v0.2.0

func (bm *BranchManager) Prune(olderThan time.Duration)

Prune removes abandoned branches that are older than the specified duration.

func (*BranchManager) Switch added in v0.2.0

func (bm *BranchManager) Switch(branchID string) error

Switch changes the active branch to the specified branch ID.

type BranchMessage added in v0.2.0

type BranchMessage struct {
	Role      string    `json:"role"`
	Content   string    `json:"content"`
	ToolUse   []string  `json:"tool_use,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

BranchMessage represents a single message within a conversation branch.

type BudgetAlert added in v0.2.0

type BudgetAlert struct {
	Level      string // "info", "warning", "critical"
	Message    string
	Triggered  time.Time
	Percentage float64
}

BudgetAlert represents a budget threshold notification.

type BudgetAllocator added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

func (ba *BudgetAllocator) DefaultAllocations()

DefaultAllocations registers the standard allocation categories for a coding agent.

func (*BudgetAllocator) FormatBudget added in v0.2.0

func (ba *BudgetAllocator) FormatBudget() string

FormatBudget returns a formatted table showing all allocations, their bounds, current assignment, usage, and priority.

func (*BudgetAllocator) GetAvailable added in v0.2.0

func (ba *BudgetAllocator) GetAvailable() int

GetAvailable returns the number of tokens not currently assigned to any allocation.

func (*BudgetAllocator) Rebalance added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 CICheck added in v0.2.0

type CICheck struct {
	Name     string
	Status   string
	Duration time.Duration
	URL      string
}

CICheck represents a single CI check/job.

type CIStatus added in v0.2.0

type CIStatus struct {
	State  string // "success", "failure", "pending"
	Checks []CICheck
	URL    string
}

CIStatus represents the overall CI/CD status for a branch.

type CacheEntry added in v0.2.0

type CacheEntry struct {
	Key        string    `json:"key"`
	Prompt     string    `json:"prompt"`
	Response   string    `json:"response"`
	Model      string    `json:"model"`
	Tokens     int       `json:"tokens"`
	CreatedAt  time.Time `json:"created_at"`
	LastHit    time.Time `json:"last_hit"`
	HitCount   int       `json:"hit_count"`
	Similarity float64   `json:"similarity"`
}

CacheEntry holds a cached LLM response.

type CacheStats added in v0.2.0

type CacheStats struct {
	Entries      int     `json:"entries"`
	HitCount     int64   `json:"hit_count"`
	MissCount    int64   `json:"miss_count"`
	HitRate      float64 `json:"hit_rate"`
	SavedTokens  int64   `json:"saved_tokens"`
	SavedCostUSD float64 `json:"saved_cost_usd"`
}

CacheStats holds statistics about the response cache.

type Capability added in v0.2.0

type Capability struct {
	ID               string   `json:"id"`
	Name             string   `json:"name"`
	Description      string   `json:"description"`
	Category         string   `json:"category"`
	Tools            []string `json:"tools"`
	Examples         []string `json:"examples"`
	Complexity       string   `json:"complexity"` // "trivial", "simple", "moderate", "complex"
	RequiresApproval bool     `json:"requires_approval"`
	Enabled          bool     `json:"enabled"`
}

Capability represents a single thing the agent can do.

type CapabilityRegistry added in v0.2.0

type CapabilityRegistry struct {
	Capabilities map[string]*Capability
	Categories   map[string][]string
	// contains filtered or unexported fields
}

CapabilityRegistry manages the set of capabilities the agent advertises.

func NewCapabilityRegistry added in v0.2.0

func NewCapabilityRegistry() *CapabilityRegistry

NewCapabilityRegistry creates a registry pre-populated with built-in capabilities.

func (*CapabilityRegistry) CanDo added in v0.2.0

func (r *CapabilityRegistry) CanDo(taskDescription string) []*Capability

CanDo matches a task description against capabilities and returns relevant ones.

func (*CapabilityRegistry) Disable added in v0.2.0

func (r *CapabilityRegistry) Disable(id string)

Disable disables a capability by ID.

func (*CapabilityRegistry) Enable added in v0.2.0

func (r *CapabilityRegistry) Enable(id string)

Enable enables a capability by ID.

func (*CapabilityRegistry) FormatCapability added in v0.2.0

func (r *CapabilityRegistry) FormatCapability(cap *Capability) string

FormatCapability returns a detailed formatted string for a single capability.

func (*CapabilityRegistry) FormatHelp added in v0.2.0

func (r *CapabilityRegistry) FormatHelp() string

FormatHelp returns a formatted help string listing all capabilities by category.

func (*CapabilityRegistry) GetCapability added in v0.2.0

func (r *CapabilityRegistry) GetCapability(id string) *Capability

GetCapability returns a capability by ID, or nil if not found.

func (*CapabilityRegistry) GetCategories added in v0.2.0

func (r *CapabilityRegistry) GetCategories() []string

GetCategories returns a sorted list of all category names.

func (*CapabilityRegistry) ListByCategory added in v0.2.0

func (r *CapabilityRegistry) ListByCategory(category string) []*Capability

ListByCategory returns all capabilities in the given category.

func (*CapabilityRegistry) Search added in v0.2.0

func (r *CapabilityRegistry) Search(query string) []*Capability

Search finds capabilities matching the query string against ID, name, description, and examples.

type CascadeRouter

type CascadeRouter struct {
	Enabled      bool
	FrugalMode   bool   // more aggressive downgrading
	DefaultModel string // fallback when classification is inconclusive
	Roles        routing.ModelRoles
	// contains filtered or unexported fields
}

CascadeRouter selects the optimal model for each request based on task complexity. It uses pre-request classification (before we have a response) to route:

  • simple/chat tasks -> cheap model (haiku)
  • debug/review/refactor -> mid model (sonnet)
  • generation -> expensive model (opus)

The router also tracks routing decisions for analytics.

func NewCascadeRouter

func NewCascadeRouter(defaultModel string, roles routing.ModelRoles) *CascadeRouter

NewCascadeRouter creates a router with sensible defaults. The defaultModel is used as the fallback when classification yields no strong signal and no role-specific model is configured.

func (*CascadeRouter) DecisionCount

func (cr *CascadeRouter) DecisionCount() int

DecisionCount returns how many routing decisions have been recorded.

func (*CascadeRouter) Decisions

func (cr *CascadeRouter) Decisions() []RoutingDecision

Decisions returns a snapshot of all routing decisions made so far.

func (*CascadeRouter) Savings

func (cr *CascadeRouter) Savings() float64

Savings estimates the USD saved by routing decisions compared to always using the most expensive model. This is a rough heuristic: it sums the per-million-token price difference for each decision where the selected model is cheaper than the original.

func (*CascadeRouter) SelectModel

func (cr *CascadeRouter) SelectModel(prompt string, currentModel string, userOverride string) string

SelectModel picks the best model for a given prompt. If userOverride is non-empty the user's explicit choice always wins (override is never downgraded). The returned string is the model name to use for the API call.

func (*CascadeRouter) Summary

func (cr *CascadeRouter) Summary() string

Summary returns a human-readable summary of routing activity.

type ChangeEntry added in v0.2.0

type ChangeEntry struct {
	Type        string // "feat", "fix", "refactor", "perf", "docs", "test", "chore"
	Scope       string
	Description string
	CommitHash  string
	Author      string
	Breaking    bool
}

ChangeEntry represents a single change parsed from a commit message.

func ParseConventionalCommit added in v0.2.0

func ParseConventionalCommit(msg string) *ChangeEntry

ParseConventionalCommit parses a commit message in conventional commit format. Returns nil if the message cannot be parsed.

type ChangeStats added in v0.2.0

type ChangeStats struct {
	Additions int
	Deletions int
	NetChange int
}

ChangeStats summarizes additions and deletions for a file change.

type ChatClient added in v0.2.0

type ChatClient interface {
	Chat(ctx context.Context, messages []client.EyrieMessage, opts client.ChatOptions) (*client.EyrieResponse, error)
	StreamChatContinue(ctx context.Context, messages []client.EyrieMessage, opts client.ChatOptions, cfg client.ContinuationConfig) (*client.StreamResult, error)
	SetAPIKey(provider, apiKey string)
}

ChatClient abstracts the LLM client methods used by Session. The production implementation is *client.EyrieClient; tests can inject a mock.

func NewMockClientForTest added in v0.2.0

func NewMockClientForTest() ChatClient

NewMockClientForTest creates a mock ChatClient that returns canned text responses.

type CheckpointPhase added in v0.2.0

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 added in v0.2.0

type ChunkedResponse struct {
	Chunks     []string
	TotalChars int
	TotalPages int
	Current    int
}

ChunkedResponse holds a paginated response.

func (*ChunkedResponse) FormatPage added in v0.2.0

func (cr *ChunkedResponse) FormatPage(page int) string

FormatPage returns a chunk with page header/footer for the agent.

type ClassifiedInput added in v0.2.0

type ClassifiedInput struct {
	Input  string
	Intent *Intent
}

ClassifiedInput records a classification for history tracking.

type ClipboardBridge added in v0.2.0

type ClipboardBridge struct{}

ClipboardBridge enables paste-from-browser workflows. Paste code/errors from browser, hawk processes them as context.

func (*ClipboardBridge) IsCode added in v0.2.0

func (cb *ClipboardBridge) IsCode(content string) bool

IsCode heuristically detects if clipboard content is code vs prose.

func (*ClipboardBridge) ReadClipboard added in v0.2.0

func (cb *ClipboardBridge) ReadClipboard() (string, error)

ReadClipboard returns the current clipboard content.

func (*ClipboardBridge) WriteClipboard added in v0.2.0

func (cb *ClipboardBridge) WriteClipboard(content string) error

WriteClipboard sets the clipboard content.

type ClipboardMonitor added in v0.2.0

type ClipboardMonitor struct {
	Enabled      bool
	PollInterval time.Duration
	OnPaste      func(content string)
	// contains filtered or unexported fields
}

ClipboardMonitor watches the system clipboard for changes and fires a callback when new content is detected. Inspired by Aider's copypaste feature.

func NewClipboardMonitor added in v0.2.0

func NewClipboardMonitor() *ClipboardMonitor

NewClipboardMonitor creates a new ClipboardMonitor with sensible defaults.

func (*ClipboardMonitor) Start added in v0.2.0

func (cm *ClipboardMonitor) Start(ctx context.Context) error

Start begins polling the clipboard at PollInterval. When content changes and passes validation (>20 chars, <50000 chars), the OnPaste callback is fired. The monitor runs until Stop() is called or the context is cancelled.

func (*ClipboardMonitor) Stop added in v0.2.0

func (cm *ClipboardMonitor) Stop()

Stop halts the clipboard polling loop.

type CodeAction added in v0.2.0

type CodeAction struct {
	ID          string
	Title       string
	Description string
	File        string
	Line        int
	Category    string  // "refactor", "performance", "security", "style", "fix"
	Priority    int     // 1=high, 3=medium, 5=low
	Fix         string  // suggested replacement code
	Confidence  float64 // 0.0 to 1.0
}

CodeAction represents a suggested improvement for a specific location in code.

type CodeContext added in v0.2.0

type CodeContext struct {
	Snippets    []CodeSnippet
	TotalTokens int
	Query       string
	// contains filtered or unexported fields
}

CodeContext holds a collection of relevant code snippets for a task.

type CodeExplainer added in v0.2.0

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

CodeExplainer generates structured explanations of code using AST analysis and pattern recognition, without any LLM calls.

func NewCodeExplainer added in v0.2.0

func NewCodeExplainer() *CodeExplainer

NewCodeExplainer creates a new CodeExplainer instance.

func (*CodeExplainer) ExplainFile added in v0.2.0

func (ce *CodeExplainer) ExplainFile(path, content string) (*CodeExplanation, error)

ExplainFile generates a structured explanation of an entire file.

func (*CodeExplainer) ExplainFunction added in v0.2.0

func (ce *CodeExplainer) ExplainFunction(file, content, funcName string) (*CodeExplanation, error)

ExplainFunction parses the given file content and generates a structured explanation for the named function.

func (*CodeExplainer) ExplainType added in v0.2.0

func (ce *CodeExplainer) ExplainType(file, content, typeName string) (*CodeExplanation, error)

ExplainType parses the given file content and generates a structured explanation for the named type.

type CodeExplanation added in v0.2.0

type CodeExplanation struct {
	File         string
	Symbol       string
	Summary      string
	Sections     []ExplanationSection
	Complexity   string
	Dependencies []string
	UsedBy       []string
}

CodeExplanation holds a structured explanation of a code element.

type CodeLens added in v0.2.0

type CodeLens struct {
	File     string
	Line     int
	Label    string
	Category string // "test_status", "complexity", "ownership", "age", "references", "coverage"
	Command  string
	Tooltip  string
}

CodeLens represents an inline annotation for a specific line in a file.

func FilterByCategory added in v0.2.0

func FilterByCategory(lenses []CodeLens, category string) []CodeLens

FilterByCategory returns only lenses matching the given category.

func GenerateAgeLens added in v0.2.0

func GenerateAgeLens(file, content string) []CodeLens

GenerateAgeLens uses git blame to determine how recently each function was modified.

func GenerateComplexityLens added in v0.2.0

func GenerateComplexityLens(file, content string) []CodeLens

GenerateComplexityLens calculates cyclomatic complexity for each function and annotates functions that exceed a threshold of 5.

func GenerateCoverageLens added in v0.2.0

func GenerateCoverageLens(file, content string) []CodeLens

GenerateCoverageLens produces coverage annotations per function if coverage data is available.

func GenerateReferenceLens added in v0.2.0

func GenerateReferenceLens(file, content string) []CodeLens

GenerateReferenceLens counts how many times each exported symbol is referenced.

func GenerateTestLens added in v0.2.0

func GenerateTestLens(file, content string) []CodeLens

GenerateTestLens finds test functions and annotates them with last known status.

type CodeLensProvider added in v0.2.0

type CodeLensProvider struct {
	Providers map[string]LensGenerator
	// contains filtered or unexported fields
}

CodeLensProvider manages a set of lens generators and produces annotations.

func NewCodeLensProvider added in v0.2.0

func NewCodeLensProvider() *CodeLensProvider

NewCodeLensProvider creates a CodeLensProvider with built-in generators for test status, complexity, references, age, and coverage.

func (*CodeLensProvider) Generate added in v0.2.0

func (p *CodeLensProvider) Generate(file, content string) []CodeLens

Generate runs all registered providers and returns merged lenses sorted by line.

func (*CodeLensProvider) Register added in v0.2.0

func (p *CodeLensProvider) Register(name string, generator LensGenerator)

Register adds or replaces a named lens generator.

type CodeSnippet added in v0.2.0

type CodeSnippet struct {
	File      string  // relative file path
	StartLine int     // first line (1-based)
	EndLine   int     // last line (1-based)
	Content   string  // the actual code
	Relevance float64 // 0.0 - 1.0 relevance score
	Type      string  // "function", "type", "block", "import"
	Symbol    string  // name of the symbol (function/type name)
}

CodeSnippet represents an extracted piece of code with metadata.

type CodingSoul added in v0.2.0

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 added in v0.2.0

func LoadCodingSoul() *CodingSoul

LoadCodingSoul reads the soul file. Returns empty soul if not found.

func (*CodingSoul) ForPrompt added in v0.2.0

func (s *CodingSoul) ForPrompt() string

ForPrompt formats the soul as system prompt context.

type CommandFrequency added in v0.2.0

type CommandFrequency struct {
	Command     string        `json:"command"`
	Count       int           `json:"count"`
	AvgDuration time.Duration `json:"avg_duration"`
	FailRate    float64       `json:"fail_rate"`
}

CommandFrequency tracks usage statistics for a command.

type CommandHistory added in v0.2.0

type CommandHistory struct {
	Commands []CommandRecord `json:"commands"`
	Patterns map[string]int  `json:"patterns"`
	Failures map[string]int  `json:"failures"`
	// contains filtered or unexported fields
}

CommandHistory tracks shell commands executed during sessions and provides insights.

func NewCommandHistory added in v0.2.0

func NewCommandHistory() *CommandHistory

NewCommandHistory creates a new CommandHistory instance.

func (*CommandHistory) Clear added in v0.2.0

func (ch *CommandHistory) Clear()

Clear removes all command history.

func (*CommandHistory) DetectPatterns added in v0.2.0

func (ch *CommandHistory) DetectPatterns() []string

DetectPatterns analyzes command history for notable patterns and returns insights.

func (*CommandHistory) FormatSummary added in v0.2.0

func (ch *CommandHistory) FormatSummary() string

FormatSummary returns a formatted string summary of command history.

func (*CommandHistory) GetFailing added in v0.2.0

func (ch *CommandHistory) GetFailing() []CommandRecord

GetFailing returns commands that frequently fail (exit code != 0).

func (*CommandHistory) GetFrequent added in v0.2.0

func (ch *CommandHistory) GetFrequent(limit int) []CommandFrequency

GetFrequent returns the most frequently used commands up to limit.

func (*CommandHistory) GetSlow added in v0.2.0

func (ch *CommandHistory) GetSlow(threshold time.Duration) []CommandRecord

GetSlow returns commands that took longer than the given threshold.

func (*CommandHistory) Record added in v0.2.0

func (ch *CommandHistory) Record(cmd string, exitCode int, duration time.Duration, output string)

Record adds a command execution to history.

func (*CommandHistory) SearchCommands added in v0.2.0

func (ch *CommandHistory) SearchCommands(query string) []CommandRecord

SearchCommands returns commands matching the query string.

func (*CommandHistory) SuggestAlias added in v0.2.0

func (ch *CommandHistory) SuggestAlias(minCount int) []AliasSuggestion

SuggestAlias returns alias suggestions for commands used more than minCount times.

type CommandRecord added in v0.2.0

type CommandRecord struct {
	Command   string        `json:"command"`
	ExitCode  int           `json:"exit_code"`
	Duration  time.Duration `json:"duration"`
	Output    string        `json:"output"`
	Timestamp time.Time     `json:"timestamp"`
	SessionID string        `json:"session_id"`
	WorkDir   string        `json:"work_dir"`
}

CommandRecord represents a single command execution with metadata.

type CommandSuggestion added in v0.2.0

type CommandSuggestion struct {
	Command     string
	Description string
	Confidence  float64
	Category    string
	Context     string
}

CommandSuggestion represents a single proactive command suggestion.

type CommitInfo added in v0.2.0

type CommitInfo struct {
	Hash         string
	Author       string
	Date         time.Time
	Message      string
	FilesChanged int
}

CommitInfo represents a single git commit.

type CompactConfig

type CompactConfig struct {
	AutoEnabled       bool
	ContextWindowSize int
	AutoCompactBuffer int
	MaxOutputTokens   int
	MaxFailures       int
}

CompactConfig controls auto-compaction behavior.

func DefaultCompactConfig

func DefaultCompactConfig() CompactConfig

DefaultCompactConfig returns sensible defaults matching the archive behavior.

type CompactResult

type CompactResult struct {
	Messages     []client.EyrieMessage
	Summary      string
	TokensBefore int
	TokensAfter  int
	Strategy     string
}

CompactResult holds the outcome of a compaction operation.

type CompactStrategy

type CompactStrategy interface {
	Name() string
	ShouldTrigger(msgs []client.EyrieMessage, tokenCount, threshold int) bool
	Compact(ctx context.Context, s *Session) (*CompactResult, error)
}

CompactStrategy defines a conversation compaction approach.

type CompactVariant

type CompactVariant int

CompactVariant determines which compaction prompt style to use.

const (
	CompactBase    CompactVariant = iota // Full conversation
	CompactPartial                       // Recent messages only
	CompactUpTo                          // Prefix summarization
)

type CompactionTrigger added in v0.2.0

type CompactionTrigger struct {
	Threshold   float64 // trigger at this % of context window (e.g. 0.8 = 80%)
	WindowSize  int     // total context window tokens
	LastCompact time.Time
	MinInterval time.Duration // don't compact more often than this
}

CompactionTrigger monitors token usage and triggers compaction proactively.

func NewCompactionTrigger added in v0.2.0

func NewCompactionTrigger(windowSize int) *CompactionTrigger

NewCompactionTrigger creates a trigger with sensible defaults for solo dev use.

func (*CompactionTrigger) MarkCompacted added in v0.2.0

func (ct *CompactionTrigger) MarkCompacted()

MarkCompacted records that compaction just happened.

func (*CompactionTrigger) ShouldCompact added in v0.2.0

func (ct *CompactionTrigger) ShouldCompact(currentTokens int) bool

ShouldCompact returns true if current token usage warrants compaction.

type CompressMessage added in v0.2.0

type CompressMessage struct {
	Role         string
	Content      string
	ToolName     string
	IsToolResult bool
	Importance   float64
	Tokens       int
}

CompressMessage represents a single message in the conversation for compression.

func SelectiveCompress added in v0.2.0

func SelectiveCompress(messages []CompressMessage, budget int) []CompressMessage

SelectiveCompress keeps high-importance messages verbatim and summarizes low-importance blocks.

func SemanticCompress added in v0.2.0

func SemanticCompress(messages []CompressMessage, budget int) []CompressMessage

SemanticCompress groups messages by topic/task, keeps conclusions, and summarizes journeys.

func TieredCompress added in v0.2.0

func TieredCompress(messages []CompressMessage, budget int) []CompressMessage

TieredCompress applies different compression levels based on message recency. Recent (last 20%): keep verbatim Middle (20-60%): selective (keep important, summarize rest) Old (60-100%): aggressive summary

type CompressStrategy added in v0.2.0

type CompressStrategy string

CompressStrategy defines the compression approach to use.

const (
	// StrategySummarize compresses by summarizing all old messages into blocks.
	StrategySummarize CompressStrategy = "summarize"
	// StrategySelective keeps high-importance messages and summarizes the rest.
	StrategySelective CompressStrategy = "selective"
	// StrategyTiered applies different levels of compression based on recency.
	StrategyTiered CompressStrategy = "tiered"
	// StrategySemantic groups messages by topic and keeps conclusions.
	StrategySemantic CompressStrategy = "semantic"
)

type CompressedBlock added in v0.2.0

type CompressedBlock struct {
	Summary         string
	OriginalCount   int
	TokensSaved     int
	KeyFacts        []string
	ToolCallSummary string
	FilesDiscussed  []string
}

CompressedBlock represents a group of messages that have been compressed into a summary.

func SummarizeBlock added in v0.2.0

func SummarizeBlock(messages []CompressMessage) *CompressedBlock

SummarizeBlock creates a CompressedBlock from a group of messages by extracting key information.

type CompressedFile added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

type CompressionResult struct {
	Original          int
	Compressed        int
	TokensSaved       int
	Blocks            []CompressedBlock
	PreservedMessages int
}

CompressionResult holds statistics and details about a compression operation.

type ConsensusResult added in v0.2.0

type ConsensusResult struct {
	Winner     *Sample
	AllSamples []Sample
	Agreement  float64
	Method     string
}

ConsensusResult holds the outcome of multi-sample consensus.

type ConsensusSampler added in v0.2.0

type ConsensusSampler struct {
	NumSamples int
	Strategy   string // "majority", "best_score", "synthesize"
	ScoreFn    func(solution string) float64
	// contains filtered or unexported fields
}

ConsensusSampler implements the multi-sample consensus pattern inspired by SWE-agent's "Ask Colleagues" approach: generate N solutions in parallel, then select the best one using a configurable strategy.

func NewConsensusSampler added in v0.2.0

func NewConsensusSampler(numSamples int) *ConsensusSampler

NewConsensusSampler creates a ConsensusSampler with the given number of samples. If numSamples is <= 0, it defaults to 3.

func (*ConsensusSampler) SampleSolutions added in v0.2.0

func (cs *ConsensusSampler) SampleSolutions(ctx context.Context, prompt string, generateFn func(context.Context, string) (string, error)) (*ConsensusResult, error)

SampleSolutions generates N solutions in parallel, scores each, and selects a winner based on the configured strategy.

type ConsolidatedMemory added in v0.2.0

type ConsolidatedMemory struct {
	ID         string     `json:"id"`
	Category   string     `json:"category"` // "fact", "convention", "decision", "warning", "skill"
	Content    string     `json:"content"`
	Confidence float64    `json:"confidence"`
	References []string   `json:"references"`
	CreatedAt  time.Time  `json:"created_at"`
	ExpiresAt  *time.Time `json:"expires_at,omitempty"`
}

ConsolidatedMemory represents a processed, structured long-term memory.

type ConsolidatorStats added in v0.2.0

type ConsolidatorStats struct {
	RawCount          int       `json:"raw_count"`
	ProcessedCount    int       `json:"processed_count"`
	ConsolidatedCount int       `json:"consolidated_count"`
	FactCount         int       `json:"fact_count"`
	ConventionCount   int       `json:"convention_count"`
	DecisionCount     int       `json:"decision_count"`
	WarningCount      int       `json:"warning_count"`
	SkillCount        int       `json:"skill_count"`
	AvgConfidence     float64   `json:"avg_confidence"`
	LastConsolidation time.Time `json:"last_consolidation"`
}

ConsolidatorStats holds aggregate statistics about the memory consolidator.

type ContextAllocation

type ContextAllocation struct {
	SystemPrompt   int
	ToolDefs       int
	RepoMap        int
	Memory         int
	Workspace      int
	PreloadedFiles int
	Conversation   int
	OutputReserve  int
	SafetyMargin   int
	Remaining      int // should be ~0 if properly allocated
}

ContextAllocation shows where tokens are going for the current conversation state.

type ContextBudget

type ContextBudget struct {
	Total int // model's full context window

	// Fixed allocations
	SystemPrompt int // 3000-5000 tokens (rules, identity)
	ToolDefs     int // 2000-3000 tokens (tool descriptions)
	RepoMap      int // 2000-4000 tokens (ranked symbol map)
	Memory       int // 1000-2000 tokens (yaad/zenbrain context)
	Workspace    int // 500 tokens (git status, branch, recent commits)

	// Adaptive allocations
	PreloadedFiles int // 10000-30000 tokens (relevant code context)
	Conversation   int // remaining (managed by compaction)

	// Reserved
	OutputReserve int // 16000-20000 tokens (model response space)
	SafetyMargin  int // 10000-15000 tokens (estimation errors, API overhead)
}

ContextBudget allocates the model's context window across different content categories. Based on research: proper allocation prevents context overflow and optimizes information density per token spent.

The allocator ensures:

  • Fixed allocations for system prompt, repo map, memory, workspace context
  • Adaptive allocation for pre-loaded files (expands when conversation is short)
  • Managed conversation history (triggers compaction when exceeded)
  • Reserved budget for model output and safety margin

Research basis: All top coding agents (Claude Code, Cursor, Aider) manage context, but none formalize it as an explicit budget with categories. This is the missing architectural glue.

func NewContextBudget

func NewContextBudget(contextSize int) *ContextBudget

NewContextBudget creates a budget for the given model context size. Allocations scale proportionally with the context window while respecting sensible floors and ceilings per category.

func (*ContextBudget) Allocate

func (b *ContextBudget) Allocate(conversationTokens int) *ContextAllocation

Allocate distributes the budget based on current conversation length. As conversation grows, PreloadedFiles shrinks to make room.

func (*ContextBudget) FilesBudget

func (b *ContextBudget) FilesBudget(conversationTokens int) int

FilesBudget returns the current budget available for pre-loaded file context.

func (*ContextBudget) ShouldCompact

func (b *ContextBudget) ShouldCompact(conversationTokens int) bool

ShouldCompact returns true if conversation exceeds its allocation.

func (*ContextBudget) UsageReport

func (b *ContextBudget) UsageReport(conversationTokens int) string

UsageReport returns a human-readable breakdown of current allocation.

type ContextDecay added in v0.2.0

type ContextDecay struct {
	HalfLife  time.Duration
	MinWeight float64
	Entries   []DecayEntry
	// contains filtered or unexported fields
}

ContextDecay manages context entries with time-based importance decay. Older context gradually loses weight unless pinned or accessed, keeping the most relevant information prioritized for the model's context window.

The decay follows exponential half-life: weight = initial * 0.5^(elapsed/halfLife) This mirrors human memory curves and ensures stale context doesn't crowd out fresh, relevant information.

func NewContextDecay added in v0.2.0

func NewContextDecay(halfLife time.Duration) *ContextDecay

NewContextDecay creates a new ContextDecay manager with the given half-life. If halfLife is zero or negative, a default of 30 minutes is used.

func (*ContextDecay) Access added in v0.2.0

func (cd *ContextDecay) Access(id string)

Access marks an entry as accessed, boosting its weight as a relevance signal. Each access resets the decay timer and increases the base weight.

func (*ContextDecay) Add added in v0.2.0

func (cd *ContextDecay) Add(content, category string, tokens int) string

Add inserts a new context entry with initial weight 1.0. Returns the generated ID for the entry.

func (*ContextDecay) ApplyDecay added in v0.2.0

func (cd *ContextDecay) ApplyDecay()

ApplyDecay recalculates all entry weights based on time elapsed since last access. Pinned entries are not affected by decay.

func (*ContextDecay) BuildContext added in v0.2.0

func (cd *ContextDecay) BuildContext(maxTokens int) string

BuildContext formats the top entries fitting within the token budget as a context string.

func (*ContextDecay) FormatEntries added in v0.2.0

func (cd *ContextDecay) FormatEntries(entries []DecayEntry) string

FormatEntries renders a slice of entries as a human-readable context block showing weight, pin status, and content.

func (*ContextDecay) Get added in v0.2.0

func (cd *ContextDecay) Get(id string) (*DecayEntry, float64)

Get retrieves an entry by ID and returns it with its current decayed weight. Returns nil if the entry is not found.

func (*ContextDecay) GetByBudget added in v0.2.0

func (cd *ContextDecay) GetByBudget(maxTokens int) []DecayEntry

GetByBudget returns entries fitting within the given token budget, sorted by weight descending. Entries are selected greedily by weight until the budget is exhausted.

func (*ContextDecay) GetTopN added in v0.2.0

func (cd *ContextDecay) GetTopN(n int) []DecayEntry

GetTopN returns the N entries with the highest current weight, sorted descending.

func (*ContextDecay) Pin added in v0.2.0

func (cd *ContextDecay) Pin(id string)

Pin marks an entry as pinned, preventing decay. Pinned entries always have weight 1.0.

func (*ContextDecay) Prune added in v0.2.0

func (cd *ContextDecay) Prune(minWeight float64) int

Prune removes all entries whose current decayed weight is below the given threshold. Returns the number of entries removed.

func (*ContextDecay) Stats added in v0.2.0

func (cd *ContextDecay) Stats() DecayStats

Stats returns aggregate statistics about the current context decay state.

func (*ContextDecay) Unpin added in v0.2.0

func (cd *ContextDecay) Unpin(id string)

Unpin removes the pin from an entry, allowing normal decay to resume.

type ContextExtractor added in v0.2.0

type ContextExtractor struct {
	ProjectDir string
	MaxTokens  int
	// contains filtered or unexported fields
}

ContextExtractor intelligently extracts relevant code snippets for tasks.

func NewContextExtractor added in v0.2.0

func NewContextExtractor(projectDir string, maxTokens int) *ContextExtractor

NewContextExtractor creates a new extractor rooted at the given project directory.

func (*ContextExtractor) ExtractForTask added in v0.2.0

func (ce *ContextExtractor) ExtractForTask(task string) (*CodeContext, error)

ExtractForTask analyzes a task description and extracts relevant code snippets that fit within the token budget.

func (*ContextExtractor) ExtractFunction added in v0.2.0

func (ce *ContextExtractor) ExtractFunction(file, funcName string) (*CodeSnippet, error)

ExtractFunction extracts a single function's complete code from the given file.

func (*ContextExtractor) ExtractImports added in v0.2.0

func (ce *ContextExtractor) ExtractImports(file string) (*CodeSnippet, error)

ExtractImports extracts the import block from the given file.

func (*ContextExtractor) ExtractSurrounding added in v0.2.0

func (ce *ContextExtractor) ExtractSurrounding(file string, line, contextLines int) (*CodeSnippet, error)

ExtractSurrounding extracts N lines of context around a target line.

func (*ContextExtractor) ExtractType added in v0.2.0

func (ce *ContextExtractor) ExtractType(file, typeName string) (*CodeSnippet, error)

ExtractType extracts a type definition and its methods from the given file.

func (*ContextExtractor) FindRelevantSymbols added in v0.2.0

func (ce *ContextExtractor) FindRelevantSymbols(query string, limit int) []CodeSnippet

FindRelevantSymbols searches for symbols matching the query using grep and simple AST-like pattern matching.

func (*ContextExtractor) RankSnippets added in v0.2.0

func (ce *ContextExtractor) RankSnippets(snippets []CodeSnippet, query string) []CodeSnippet

RankSnippets scores and sorts snippets by relevance to the query.

type ContextFile added in v0.2.0

type ContextFile struct {
	Path          string
	Content       string
	TokenCount    int
	AddedAt       time.Time
	LastRefreshed time.Time
	AutoRefresh   bool
	Pinned        bool
}

ContextFile represents a single read-only context file loaded into the agent's context.

type ContextFileOption added in v0.2.0

type ContextFileOption func(*ContextFile)

ContextFileOption configures how a file is added to the read-only context.

func WithAutoRefresh added in v0.2.0

func WithAutoRefresh() ContextFileOption

WithAutoRefresh marks the file to be re-read on each turn if it changes on disk.

func WithPinned added in v0.2.0

func WithPinned() ContextFileOption

WithPinned marks the file as pinned so it is never evicted.

type ContextItem added in v0.2.0

type ContextItem struct {
	Source     string
	Title      string
	Content    string
	Relevance  float64
	TokenCount int
}

ContextItem represents a single piece of context gathered from a provider.

func PrioritizeItems added in v0.2.0

func PrioritizeItems(items []ContextItem, budget int) []ContextItem

PrioritizeItems performs greedy selection sorted by relevance, picking items until budget is exhausted while ensuring source diversity.

type ContextManager added in v0.2.0

type ContextManager struct {
	Providers   []ContextProvider
	TotalBudget int
	// contains filtered or unexported fields
}

ContextManager manages multiple context providers and orchestrates context gathering.

func NewContextManager added in v0.2.0

func NewContextManager(totalBudget int) *ContextManager

NewContextManager creates a new ContextManager with the given total token budget.

func (*ContextManager) GatherAll added in v0.2.0

func (cm *ContextManager) GatherAll(ctx context.Context, query string) ([]ContextItem, error)

GatherAll calls all providers in parallel, collects items, sorts by relevance, and truncates to fit within TotalBudget.

func (*ContextManager) Register added in v0.2.0

func (cm *ContextManager) Register(provider ContextProvider)

Register adds a context provider to the manager.

type ContextPacker added in v0.2.0

type ContextPacker struct {
	MaxTokens          int             // model's context window
	ReservedForOutput  int             // tokens reserved for response
	SystemPromptTokens int             // tokens consumed by system prompt
	Strategy           PackingStrategy // packing strategy to use
}

ContextPacker optimally selects which messages to keep when approaching context window limits, maximizing information density per token spent.

func NewContextPacker added in v0.2.0

func NewContextPacker(maxTokens int) *ContextPacker

NewContextPacker creates a new context packer for the given model context size.

func (*ContextPacker) OptimalSelection added in v0.2.0

func (cp *ContextPacker) OptimalSelection(messages []ScoredMessage, budget int) []int

OptimalSelection performs greedy selection by score/token ratio, respecting constraints (tool pairs, pinned messages).

func (*ContextPacker) Pack added in v0.2.0

func (cp *ContextPacker) Pack(messages []ScoredMessage, currentTask string) *PackingResult

Pack scores each message and selects the optimal subset within budget. It ensures tool_use/tool_result pairs stay together, always keeps the system prompt context, first user message, and the last 4 messages.

func (*ContextPacker) ScoreMessage added in v0.2.0

func (cp *ContextPacker) ScoreMessage(msg ScoredMessage, currentTask string, position int, total int) float64

ScoreMessage computes a composite score for a message based on multiple factors.

type ContextProvider added in v0.2.0

type ContextProvider interface {
	Name() string
	Description() string
	Gather(ctx context.Context, query string) ([]ContextItem, error)
	TokenBudget() int
}

ContextProvider is a pluggable source of context that can be injected into the agent's system prompt.

type ContextSection added in v0.2.0

type ContextSection struct {
	Name         string // "system_prompt", "memory", "conversation", "tool_results", "reserved"
	Tokens       int
	Percentage   float64
	Color        string // ANSI color code for the bar
	Items        []VizContextItem
	Compressible bool
}

ContextSection represents a named region of the context window.

type ContextSnapshot added in v0.2.0

type ContextSnapshot struct {
	Turn        int
	TotalTokens int
	Percentage  float64
	Compacted   bool
}

ContextSnapshot captures context state at a particular turn for history tracking.

type ContextStats added in v0.2.0

type ContextStats struct {
	TotalFiles  int
	TotalTokens int
	BudgetUsed  float64
	PinnedCount int
}

ContextStats provides statistics about the read-only context state.

type ContextVisualizer added in v0.2.0

type ContextVisualizer struct {
	MaxTokens int
	Sections  []ContextSection
	// contains filtered or unexported fields
}

ContextVisualizer provides a real-time view of context window usage, showing users exactly what occupies their context and how space is allocated.

func NewContextVisualizer added in v0.2.0

func NewContextVisualizer(maxTokens int) *ContextVisualizer

NewContextVisualizer creates a visualizer for the given maximum token budget.

func (*ContextVisualizer) HistoryChart added in v0.2.0

func (cv *ContextVisualizer) HistoryChart(snapshots []ContextSnapshot, width int) string

HistoryChart renders context usage across turns as a sparkline-style chart.

Example:

Turn  1: [██░░░░░░░░░░░░░░░░░░]  8%
Turn  5: [████████░░░░░░░░░░░░] 35%
Turn 10: [████████████████░░░░] 78%  ← compacted
Turn 11: [██████░░░░░░░░░░░░░░] 28%

func (*ContextVisualizer) Recommend added in v0.2.0

func (cv *ContextVisualizer) Recommend() []string

Recommend returns actionable suggestions based on current context state.

func (*ContextVisualizer) RenderBar added in v0.2.0

func (cv *ContextVisualizer) RenderBar(width int) string

RenderBar renders a horizontal stacked bar showing each section's proportion.

Example output:

Context: [████████░░░░░░░░░░░░] 42% used (84,000/200,000)
         [sys|mem|████conv████|tool|░░░reserved░░░]

func (*ContextVisualizer) RenderCompact added in v0.2.0

func (cv *ContextVisualizer) RenderCompact() string

RenderCompact renders a single-line summary of context usage.

Example: [42% | sys:2% mem:1% conv:26% repo:4% ctx:6% | 116K free]

func (*ContextVisualizer) RenderDetailed added in v0.2.0

func (cv *ContextVisualizer) RenderDetailed() string

RenderDetailed renders a full breakdown table of context usage by section.

func (*ContextVisualizer) TakeSnapshot added in v0.2.0

func (cv *ContextVisualizer) TakeSnapshot(turn int) ContextSnapshot

TakeSnapshot captures the current context state for a given turn number.

func (*ContextVisualizer) Update added in v0.2.0

func (cv *ContextVisualizer) Update(sections []ContextSection)

Update replaces the current sections and recalculates percentages.

func (*ContextVisualizer) WarnIfCritical added in v0.2.0

func (cv *ContextVisualizer) WarnIfCritical() string

WarnIfCritical returns a warning string if context usage is dangerously high. Returns empty string if usage is within safe limits.

type Convention added in v0.2.0

type Convention struct {
	Name        string
	Description string
	Pattern     *regexp.Regexp
	AntiPattern *regexp.Regexp
	Language    string
	Category    string // "naming", "structure", "error_handling", "testing", "style"
	Example     string
	Confidence  float64 // 0.0 to 1.0 — how confident we are this convention applies
}

Convention represents a single coding convention that can be enforced on generated code.

type ConventionSet added in v0.2.0

type ConventionSet struct {
	Conventions []Convention
	ProjectDir  string
	// contains filtered or unexported fields
}

ConventionSet holds a collection of conventions learned from a project.

func NewConventionSet added in v0.2.0

func NewConventionSet(projectDir string) *ConventionSet

NewConventionSet creates a new ConventionSet for the given project directory.

func (*ConventionSet) AddConvention added in v0.2.0

func (cs *ConventionSet) AddConvention(conv Convention)

AddConvention adds a new convention to the set.

func (*ConventionSet) Check added in v0.2.0

func (cs *ConventionSet) Check(code, file string) []Violation

Check validates generated code against all learned conventions and returns violations.

func (*ConventionSet) CheckErrorHandling added in v0.2.0

func (cs *ConventionSet) CheckErrorHandling(code string) []Violation

CheckErrorHandling verifies error handling matches the project's style.

func (*ConventionSet) CheckNaming added in v0.2.0

func (cs *ConventionSet) CheckNaming(code string) []Violation

CheckNaming verifies names follow the project's naming conventions.

func (*ConventionSet) CheckTestStyle added in v0.2.0

func (cs *ConventionSet) CheckTestStyle(code string) []Violation

CheckTestStyle verifies tests match the project's testing patterns.

func (*ConventionSet) Enforce added in v0.2.0

func (cs *ConventionSet) Enforce(code string) (string, []Violation)

Enforce auto-fixes violations where possible and returns fixed code plus remaining violations.

func (*ConventionSet) FormatConventions added in v0.2.0

func (cs *ConventionSet) FormatConventions() string

FormatConventions lists all learned conventions in a human-readable format.

func (*ConventionSet) LearnConventions added in v0.2.0

func (cs *ConventionSet) LearnConventions(projectDir string) error

LearnConventions scans existing code in projectDir to infer conventions: naming style, error handling, testing patterns, structure, and imports.

type ConversationBranch added in v0.2.0

type ConversationBranch struct {
	ID        string            `json:"id"`
	ParentID  string            `json:"parent_id"`
	Name      string            `json:"name"`
	ForkPoint int               `json:"fork_point"`
	Messages  []BranchMessage   `json:"messages"`
	CreatedAt time.Time         `json:"created_at"`
	Status    string            `json:"status"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

ConversationBranch represents a named branch in the conversation tree.

type ConversationSummarizer added in v0.2.0

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

ConversationSummarizer produces concise summaries of conversation messages at different granularities for compaction, session titles, and cross-session context.

func NewConversationSummarizer added in v0.2.0

func NewConversationSummarizer() *ConversationSummarizer

NewConversationSummarizer creates a new ConversationSummarizer.

func (*ConversationSummarizer) CompareMessages added in v0.2.0

func (cs *ConversationSummarizer) CompareMessages(before, after []SumMessage) string

CompareMessages describes what changed between two message states.

func (*ConversationSummarizer) Detailed added in v0.2.0

func (cs *ConversationSummarizer) Detailed(messages []SumMessage) string

Detailed produces a full multi-section summary.

func (*ConversationSummarizer) ExtractDecisions added in v0.2.0

func (cs *ConversationSummarizer) ExtractDecisions(messages []SumMessage) []string

ExtractDecisions identifies key decisions made during the conversation.

func (*ConversationSummarizer) ExtractFilesDiscussed added in v0.2.0

func (cs *ConversationSummarizer) ExtractFilesDiscussed(messages []SumMessage) []string

ExtractFilesDiscussed identifies files mentioned or modified in the conversation.

func (*ConversationSummarizer) ExtractTopics added in v0.2.0

func (cs *ConversationSummarizer) ExtractTopics(messages []SumMessage) []string

ExtractTopics identifies what was discussed in the conversation.

func (*ConversationSummarizer) FormatSummary added in v0.2.0

func (cs *ConversationSummarizer) FormatSummary(summary *Summary) string

FormatSummary formats a Summary into a human-readable string.

func (*ConversationSummarizer) GenerateTitle added in v0.2.0

func (cs *ConversationSummarizer) GenerateTitle(messages []SumMessage) string

GenerateTitle produces a short title suitable for labeling a session.

func (*ConversationSummarizer) OneLine added in v0.2.0

func (cs *ConversationSummarizer) OneLine(messages []SumMessage) string

OneLine produces a single concise sentence summarizing the conversation.

func (*ConversationSummarizer) Paragraph added in v0.2.0

func (cs *ConversationSummarizer) Paragraph(messages []SumMessage) string

Paragraph produces a 3-5 sentence summary covering what happened.

func (*ConversationSummarizer) Structured added in v0.2.0

func (cs *ConversationSummarizer) Structured(messages []SumMessage) *Summary

Structured produces a Summary with all fields populated.

func (*ConversationSummarizer) Summarize added in v0.2.0

func (cs *ConversationSummarizer) Summarize(messages []SumMessage, level SummaryLevel) *Summary

Summarize produces a Summary at the requested level from the given messages.

type CoreLoop added in v0.2.0

type CoreLoop struct {
	Client   ChatClient
	Registry *tool.Registry
	Messages []client.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 Cost

type Cost struct {
	Model            string
	PromptTokens     int
	CompletionTokens int
	CacheReadTokens  int
	CacheWriteTokens int
	TotalCostUSD     float64
	// contains filtered or unexported fields
}

Cost tracks token usage and estimated cost.

func (*Cost) Add

func (c *Cost) Add(prompt, completion int)

Add records token usage from a response.

func (*Cost) AddCacheTokens

func (c *Cost) AddCacheTokens(read, write int)

AddCacheTokens records cache token usage (priced at ~10% of input).

func (*Cost) Summary

func (c *Cost) Summary() string

Summary returns a formatted cost string.

func (*Cost) Total

func (c *Cost) Total() float64

Total returns the estimated total cost in USD.

func (*Cost) TotalUSD

func (c *Cost) TotalUSD() float64

TotalUSD returns the estimated total cost (same as Total — unified pricing).

type CostEntry

type CostEntry struct {
	SessionID string
	TaskGoal  string
	TotalCost float64
	Duration  time.Duration
	Success   bool
	Timestamp time.Time
}

CostEntry represents a single cost data point recorded at session end.

type CostOptimizer added in v0.2.0

type CostOptimizer struct {
	History         []RequestCost
	Recommendations []Recommendation
	ModelPricing    map[string]ModelPrice
	// contains filtered or unexported fields
}

CostOptimizer analyzes usage patterns and suggests ways to reduce API costs.

func NewCostOptimizer added in v0.2.0

func NewCostOptimizer() *CostOptimizer

NewCostOptimizer creates a CostOptimizer with default pricing for common models.

func (*CostOptimizer) Analyze added in v0.2.0

func (co *CostOptimizer) Analyze() []Recommendation

Analyze scans the history for optimization opportunities and returns recommendations.

func (*CostOptimizer) CostByModel added in v0.2.0

func (co *CostOptimizer) CostByModel() map[string]float64

CostByModel returns a map of model name to total cost.

func (*CostOptimizer) CostByTaskType added in v0.2.0

func (co *CostOptimizer) CostByTaskType() map[string]float64

CostByTaskType returns a map of task type to total cost.

func (*CostOptimizer) DailyCost added in v0.2.0

func (co *CostOptimizer) DailyCost() float64

DailyCost returns the sum of costs from the last 24 hours.

func (*CostOptimizer) FormatReport added in v0.2.0

func (co *CostOptimizer) FormatReport() string

FormatReport generates a formatted cost report string.

func (*CostOptimizer) ProjectSavings added in v0.2.0

func (co *CostOptimizer) ProjectSavings(recommendations []Recommendation) float64

ProjectSavings calculates the total estimated daily savings if all recommendations are applied.

func (*CostOptimizer) Record added in v0.2.0

func (co *CostOptimizer) Record(cost RequestCost)

Record adds a RequestCost entry to the history.

func (*CostOptimizer) WeeklyCost added in v0.2.0

func (co *CostOptimizer) WeeklyCost() float64

WeeklyCost returns the sum of costs from the last 7 days.

func (*CostOptimizer) WhatIf added in v0.2.0

func (co *CostOptimizer) WhatIf(model string) float64

WhatIf calculates what the total cost would have been if all requests used the given model.

type CostTracker

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

CostTracker records per-request cost entries for analytics and optimization. Data is appended to ~/.hawk/cost.jsonl for cross-session analysis.

func NewCostTracker

func NewCostTracker(sessionID string) *CostTracker

NewCostTracker creates a tracker that persists to ~/.hawk/cost.jsonl.

func (*CostTracker) Entries

func (ct *CostTracker) Entries() []analytics.CostEntry

Entries returns all recorded entries for this session.

func (*CostTracker) Record

func (ct *CostTracker) Record(entry analytics.CostEntry) error

Record adds a cost entry and persists it.

func (*CostTracker) SessionTotal

func (ct *CostTracker) SessionTotal() float64

SessionTotal returns total USD spent in the current session.

type CostTrackerInterface

type CostTrackerInterface interface {
	Record(entry CostEntry) error
	SessionTotal() float64
}

CostTrackerInterface abstracts cost recording and querying.

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

type CouncilRanking struct {
	Model   string
	Ranking string
}

CouncilRanking holds one model's ranking of responses.

type CouncilResponse

type CouncilResponse struct {
	Model    string
	Response string
}

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:

  1. Send query to all models in parallel, collect responses
  2. Anonymize responses, send ranking prompt to all models in parallel
  3. Send all responses + rankings to chairman for synthesis

type Counter added in v0.2.0

type Counter struct {
	Name  string
	Value int64
	// contains filtered or unexported fields
}

Counter tracks a named incrementing value.

type Critic

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

Critic provides fast pre-validation of patches using a cheap model before expensive execution. It generates a prompt for the cheap model and parses the response into a structured verdict.

func NewCritic

func NewCritic(model string) *Critic

NewCritic creates a new critic that will use the given model for screening.

func (*Critic) BuildPrompt

func (c *Critic) BuildPrompt(original, patched, intent string) string

BuildPrompt constructs a prompt for the cheap model to evaluate a patch.

func (*Critic) Model

func (c *Critic) Model() string

Model returns the model name used for pre-screening.

func (*Critic) ParseVerdict

func (c *Critic) ParseVerdict(response string) *PatchVerdict

ParseVerdict parses a model response into a structured PatchVerdict.

func (*Critic) PreScreenPatch

func (c *Critic) PreScreenPatch(originalContent, patchedContent, intent string) *PatchVerdict

PreScreenPatch asks the cheap model whether a patch looks correct given the stated intent. It builds a prompt, and returns a verdict. In this implementation, the caller is expected to send the prompt to the model and pass the response to ParseVerdict. This method constructs a PatchVerdict based on a simple heuristic comparison when no model call is available.

func (*Critic) ShouldBlock

func (c *Critic) ShouldBlock(verdict *PatchVerdict) bool

ShouldBlock returns true if the verdict indicates the patch should be blocked (verdict is "incorrect" with confidence > 0.8).

type CronExpr added in v0.2.0

type CronExpr struct {
	Minute     []int
	Hour       []int
	DayOfMonth []int
	Month      []int
	DayOfWeek  []int
}

CronExpr holds parsed cron expression fields as integer slices.

func ParseCron added in v0.2.0

func ParseCron(expression string) (*CronExpr, error)

ParseCron parses a standard 5-field cron expression. Fields: minute hour day-of-month month day-of-week Supports: * (any), */N (step), N-M (range), N,M,O (list)

type CronJob added in v0.2.0

type CronJob struct {
	ID         string
	Name       string
	Schedule   string
	Command    string
	Enabled    bool
	LastRun    *time.Time
	NextRun    *time.Time
	RunCount   int
	LastResult string
	LastError  string
	CreatedAt  time.Time
}

CronJob represents a scheduled recurring task.

type CronScheduler added in v0.2.0

type CronScheduler struct {
	Jobs    map[string]*CronJob
	Running bool
	// contains filtered or unexported fields
}

CronScheduler manages scheduled cron jobs and executes them when due.

func NewCronScheduler added in v0.2.0

func NewCronScheduler() *CronScheduler

NewCronScheduler creates an initialized CronScheduler.

func (*CronScheduler) AddJob added in v0.2.0

func (cs *CronScheduler) AddJob(name, schedule, command string) (*CronJob, error)

AddJob parses the schedule expression and registers a new job.

func (*CronScheduler) FormatJobs added in v0.2.0

func (cs *CronScheduler) FormatJobs() string

FormatJobs returns a human-readable representation of all scheduled jobs.

func (*CronScheduler) ListJobs added in v0.2.0

func (cs *CronScheduler) ListJobs() []*CronJob

ListJobs returns all jobs as a slice.

func (*CronScheduler) PauseJob added in v0.2.0

func (cs *CronScheduler) PauseJob(id string) error

PauseJob disables a job so it won't be executed.

func (*CronScheduler) RemoveJob added in v0.2.0

func (cs *CronScheduler) RemoveJob(id string) error

RemoveJob deletes a job by ID.

func (*CronScheduler) ResumeJob added in v0.2.0

func (cs *CronScheduler) ResumeJob(id string) error

ResumeJob re-enables a paused job and recalculates its next run time.

func (*CronScheduler) Start added in v0.2.0

func (cs *CronScheduler) Start(ctx context.Context, execFn func(string) (string, error))

Start launches a background goroutine that checks for due jobs every minute.

func (*CronScheduler) Stop added in v0.2.0

func (cs *CronScheduler) Stop()

Stop halts the scheduler.

type CrossSessionLearner added in v0.2.0

type CrossSessionLearner struct {
	Insights        []Insight           `json:"insights"`
	Conventions     []SessionConvention `json:"conventions"`
	FailurePatterns []FailurePattern    `json:"failure_patterns"`
	Dir             string              `json:"-"`
	// contains filtered or unexported fields
}

CrossSessionLearner transfers insights, conventions, and patterns across sessions.

func NewCrossSessionLearner added in v0.2.0

func NewCrossSessionLearner(dir string) *CrossSessionLearner

NewCrossSessionLearner creates a new CrossSessionLearner that persists data in dir.

func (*CrossSessionLearner) BuildSessionPrimer added in v0.2.0

func (c *CrossSessionLearner) BuildSessionPrimer(task string) string

BuildSessionPrimer formats all relevant learning for injection into a new session.

func (*CrossSessionLearner) Decay added in v0.2.0

func (c *CrossSessionLearner) Decay(factor float64)

Decay reduces confidence of old unused insights by the given factor.

func (*CrossSessionLearner) GetConventions added in v0.2.0

func (c *CrossSessionLearner) GetConventions() []SessionConvention

GetConventions returns all learned conventions.

func (*CrossSessionLearner) GetFailureResolutions added in v0.2.0

func (c *CrossSessionLearner) GetFailureResolutions(errorMsg string) []FailurePattern

GetFailureResolutions finds past failures matching an error message and returns them with their resolutions.

func (*CrossSessionLearner) GetRelevantInsights added in v0.2.0

func (c *CrossSessionLearner) GetRelevantInsights(task string, limit int) []Insight

GetRelevantInsights returns insights relevant to the current task, scored by keyword overlap, confidence, and recency.

func (*CrossSessionLearner) LearnConvention added in v0.2.0

func (c *CrossSessionLearner) LearnConvention(rule string, examples []string, source string)

LearnConvention records a project convention discovered during a session.

func (*CrossSessionLearner) LearnFromOutcome added in v0.2.0

func (c *CrossSessionLearner) LearnFromOutcome(task, approach string, success bool, toolsUsed []string, filesModified []string)

LearnFromOutcome records the result of a task attempt. If successful, it extracts an insight about what worked. If failed, it records a failure pattern.

func (*CrossSessionLearner) Load added in v0.2.0

func (c *CrossSessionLearner) Load() error

Load restores the learner state from disk.

func (*CrossSessionLearner) RecordFailure added in v0.2.0

func (c *CrossSessionLearner) RecordFailure(pattern, context, resolution string)

RecordFailure records a failure pattern and how it was resolved.

func (*CrossSessionLearner) Save added in v0.2.0

func (c *CrossSessionLearner) Save() error

Save persists the learner state to disk.

func (*CrossSessionLearner) Stats added in v0.2.0

func (c *CrossSessionLearner) Stats() LearnerStats

Stats returns aggregate statistics about the learner.

type DebugRecorder added in v0.2.0

type DebugRecorder struct {
	Sessions      []*DebugSession `json:"sessions"`
	ActiveSession *DebugSession   `json:"active_session,omitempty"`
	Dir           string          `json:"dir"`
	// contains filtered or unexported fields
}

DebugRecorder manages debug sessions, recording steps and persisting them for future reference.

func NewDebugRecorder added in v0.2.0

func NewDebugRecorder(dir string) *DebugRecorder

NewDebugRecorder creates a new DebugRecorder that persists sessions to the given directory.

func (*DebugRecorder) AddHypothesis added in v0.2.0

func (dr *DebugRecorder) AddHypothesis(description string)

AddHypothesis adds a new hypothesis to the active debug session.

func (*DebugRecorder) BuildDebugContext added in v0.2.0

func (dr *DebugRecorder) BuildDebugContext(symptom string) string

BuildDebugContext formats relevant past sessions as context for the agent.

func (*DebugRecorder) ConfirmHypothesis added in v0.2.0

func (dr *DebugRecorder) ConfirmHypothesis(index int, evidence string)

ConfirmHypothesis marks a hypothesis as tested and confirmed with evidence.

func (*DebugRecorder) EndSession added in v0.2.0

func (dr *DebugRecorder) EndSession(successful bool)

EndSession ends the active debug session and marks it as successful or not.

func (*DebugRecorder) FormatSession added in v0.2.0

func (dr *DebugRecorder) FormatSession(session *DebugSession) string

FormatSession produces a human-readable summary of a debug session.

func (*DebugRecorder) Load added in v0.2.0

func (dr *DebugRecorder) Load() error

Load reads previously persisted sessions from disk.

func (*DebugRecorder) RecordStep added in v0.2.0

func (dr *DebugRecorder) RecordStep(action, target, result, insight string)

RecordStep adds a step to the active debug session.

func (*DebugRecorder) RejectHypothesis added in v0.2.0

func (dr *DebugRecorder) RejectHypothesis(index int, evidence string)

RejectHypothesis marks a hypothesis as tested and rejected with evidence.

func (*DebugRecorder) Save added in v0.2.0

func (dr *DebugRecorder) Save() error

Save persists all sessions to disk as JSON.

func (*DebugRecorder) SearchSessions added in v0.2.0

func (dr *DebugRecorder) SearchSessions(symptom string) []*DebugSession

SearchSessions finds past sessions with symptoms similar to the given symptom.

func (*DebugRecorder) SetResolution added in v0.2.0

func (dr *DebugRecorder) SetResolution(resolution string)

SetResolution records the resolution for the active debug session.

func (*DebugRecorder) SetRootCause added in v0.2.0

func (dr *DebugRecorder) SetRootCause(cause string)

SetRootCause records the root cause for the active debug session.

func (*DebugRecorder) StartSession added in v0.2.0

func (dr *DebugRecorder) StartSession(symptom string) *DebugSession

StartSession begins a new debug session with the given symptom description.

type DebugSession added in v0.2.0

type DebugSession struct {
	ID                string       `json:"id"`
	StartTime         time.Time    `json:"start_time"`
	EndTime           *time.Time   `json:"end_time,omitempty"`
	Symptom           string       `json:"symptom"`
	RootCause         string       `json:"root_cause,omitempty"`
	Resolution        string       `json:"resolution,omitempty"`
	Steps             []DebugStep  `json:"steps"`
	FilesInvestigated []string     `json:"files_investigated"`
	HypothesesTested  []Hypothesis `json:"hypotheses_tested"`
	Successful        bool         `json:"successful"`
}

DebugSession captures a complete debugging workflow from symptom to resolution.

type DebugStep added in v0.2.0

type DebugStep struct {
	Index         int       `json:"index"`
	Action        string    `json:"action"` // "read", "grep", "test", "hypothesis", "fix_attempt"
	Target        string    `json:"target"`
	Result        string    `json:"result"`
	Timestamp     time.Time `json:"timestamp"`
	InsightGained string    `json:"insight_gained,omitempty"`
}

DebugStep records a single action taken during a debugging session.

type DecayEntry added in v0.2.0

type DecayEntry struct {
	ID           string
	Content      string
	Weight       float64
	CreatedAt    time.Time
	LastAccessed time.Time
	AccessCount  int
	Category     string
	Tokens       int
	Pinned       bool
}

DecayEntry represents a single piece of context with decay metadata.

type DecayStats added in v0.2.0

type DecayStats struct {
	TotalEntries int
	AvgWeight    float64
	Oldest       time.Time
	Newest       time.Time
	PinnedCount  int
	TotalTokens  int
}

DecayStats provides aggregate statistics about the context decay state.

type DecisionPoint

type DecisionPoint struct {
	TurnIndex    int
	Description  string                // what was decided
	Alternatives []string              // other options available
	Outcome      string                // "success", "failure", or "" (pending)
	Messages     []client.EyrieMessage // conversation state at this point
}

DecisionPoint captures a point in the conversation where the agent made a choice that can potentially be rolled back if it leads to failure.

type DegradationDetector added in v0.2.0

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

DegradationDetector monitors agent quality over turns and triggers recovery.

func NewDegradationDetector added in v0.2.0

func NewDegradationDetector(maxTurns int) *DegradationDetector

NewDegradationDetector creates a detector with default thresholds.

func (*DegradationDetector) IsDegraded added in v0.2.0

func (dd *DegradationDetector) IsDegraded() bool

IsDegraded returns whether quality has dropped.

func (*DegradationDetector) RecordTurn added in v0.2.0

func (dd *DegradationDetector) RecordTurn(toolName string, success bool)

RecordTurn logs a turn and checks for degradation.

func (*DegradationDetector) RecoveryAction added in v0.2.0

func (dd *DegradationDetector) RecoveryAction() string

RecoveryAction returns what to do when degradation is detected.

func (*DegradationDetector) Reset added in v0.2.0

func (dd *DegradationDetector) Reset()

Reset clears the detector state (e.g., after recovery or new task).

func (*DegradationDetector) Signal added in v0.2.0

Signal returns the type of degradation detected.

func (*DegradationDetector) Stats added in v0.2.0

func (dd *DegradationDetector) Stats() (turns, errors, consecutive int)

Stats returns current metrics.

type DegradationSignal added in v0.2.0

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 added in v0.2.0

type Dependency struct {
	Name               string
	CurrentVersion     string
	LatestVersion      string
	UpdateType         string // "major", "minor", "patch"
	IsDirectDep        bool
	HasBreakingChanges bool
	SecurityFix        bool
	Changelog          string
}

Dependency represents a single package dependency with version info.

type DependencyContextProvider added in v0.2.0

type DependencyContextProvider struct {
	ProjectDir string
}

DependencyContextProvider provides dependency information from project files.

func (*DependencyContextProvider) Description added in v0.2.0

func (d *DependencyContextProvider) Description() string

func (*DependencyContextProvider) Gather added in v0.2.0

func (d *DependencyContextProvider) Gather(ctx context.Context, query string) ([]ContextItem, error)

func (*DependencyContextProvider) Name added in v0.2.0

func (*DependencyContextProvider) TokenBudget added in v0.2.0

func (d *DependencyContextProvider) TokenBudget() int

type DependencyUpdater added in v0.2.0

type DependencyUpdater struct {
	ProjectDir string
	Language   string
	// contains filtered or unexported fields
}

DependencyUpdater detects outdated packages and helps update them safely.

func NewDependencyUpdater added in v0.2.0

func NewDependencyUpdater(projectDir string) *DependencyUpdater

NewDependencyUpdater creates a new DependencyUpdater for the given project directory.

func (*DependencyUpdater) ApplyUpdate added in v0.2.0

func (du *DependencyUpdater) ApplyUpdate(dep Dependency) error

ApplyUpdate applies a single dependency update using the appropriate package manager.

func (*DependencyUpdater) BatchUpdate added in v0.2.0

func (du *DependencyUpdater) BatchUpdate(deps []Dependency, maxRisk string) ([]string, []error)

BatchUpdate updates dependencies up to the specified risk level. maxRisk can be "patch", "minor", or "major" (includes all lower levels).

func (*DependencyUpdater) DetectLanguage added in v0.2.0

func (du *DependencyUpdater) DetectLanguage() string

DetectLanguage determines the project language by checking for known manifest files.

func (*DependencyUpdater) GeneratePlan added in v0.2.0

func (du *DependencyUpdater) GeneratePlan(deps []Dependency) *UpdatePlan

GeneratePlan creates an UpdatePlan from a list of dependencies. It prioritizes security fixes, then patch, minor, and major updates.

func (*DependencyUpdater) ListOutdated added in v0.2.0

func (du *DependencyUpdater) ListOutdated() ([]Dependency, error)

ListOutdated returns the list of outdated dependencies for the detected language.

type Diff3Conflict added in v0.2.0

type Diff3Conflict struct {
	BaseLines   []string
	OursLines   []string
	TheirsLines []string
	StartLine   int
}

Diff3Conflict represents a single conflict region in the merge.

type Diff3Region added in v0.2.0

type Diff3Region struct {
	Type        string // "unchanged", "ours", "theirs", "conflict"
	BaseStart   int
	BaseEnd     int
	OursLines   []string
	TheirsLines []string
}

Diff3Region represents a classified region in the three-way diff.

type Diff3Result added in v0.2.0

type Diff3Result struct {
	Merged       string
	Conflicts    []Diff3Conflict
	HasConflicts bool
	Stats        Diff3Stats
}

Diff3Result holds the outcome of a three-way merge.

func Merge3 added in v0.2.0

func Merge3(base, ours, theirs string) *Diff3Result

Merge3 performs a three-way merge using the diff3 algorithm. It splits base, ours, and theirs into lines, computes diff regions, and merges non-conflicting changes automatically while marking conflicts.

type Diff3Stats added in v0.2.0

type Diff3Stats struct {
	TotalLines    int
	ConflictCount int
	AutoMerged    int
	OursOnly      int
	TheirsOnly    int
}

Diff3Stats provides statistics about the merge operation.

type DiffHunk added in v0.2.0

type DiffHunk struct {
	OldStart int
	OldCount int
	NewStart int
	NewCount int
	Lines    []DiffLine
}

DiffHunk represents a contiguous block of changes with surrounding context.

func ComputeDiff added in v0.2.0

func ComputeDiff(oldContent, newContent string) []DiffHunk

ComputeDiff computes hunks between old and new content using Myers diff with 3 lines of context.

type DiffLine added in v0.2.0

type DiffLine struct {
	Type      string // "add", "remove", "context"
	Content   string
	OldLineNo int
	NewLineNo int
}

DiffLine represents a single line in a diff hunk.

func ComputeMyersDiff added in v0.2.0

func ComputeMyersDiff(a, b []string) []DiffLine

ComputeMyersDiff implements Myers' O(ND) diff algorithm returning an edit script. It finds a minimal edit distance between sequences a and b, then returns the result as a series of DiffLine entries (context, add, remove).

type DiffPreview added in v0.2.0

type DiffPreview struct {
	Changes   []FileChange
	CreatedAt time.Time
	SessionID string
	// contains filtered or unexported fields
}

DiffPreview holds all pending changes for review before they are committed/applied.

func NewDiffPreview added in v0.2.0

func NewDiffPreview() *DiffPreview

NewDiffPreview creates a new DiffPreview with a generated session ID.

func (*DiffPreview) Approve added in v0.2.0

func (dp *DiffPreview) Approve(path string)

Approve marks a specific file change as approved.

func (*DiffPreview) ApproveAll added in v0.2.0

func (dp *DiffPreview) ApproveAll()

ApproveAll marks all changes as approved.

func (*DiffPreview) Clear added in v0.2.0

func (dp *DiffPreview) Clear()

Clear removes all recorded changes.

func (*DiffPreview) GetApproved added in v0.2.0

func (dp *DiffPreview) GetApproved() []FileChange

GetApproved returns changes that have been approved.

func (*DiffPreview) GetPending added in v0.2.0

func (dp *DiffPreview) GetPending() []FileChange

GetPending returns changes that are neither approved nor rejected.

func (*DiffPreview) RecordChange added in v0.2.0

func (dp *DiffPreview) RecordChange(path, oldContent, newContent string)

RecordChange computes a unified diff between old and new content and records it.

func (*DiffPreview) Reject added in v0.2.0

func (dp *DiffPreview) Reject(path string, comment string)

Reject marks a specific file change as rejected with an optional comment.

func (*DiffPreview) RejectAll added in v0.2.0

func (dp *DiffPreview) RejectAll(comment string)

RejectAll marks all changes as rejected with an optional comment.

func (*DiffPreview) RenderAll added in v0.2.0

func (dp *DiffPreview) RenderAll() string

RenderAll renders all changes as a combined unified diff.

func (*DiffPreview) RenderSummary added in v0.2.0

func (dp *DiffPreview) RenderSummary() string

RenderSummary produces a compact summary of all pending changes.

type DiffReporter added in v0.2.0

type DiffReporter struct {
	ProjectDir string
	// contains filtered or unexported fields
}

DiffReporter generates comprehensive diff reports for a workspace.

func NewDiffReporter added in v0.2.0

func NewDiffReporter(projectDir string) *DiffReporter

NewDiffReporter creates a new DiffReporter for the given project directory.

func (*DiffReporter) GenerateFromGit added in v0.2.0

func (dr *DiffReporter) GenerateFromGit() (*WorkspaceDiffReport, error)

GenerateFromGit builds a WorkspaceDiffReport by running git diff commands in the project directory.

func (*DiffReporter) GenerateReport added in v0.2.0

func (dr *DiffReporter) GenerateReport(modifiedFiles map[string]string) *WorkspaceDiffReport

GenerateReport creates a WorkspaceDiffReport from a map of modified file paths to their diff content. The modifiedFiles map keys are file paths and values are unified diff content for each file.

type DiffSandbox

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

DiffSandbox holds pending file changes so the user can review diffs before applying.

func NewDiffSandbox

func NewDiffSandbox() *DiffSandbox

NewDiffSandbox creates a new, enabled DiffSandbox.

func (*DiffSandbox) Apply

func (ds *DiffSandbox) Apply(path string) error

Apply writes one pending change to disk and removes it from the sandbox.

func (*DiffSandbox) ApplyAll

func (ds *DiffSandbox) ApplyAll() (int, error)

ApplyAll writes all pending changes to disk and clears the sandbox.

func (*DiffSandbox) DiffAll

func (ds *DiffSandbox) DiffAll() string

DiffAll returns all diffs combined.

func (*DiffSandbox) DiffFor

func (ds *DiffSandbox) DiffFor(path string) string

DiffFor returns the unified diff for a single pending file.

func (*DiffSandbox) Disable

func (ds *DiffSandbox) Disable()

Disable deactivates the sandbox.

func (*DiffSandbox) Enable

func (ds *DiffSandbox) Enable()

Enable activates the sandbox.

func (*DiffSandbox) Format

func (ds *DiffSandbox) Format() string

Format returns a human-readable summary of all pending changes.

func (*DiffSandbox) Get

func (ds *DiffSandbox) Get(path string) *PendingChange

Get returns the pending change for a specific path, or nil.

func (*DiffSandbox) IsEnabled

func (ds *DiffSandbox) IsEnabled() bool

IsEnabled returns whether the sandbox is active.

func (*DiffSandbox) List

func (ds *DiffSandbox) List() []*PendingChange

List returns all pending changes sorted by path.

func (*DiffSandbox) Reject

func (ds *DiffSandbox) Reject(path string)

Reject discards the pending change for one file.

func (*DiffSandbox) RejectAll

func (ds *DiffSandbox) RejectAll()

RejectAll discards all pending changes.

func (*DiffSandbox) Stage

func (ds *DiffSandbox) Stage(path, action, oldContent, newContent string)

Stage records a pending file change and computes a unified diff.

type DiffSummarizer added in v0.2.0

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

DiffSummarizer parses unified diffs and produces human-readable summaries.

func NewDiffSummarizer added in v0.2.0

func NewDiffSummarizer() *DiffSummarizer

NewDiffSummarizer creates a new DiffSummarizer instance.

func (*DiffSummarizer) AssessImpact added in v0.2.0

func (ds *DiffSummarizer) AssessImpact(summary *DiffSummary) string

AssessImpact determines the impact level of the changes.

func (*DiffSummarizer) DetectChangeType added in v0.2.0

func (ds *DiffSummarizer) DetectChangeType(summary *DiffSummary) string

DetectChangeType classifies the overall change type based on file patterns and content.

func (*DiffSummarizer) FormatSummary added in v0.2.0

func (ds *DiffSummarizer) FormatSummary(summary *DiffSummary) string

FormatSummary produces a compact terminal-friendly summary display.

func (*DiffSummarizer) GenerateCommitMessage added in v0.2.0

func (ds *DiffSummarizer) GenerateCommitMessage(summary *DiffSummary) string

GenerateCommitMessage produces a conventional commit message from the summary.

func (*DiffSummarizer) GeneratePRSummary added in v0.2.0

func (ds *DiffSummarizer) GeneratePRSummary(summary *DiffSummary) string

GeneratePRSummary produces a multi-paragraph PR description from the summary.

func (*DiffSummarizer) Summarize added in v0.2.0

func (ds *DiffSummarizer) Summarize(diff string) *DiffSummary

Summarize parses a unified diff and returns a complete DiffSummary.

func (*DiffSummarizer) SummarizeFile added in v0.2.0

func (ds *DiffSummarizer) SummarizeFile(path string, hunks []string) *FileSummary

SummarizeFile analyzes hunks for a single file and produces a FileSummary.

type DiffSummary added in v0.2.0

type DiffSummary struct {
	Files          []FileSummary
	OverallSummary string
	ChangeType     string // "feature", "bugfix", "refactor", "test", "docs", "config"
	Impact         string // "low", "medium", "high"
	AffectedAreas  []string
}

DiffSummary holds the full summarized output of a diff analysis.

type Directive added in v0.2.0

type Directive struct {
	File    string
	Line    int
	Command string
	Context string
}

Directive is a parsed hawk: comment from source code.

func ScanDirectives added in v0.2.0

func ScanDirectives(dir string) []Directive

ScanDirectives finds all `// hawk: <command>` comments in source files.

type DistillExample added in v0.2.0

type DistillExample struct {
	ID                string    `json:"id"`
	SystemPrompt      string    `json:"system_prompt"`
	UserMessage       string    `json:"user_message"`
	AssistantResponse string    `json:"assistant_response"`
	ToolCalls         []string  `json:"tool_calls,omitempty"`
	Quality           float64   `json:"quality"`
	Model             string    `json:"model"`
	Tokens            int       `json:"tokens"`
	CreatedAt         time.Time `json:"created_at"`
	Tags              []string  `json:"tags,omitempty"`
}

DistillExample represents a single successful interaction captured for fine-tuning distillation.

type DistillStats added in v0.2.0

type DistillStats struct {
	TotalExamples int            `json:"total_examples"`
	AvgQuality    float64        `json:"avg_quality"`
	ByModel       map[string]int `json:"by_model"`
	ByTag         map[string]int `json:"by_tag"`
	TotalTokens   int            `json:"total_tokens"`
	EstimatedCost float64        `json:"estimated_cost"`
}

DistillStats holds aggregate statistics about the distillation pipeline.

type DistillationPipeline added in v0.2.0

type DistillationPipeline struct {
	Examples    []DistillExample `json:"examples"`
	Dir         string           `json:"dir"`
	TargetModel string           `json:"target_model"`
	SourceModel string           `json:"source_model"`
	MinQuality  float64          `json:"min_quality"`
	// contains filtered or unexported fields
}

DistillationPipeline collects successful interactions as fine-tuning examples to distill expensive model behavior into cheaper models.

func NewDistillationPipeline added in v0.2.0

func NewDistillationPipeline(dir string) *DistillationPipeline

NewDistillationPipeline creates a new distillation pipeline that stores data in dir.

func (*DistillationPipeline) Capture added in v0.2.0

func (dp *DistillationPipeline) Capture(system, user, assistant string, toolCalls []string, quality float64, model string)

Capture records a successful interaction as a training example. Only keeps the example if quality >= MinQuality.

func (*DistillationPipeline) Deduplicate added in v0.2.0

func (dp *DistillationPipeline) Deduplicate()

Deduplicate removes near-duplicate examples (>0.9 similarity based on content hashing and overlap).

func (*DistillationPipeline) ExportAnthropicFormat added in v0.2.0

func (dp *DistillationPipeline) ExportAnthropicFormat(path string) error

ExportAnthropicFormat exports examples in Anthropic fine-tuning format. Format: {"system":"...","messages":[{"role":"user","content":"..."},{"role":"assistant","content":"..."}]}

func (*DistillationPipeline) ExportJSONL added in v0.2.0

func (dp *DistillationPipeline) ExportJSONL(path string) error

ExportJSONL exports examples as JSONL format suitable for fine-tuning. Each line: {"messages":[{"role":"system","content":"..."},{"role":"user","content":"..."},{"role":"assistant","content":"..."}]}

func (*DistillationPipeline) ExportOpenAI added in v0.2.0

func (dp *DistillationPipeline) ExportOpenAI(path string) error

ExportOpenAI exports examples in OpenAI fine-tuning format. Format: {"messages":[{"role":"system","content":"..."},{"role":"user","content":"..."},{"role":"assistant","content":"..."}]}

func (*DistillationPipeline) Filter added in v0.2.0

func (dp *DistillationPipeline) Filter(minQuality float64, tags []string) []DistillExample

Filter returns examples matching the given minimum quality and any of the specified tags. If tags is empty, only quality filtering is applied.

func (*DistillationPipeline) FormatStats added in v0.2.0

func (dp *DistillationPipeline) FormatStats() string

FormatStats returns a human-readable summary of the distillation pipeline.

func (*DistillationPipeline) Load added in v0.2.0

func (dp *DistillationPipeline) Load() error

Load restores the pipeline state from disk.

func (*DistillationPipeline) Prune added in v0.2.0

func (dp *DistillationPipeline) Prune(maxExamples int)

Prune keeps only the top N examples by quality, discarding the rest.

func (*DistillationPipeline) Save added in v0.2.0

func (dp *DistillationPipeline) Save() error

Save persists the pipeline state to disk.

func (*DistillationPipeline) Stats added in v0.2.0

func (dp *DistillationPipeline) Stats() DistillStats

Stats computes aggregate statistics about the distillation pipeline.

type DocGenerator added in v0.2.0

type DocGenerator struct {
	ProjectDir     string
	OutputFormat   string // "markdown", "html"
	IncludePrivate bool
	MaxDepth       int
}

DocGenerator generates project documentation from code analysis.

func NewDocGenerator added in v0.2.0

func NewDocGenerator(projectDir string) *DocGenerator

NewDocGenerator creates a new DocGenerator for the given project directory.

func (*DocGenerator) Generate added in v0.2.0

func (dg *DocGenerator) Generate() (*ProjectDoc, error)

Generate scans the project directory and produces structured documentation.

func (*DocGenerator) InferDescription added in v0.2.0

func (dg *DocGenerator) InferDescription(projectDir string) string

InferDescription reads existing README for description, falls back to package doc, then go.mod.

type DocResult added in v0.2.0

type DocResult struct {
	Source    string  // source name that provided this result
	Title     string  // human-readable title
	Content   string  // documentation excerpt or summary
	URL       string  // full URL to the documentation page
	Relevance float64 // 0.0-1.0 relevance score
	Tokens    int     // estimated token count
}

DocResult represents a documentation reference matched for a task.

type DocSection added in v0.2.0

type DocSection struct {
	Title    string
	Content  string
	Children []DocSection
	Level    int
}

DocSection represents a section in the generated documentation.

type DocSource added in v0.2.0

type DocSource struct {
	Name     string   // e.g. "pkg.go.dev", "MDN"
	BaseURL  string   // e.g. "https://pkg.go.dev"
	Packages []string // known packages served by this source
	Language string   // "go", "python", "javascript", "typescript", "rust"
	Priority int      // higher = preferred when multiple sources match
}

DocSource represents an external documentation source for a language ecosystem.

type DocUpdate added in v0.2.0

type DocUpdate struct {
	File   string
	Line   int
	OldDoc string
	NewDoc string
	Symbol string
	Reason string // "signature_changed", "behavior_changed", "new_params", "outdated_reference"
}

DocUpdate represents a single documentation update suggestion.

type DocUpdater added in v0.2.0

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

DocUpdater detects stale documentation and suggests updates.

func NewDocUpdater added in v0.2.0

func NewDocUpdater() *DocUpdater

NewDocUpdater creates a new DocUpdater instance.

func (*DocUpdater) ApplyUpdates added in v0.2.0

func (du *DocUpdater) ApplyUpdates(updates []DocUpdate, content string) string

ApplyUpdates applies documentation fixes to file content.

func (*DocUpdater) DetectStaleDocumentation added in v0.2.0

func (du *DocUpdater) DetectStaleDocumentation(file, oldContent, newContent string) []DocUpdate

DetectStaleDocumentation compares old and new file content to find documentation that has become stale due to code changes.

func (*DocUpdater) FormatUpdates added in v0.2.0

func (du *DocUpdater) FormatUpdates(updates []DocUpdate) string

FormatUpdates formats documentation updates into a human-readable report.

func (*DocUpdater) GenerateDocUpdate added in v0.2.0

func (du *DocUpdater) GenerateDocUpdate(funcName, signature, oldDoc string) string

GenerateDocUpdate creates an updated doc comment based on the new signature.

func (*DocUpdater) ScanProjectForStaleDocs added in v0.2.0

func (du *DocUpdater) ScanProjectForStaleDocs(projectDir string) []DocUpdate

ScanProjectForStaleDocs walks the project directory and finds documentation that references non-existent symbols.

type Edit added in v0.2.0

type Edit struct {
	Type  string // "keep", "insert", "delete"
	Line  string
	Index int
}

Edit represents a single edit operation in an edit script.

func EditScript added in v0.2.0

func EditScript(from, to []string) []Edit

EditScript computes a minimal edit script to transform 'from' into 'to'.

type EditStrategy added in v0.2.0

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 added in v0.2.0

func SelectEditStrategy(fileLines int, changeDescription string) EditStrategy

SelectEditStrategy picks the optimal edit approach based on file size and change type.

type EfficientPrompter added in v0.2.0

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 added in v0.2.0

func NewEfficientPrompter() *EfficientPrompter

NewEfficientPrompter creates a new EfficientPrompter with all default strategies enabled.

func (*EfficientPrompter) DisableStrategy added in v0.2.0

func (ep *EfficientPrompter) DisableStrategy(name string)

DisableStrategy disables the named strategy.

func (*EfficientPrompter) EnableStrategy added in v0.2.0

func (ep *EfficientPrompter) EnableStrategy(name string)

EnableStrategy enables the named strategy.

func (*EfficientPrompter) EstimateSavings added in v0.2.0

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 added in v0.2.0

func (ep *EfficientPrompter) FormatEfficientStats() string

FormatEfficientStats returns a human-readable summary of token savings.

func (*EfficientPrompter) Optimize added in v0.2.0

func (ep *EfficientPrompter) Optimize(prompt string) *OptimizedResult

Optimize applies all enabled strategies to the given prompt and returns an OptimizedResult.

func (*EfficientPrompter) OptimizeMessages added in v0.2.0

func (ep *EfficientPrompter) OptimizeMessages(messages []PromptMsg) []PromptMsg

OptimizeMessages compresses older messages more aggressively while keeping recent messages mostly intact.

func (*EfficientPrompter) OptimizeOutput added in v0.2.0

func (ep *EfficientPrompter) OptimizeOutput(output string) string

OptimizeOutput removes noise from tool outputs and collapses repeated lines.

type EfficientStats added in v0.2.0

type EfficientStats struct {
	OriginalTokens  int
	OptimizedTokens int
	TotalSavings    int
	CallCount       int
}

EfficientStats tracks cumulative token savings across all optimization calls.

type EnrichedError added in v0.2.0

type EnrichedError struct {
	Original    string
	Title       string
	Explanation string
	Suggestions []string
	Examples    []string
	Severity    string
	Recoverable bool
}

EnrichedError is the result of enriching a raw error string with contextual help.

type EnvironmentContextProvider added in v0.2.0

type EnvironmentContextProvider struct{}

EnvironmentContextProvider provides system and environment information.

func (*EnvironmentContextProvider) Description added in v0.2.0

func (e *EnvironmentContextProvider) Description() string

func (*EnvironmentContextProvider) Gather added in v0.2.0

func (*EnvironmentContextProvider) Name added in v0.2.0

func (*EnvironmentContextProvider) TokenBudget added in v0.2.0

func (e *EnvironmentContextProvider) TokenBudget() int

type ErrorContext added in v0.2.0

type ErrorContext struct {
	Patterns map[string]*ErrorHelp
	// contains filtered or unexported fields
}

ErrorContext provides context-aware error messages by matching error strings against known patterns and returning rich contextual help.

func NewErrorContext added in v0.2.0

func NewErrorContext() *ErrorContext

NewErrorContext creates an ErrorContext pre-loaded with 30+ common error patterns covering Go, Python, JS/TS, Git, system errors, and hawk-specific errors.

func (*ErrorContext) AddPattern added in v0.2.0

func (ec *ErrorContext) AddPattern(pattern string, help ErrorHelp) error

AddPattern registers a new error pattern with its associated help information. Returns an error if the pattern string fails to compile as a regular expression.

func (*ErrorContext) Enrich added in v0.2.0

func (ec *ErrorContext) Enrich(err string) *EnrichedError

Enrich takes a raw error string and returns an EnrichedError with contextual help if the error matches any known pattern. Returns nil if no pattern matches. When multiple patterns match, the longest matching pattern string is preferred for deterministic results.

func (*ErrorContext) IsRecoverable added in v0.2.0

func (ec *ErrorContext) IsRecoverable(err string) bool

IsRecoverable returns true if the given error is classified as recoverable, meaning the operation can potentially succeed if retried or modified.

func (*ErrorContext) SuggestFix added in v0.2.0

func (ec *ErrorContext) SuggestFix(err string) string

SuggestFix returns a quick one-liner suggestion for fixing the given error. Returns an empty string if no suggestion is available.

type ErrorContextProvider added in v0.2.0

type ErrorContextProvider struct {
	LogDir string
}

ErrorContextProvider provides recent build/test errors as context.

func (*ErrorContextProvider) Description added in v0.2.0

func (e *ErrorContextProvider) Description() string

func (*ErrorContextProvider) Gather added in v0.2.0

func (e *ErrorContextProvider) Gather(ctx context.Context, query string) ([]ContextItem, error)

func (*ErrorContextProvider) Name added in v0.2.0

func (e *ErrorContextProvider) Name() string

func (*ErrorContextProvider) TokenBudget added in v0.2.0

func (e *ErrorContextProvider) TokenBudget() int

type ErrorGroup added in v0.2.0

type ErrorGroup struct {
	ID         string          `json:"id"`
	Pattern    string          `json:"pattern"`
	Instances  []ErrorInstance `json:"instances"`
	Count      int             `json:"count"`
	FirstSeen  time.Time       `json:"first_seen"`
	LastSeen   time.Time       `json:"last_seen"`
	Resolution string          `json:"resolution"`
	Status     string          `json:"status"` // "active", "resolved", "recurring"
}

ErrorGroup clusters similar errors together to track patterns and resolutions.

type ErrorGrouper added in v0.2.0

type ErrorGrouper struct {
	Groups map[string]*ErrorGroup
	// contains filtered or unexported fields
}

ErrorGrouper clusters similar errors to avoid repeating fix attempts.

func NewErrorGrouper added in v0.2.0

func NewErrorGrouper() *ErrorGrouper

NewErrorGrouper creates a new ErrorGrouper with an initialized groups map.

func (*ErrorGrouper) Add added in v0.2.0

func (eg *ErrorGrouper) Add(errorMsg, file string, line int, context string) *ErrorGroup

Add records an error occurrence, finding or creating the appropriate group. It returns the group the error was added to.

func (*ErrorGrouper) FindGroup added in v0.2.0

func (eg *ErrorGrouper) FindGroup(errorMsg string) *ErrorGroup

FindGroup returns the group matching the given error message, or nil if none exists.

func (*ErrorGrouper) FormatGroups added in v0.2.0

func (eg *ErrorGrouper) FormatGroups() string

FormatGroups returns a human-readable summary of all error groups.

func (*ErrorGrouper) GetActive added in v0.2.0

func (eg *ErrorGrouper) GetActive() []*ErrorGroup

GetActive returns all groups with "active" or "recurring" status.

func (*ErrorGrouper) GetResolution added in v0.2.0

func (eg *ErrorGrouper) GetResolution(errorMsg string) string

GetResolution returns the resolution for a previously resolved error pattern. Returns an empty string if the error is unknown or unresolved.

func (*ErrorGrouper) IsKnown added in v0.2.0

func (eg *ErrorGrouper) IsKnown(errorMsg string) bool

IsKnown reports whether this error pattern has been seen before.

func (*ErrorGrouper) MarkResolved added in v0.2.0

func (eg *ErrorGrouper) MarkResolved(groupID, resolution string)

MarkResolved marks the group with the given ID as resolved with the provided resolution.

func (*ErrorGrouper) Prune added in v0.2.0

func (eg *ErrorGrouper) Prune(maxAge time.Duration)

Prune removes resolved groups older than maxAge.

type ErrorHelp added in v0.2.0

type ErrorHelp struct {
	Pattern     *regexp.Regexp
	Title       string
	Explanation string
	Suggestions []string
	Examples    []string
	DocURL      string
	AutoFix     string
}

ErrorHelp defines the contextual help associated with a recognized error pattern.

type ErrorInstance added in v0.2.0

type ErrorInstance struct {
	Message   string    `json:"message"`
	File      string    `json:"file"`
	Line      int       `json:"line"`
	Timestamp time.Time `json:"timestamp"`
	Context   string    `json:"context"`
}

ErrorInstance represents a single occurrence of an error.

type ErrorLearner added in v0.2.0

type ErrorLearner struct {
	Patterns map[string]*LearnedPattern
	// contains filtered or unexported fields
}

ErrorLearner stores and matches error patterns to provide fix suggestions.

func NewErrorLearner added in v0.2.0

func NewErrorLearner() *ErrorLearner

NewErrorLearner creates an ErrorLearner pre-loaded with common error patterns.

func (*ErrorLearner) BuildFixSuggestion added in v0.2.0

func (el *ErrorLearner) BuildFixSuggestion(errorMsg string) string

BuildFixSuggestion matches the error and returns a formatted fix suggestion.

func (*ErrorLearner) Export added in v0.2.0

func (el *ErrorLearner) Export() ([]byte, error)

Export serializes all patterns to JSON for persistence.

func (*ErrorLearner) Import added in v0.2.0

func (el *ErrorLearner) Import(data []byte) error

Import loads patterns from JSON data, merging with existing patterns.

func (*ErrorLearner) Learn added in v0.2.0

func (el *ErrorLearner) Learn(errorMsg, fix, language, category string)

Learn records a new error pattern or updates an existing one.

func (*ErrorLearner) MatchLearned added in v0.2.0

func (el *ErrorLearner) MatchLearned(errorMsg string) []*LearnedPattern

MatchLearned finds all learned patterns matching the error message, sorted by confidence (highest first).

func (*ErrorLearner) PruneWeak added in v0.2.0

func (el *ErrorLearner) PruneWeak(minConfidence float64)

PruneWeak removes patterns with confidence below the given threshold.

func (*ErrorLearner) RecordFailure added in v0.2.0

func (el *ErrorLearner) RecordFailure(patternID string)

RecordFailure increments the failure count and reduces confidence for a pattern.

func (*ErrorLearner) RecordSuccess added in v0.2.0

func (el *ErrorLearner) RecordSuccess(patternID string)

RecordSuccess increments the success count and boosts confidence for a pattern.

func (*ErrorLearner) Stats added in v0.2.0

func (el *ErrorLearner) Stats() ErrorLearnerStats

Stats returns aggregate statistics about the learner's patterns.

type ErrorLearnerStats added in v0.2.0

type ErrorLearnerStats struct {
	TotalPatterns int            `json:"total_patterns"`
	ByCategory    map[string]int `json:"by_category"`
	ByLanguage    map[string]int `json:"by_language"`
	AvgConfidence float64        `json:"avg_confidence"`
}

ErrorLearnerStats holds aggregate statistics about the error learner.

type ErrorPattern

type ErrorPattern struct {
	Trigger    string    `json:"trigger"`    // error message pattern
	RootCause  string    `json:"root_cause"` // why it happens
	Resolution string    `json:"resolution"` // how to fix it
	HitCount   int       `json:"hit_count"`  // times encountered
	LastSeen   time.Time `json:"last_seen"`
}

ErrorPattern records a known error trigger, root cause, and resolution.

type ErrorPatternDB

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

ErrorPatternDB learns from tool failures and prevents repeating mistakes.

func NewErrorPatternDB

func NewErrorPatternDB() *ErrorPatternDB

NewErrorPatternDB creates a database backed by ~/.hawk/error_patterns.json.

func (*ErrorPatternDB) FormatHints

func (db *ErrorPatternDB) FormatHints(errorMsg string) string

FormatHints returns actionable hints for an error from known patterns.

func (*ErrorPatternDB) Match

func (db *ErrorPatternDB) Match(errorMsg string) []ErrorPattern

Match finds patterns that match the given error message.

func (*ErrorPatternDB) Record

func (db *ErrorPatternDB) Record(trigger, rootCause, resolution string)

Record adds or updates an error pattern.

type ErrorRecovery added in v0.2.0

type ErrorRecovery struct {
	Strategies  map[string]*RecoveryStrategy
	History     []RecoveryAttempt
	MaxAttempts int
	// contains filtered or unexported fields
}

ErrorRecovery manages automatic recovery strategies for common errors.

func NewErrorRecovery added in v0.2.0

func NewErrorRecovery() *ErrorRecovery

NewErrorRecovery creates an ErrorRecovery instance preloaded with built-in strategies.

func (*ErrorRecovery) BuildRecoveryPrompt added in v0.2.0

func (er *ErrorRecovery) BuildRecoveryPrompt(result *RecoveryResult) string

BuildRecoveryPrompt formats a recovery result into a human-readable prompt suitable for an agent to understand and act on.

func (*ErrorRecovery) FormatHistory added in v0.2.0

func (er *ErrorRecovery) FormatHistory(limit int) string

FormatHistory returns a formatted string of the most recent recovery attempts.

func (*ErrorRecovery) Recover added in v0.2.0

func (er *ErrorRecovery) Recover(err error, ctx *RecoveryContext) (*RecoveryResult, error)

Recover attempts to recover from the given error using matching strategies.

func (*ErrorRecovery) RegisterStrategy added in v0.2.0

func (er *ErrorRecovery) RegisterStrategy(strategy *RecoveryStrategy)

RegisterStrategy adds or replaces a recovery strategy.

func (*ErrorRecovery) ShouldRetry added in v0.2.0

func (er *ErrorRecovery) ShouldRetry(err error) bool

ShouldRetry checks whether the given error matches any known recoverable pattern.

func (*ErrorRecovery) SuccessRate added in v0.2.0

func (er *ErrorRecovery) SuccessRate() float64

SuccessRate returns the overall success rate of recovery attempts (0.0 to 1.0).

type Event added in v0.2.0

type Event struct {
	Type    EventType
	Payload interface{}
}

Event is a typed event in the system.

type EventBus added in v0.2.0

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

EventBus is a lightweight pub/sub system for decoupling hawk components.

func NewEventBus added in v0.2.0

func NewEventBus() *EventBus

NewEventBus creates a new event bus.

func (*EventBus) Publish added in v0.2.0

func (eb *EventBus) Publish(event Event)

Publish sends an event to all subscribers of that type.

func (*EventBus) Subscribe added in v0.2.0

func (eb *EventBus) Subscribe(eventType EventType) chan Event

Subscribe returns a channel that receives events of the given type.

func (*EventBus) Unsubscribe added in v0.2.0

func (eb *EventBus) Unsubscribe(eventType EventType, ch chan Event)

Unsubscribe removes a channel from receiving events.

type EventType added in v0.2.0

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 struct {
	EM *memory.EvolvingMemory
}

EvolvingMemoryAdapter bridges memory.EvolvingMemory to the EvolvingMemoryInterface.

func (*EvolvingMemoryAdapter) Format

func (a *EvolvingMemoryAdapter) Format() string

func (*EvolvingMemoryAdapter) Learn

func (a *EvolvingMemoryAdapter) Learn(pattern, lesson string) error

func (*EvolvingMemoryAdapter) Retrieve

func (a *EvolvingMemoryAdapter) Retrieve(query string) []string

type EvolvingMemoryInterface

type EvolvingMemoryInterface interface {
	Learn(pattern, lesson string) error
	Retrieve(query string) []string
	Format() string
}

EvolvingMemoryInterface abstracts guideline retrieval and learning so the lifecycle can be tested without real storage.

type ExecutionPlan added in v0.2.0

type ExecutionPlan struct {
	Steps              []ExecutionStep
	TotalEstimatedTime time.Duration
	Parallelizable     bool
	Dependencies       map[string][]string // step ID -> list of step IDs it depends on
}

ExecutionPlan represents the full plan for executing a batch of tool calls, including ordering, parallelization groups, and timing estimates.

type ExecutionPlanner added in v0.2.0

type ExecutionPlanner struct {
	ToolTimings map[string]time.Duration
	// contains filtered or unexported fields
}

ExecutionPlanner analyzes tool calls and determines optimal execution order and parallelization opportunities based on dependency analysis and timing data.

func NewExecutionPlanner added in v0.2.0

func NewExecutionPlanner() *ExecutionPlanner

NewExecutionPlanner creates an ExecutionPlanner with default timing estimates for common tool operations.

func (*ExecutionPlanner) EstimateDuration added in v0.2.0

func (ep *ExecutionPlanner) EstimateDuration(plan *ExecutionPlan) time.Duration

EstimateDuration calculates the total estimated execution time for a plan, accounting for parallelism within groups. The total time is the sum of the maximum duration within each group.

func (*ExecutionPlanner) FindDependencies added in v0.2.0

func (ep *ExecutionPlanner) FindDependencies(calls []PlannedCall) map[string][]string

FindDependencies builds a dependency graph from the planned calls based on file target analysis. A write/edit to file X creates a dependency for any subsequent read/edit of the same file.

func (*ExecutionPlanner) FormatPlan added in v0.2.0

func (ep *ExecutionPlanner) FormatPlan(plan *ExecutionPlan) string

FormatPlan produces a human-readable representation of the execution plan showing groups, parallelism, and timing estimates.

func (*ExecutionPlanner) GroupParallel added in v0.2.0

func (ep *ExecutionPlanner) GroupParallel(plan *ExecutionPlan) [][]ExecutionStep

GroupParallel groups execution steps that can run simultaneously into batches. Steps within the same group have no mutual dependencies and can execute in parallel.

func (*ExecutionPlanner) Optimize added in v0.2.0

func (ep *ExecutionPlanner) Optimize(plan *ExecutionPlan) *ExecutionPlan

Optimize reorders plan steps to minimize total execution time by maximizing parallelism. It reassigns priorities and groups to achieve the optimal schedule.

func (*ExecutionPlanner) Plan added in v0.2.0

func (ep *ExecutionPlanner) Plan(toolCalls []PlannedCall) *ExecutionPlan

Plan analyzes the given tool calls for dependencies and groups them into an optimized execution plan that maximizes parallelism while respecting ordering constraints.

func (*ExecutionPlanner) RecordTiming added in v0.2.0

func (ep *ExecutionPlanner) RecordTiming(tool string, duration time.Duration)

RecordTiming updates the timing estimate for a tool based on actual observed duration. Uses exponential moving average to smooth estimates.

type ExecutionStep added in v0.2.0

type ExecutionStep struct {
	ID                string
	ToolName          string
	Args              map[string]interface{}
	DependsOn         []string
	EstimatedDuration time.Duration
	CanParallel       bool
	Priority          int
	Group             int
}

ExecutionStep represents a single tool invocation within an execution plan.

type Experience added in v0.2.0

type Experience struct {
	ID            string        `json:"id"`
	Task          string        `json:"task"`
	Approach      string        `json:"approach"`
	Steps         []string      `json:"steps"`
	Outcome       string        `json:"outcome"`
	ToolsUsed     []string      `json:"tools_used"`
	FilesModified []string      `json:"files_modified"`
	TokensUsed    int           `json:"tokens_used"`
	Duration      time.Duration `json:"duration"`
	Score         float64       `json:"score"`
	Tags          []string      `json:"tags"`
	CreatedAt     time.Time     `json:"created_at"`
	UsedCount     int           `json:"used_count"`
}

Experience represents a single recorded task completion with its context and outcome.

type ExperienceStats added in v0.2.0

type ExperienceStats struct {
	TotalExperiences int            `json:"total_experiences"`
	AvgScore         float64        `json:"avg_score"`
	AvgTokens        int            `json:"avg_tokens"`
	AvgDuration      time.Duration  `json:"avg_duration"`
	ByOutcome        map[string]int `json:"by_outcome"`
	TopTags          []string       `json:"top_tags"`
	TopTools         []string       `json:"top_tools"`
}

ExperienceStats holds aggregate statistics about the experience store.

type ExperienceStore added in v0.2.0

type ExperienceStore struct {
	Experiences []*Experience
	Dir         string
	// contains filtered or unexported fields
}

ExperienceStore manages a collection of experiences with persistence.

func NewExperienceStore added in v0.2.0

func NewExperienceStore(dir string) *ExperienceStore

NewExperienceStore creates a new ExperienceStore that persists to the given directory.

func (*ExperienceStore) BuildExperienceContext added in v0.2.0

func (es *ExperienceStore) BuildExperienceContext(task string, maxTokens int) string

BuildExperienceContext formats relevant experiences for prompt injection.

func (*ExperienceStore) Deduplicate added in v0.2.0

func (es *ExperienceStore) Deduplicate() int

Deduplicate removes experiences that are too similar to each other, keeping the one with the higher score.

func (*ExperienceStore) FindRelevant added in v0.2.0

func (es *ExperienceStore) FindRelevant(task string, limit int) []*Experience

FindRelevant returns the most relevant experiences for a given task description.

func (*ExperienceStore) Generalize added in v0.2.0

func (es *ExperienceStore) Generalize(exp *Experience) *Experience

Generalize creates a generalized version of an experience by stripping specific details.

func (*ExperienceStore) Load added in v0.2.0

func (es *ExperienceStore) Load() error

Load reads experiences from the JSON file in the store directory.

func (*ExperienceStore) Prune added in v0.2.0

func (es *ExperienceStore) Prune(maxAge time.Duration, minScore float64) int

Prune removes experiences older than maxAge or below minScore.

func (*ExperienceStore) Record added in v0.2.0

func (es *ExperienceStore) Record(task, approach, outcome string, steps, tools, files []string, tokens int, duration time.Duration) *Experience

Record creates a new experience entry from a completed task.

func (*ExperienceStore) Save added in v0.2.0

func (es *ExperienceStore) Save() error

Save persists all experiences to a JSON file in the store directory.

func (*ExperienceStore) Stats added in v0.2.0

func (es *ExperienceStore) Stats() ExperienceStats

Stats returns aggregate statistics about the experience store.

type ExperimentLoop added in v0.2.0

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 added in v0.2.0

func NewExperimentLoop(workDir, validateCmd string, maxIters int) *ExperimentLoop

NewExperimentLoop creates a loop with sensible defaults for coding.

func (*ExperimentLoop) Run added in v0.2.0

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 added in v0.2.0

func (el *ExperimentLoop) Summary() string

Summary returns a formatted summary of all experiments.

type ExperimentResult added in v0.2.0

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 ExplanationSection added in v0.2.0

type ExplanationSection struct {
	Title   string
	Content string
	CodeRef string
}

ExplanationSection is a titled portion of an explanation with optional code reference.

type ExternalDocs added in v0.2.0

type ExternalDocs struct {
	Sources   []DocSource
	Cache     map[string]*DocResult
	MaxTokens int
	// contains filtered or unexported fields
}

ExternalDocs manages external documentation sources and finds relevant docs for coding tasks. Inspired by gpt-pilot's external_docs agent.

func NewExternalDocs added in v0.2.0

func NewExternalDocs() *ExternalDocs

NewExternalDocs creates an ExternalDocs instance pre-loaded with known sources for Go, Python, JavaScript/TypeScript, and Rust ecosystems.

func (*ExternalDocs) BuildDocContext added in v0.2.0

func (ed *ExternalDocs) BuildDocContext(results []DocResult, budget int) string

BuildDocContext formats documentation results into a string suitable for prompt injection, staying within the given token budget.

func (*ExternalDocs) ExtractPackageRefs added in v0.2.0

func (ed *ExternalDocs) ExtractPackageRefs(text string) []string

ExtractPackageRefs finds package/library names mentioned in text by matching against the known package database.

func (*ExternalDocs) FindRelevant added in v0.2.0

func (ed *ExternalDocs) FindRelevant(task string, language string, limit int) []DocResult

FindRelevant analyzes a task description and returns relevant documentation references, limited to the specified count.

func (*ExternalDocs) FormatResults added in v0.2.0

func (ed *ExternalDocs) FormatResults(results []DocResult) string

FormatResults produces a human-readable summary of documentation results.

func (*ExternalDocs) RegisterSource added in v0.2.0

func (ed *ExternalDocs) RegisterSource(source DocSource)

RegisterSource adds a new documentation source to the registry.

type FailureLayer added in v0.2.0

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 added in v0.2.0

func (l FailureLayer) String() string

type FailurePattern added in v0.2.0

type FailurePattern struct {
	ID          string    `json:"id"`
	Pattern     string    `json:"pattern"`
	Context     string    `json:"context"`
	Resolution  string    `json:"resolution"`
	Language    string    `json:"language"`
	Occurrences int       `json:"occurrences"`
	LastSeen    time.Time `json:"last_seen"`
}

FailurePattern represents a recorded failure and its resolution.

type FailureRecord added in v0.2.0

type FailureRecord struct {
	Provider      string
	Model         string
	ErrorType     string // "rate_limit", "timeout", "server_error", "invalid_request", "auth"
	ErrorMsg      string
	Timestamp     time.Time
	RetryCount    int
	Recovered     bool
	RecoveryDelay time.Duration
}

FailureRecord captures information about a failure for learning.

type Feedback added in v0.2.0

type Feedback struct {
	ID        string    `json:"id"`
	SessionID string    `json:"session_id"`
	Rating    int       `json:"rating"`
	Comment   string    `json:"comment"`
	Category  string    `json:"category"`
	Context   string    `json:"context"`
	Timestamp time.Time `json:"timestamp"`
	TaskType  string    `json:"task_type"`
}

Feedback represents explicit user feedback on an interaction.

type FeedbackCollector added in v0.2.0

type FeedbackCollector struct {
	Entries         []Feedback       `json:"entries"`
	ImplicitSignals []ImplicitSignal `json:"implicit_signals"`
	Dir             string           `json:"dir"`
	// contains filtered or unexported fields
}

FeedbackCollector gathers explicit and implicit user satisfaction signals and uses them to identify trends and improvement opportunities.

func NewFeedbackCollector added in v0.2.0

func NewFeedbackCollector(dir string) *FeedbackCollector

NewFeedbackCollector creates a new FeedbackCollector that persists data to dir.

func (*FeedbackCollector) FormatReport added in v0.2.0

func (fc *FeedbackCollector) FormatReport() string

FormatReport generates a human-readable feedback report.

func (*FeedbackCollector) GetByCategory added in v0.2.0

func (fc *FeedbackCollector) GetByCategory(category string) []Feedback

GetByCategory returns all feedback entries matching the given category.

func (*FeedbackCollector) GetSatisfactionScore added in v0.2.0

func (fc *FeedbackCollector) GetSatisfactionScore() float64

GetSatisfactionScore computes a weighted average satisfaction score from all signals. Explicit ratings are weighted 3x compared to implicit signals. Returns a value between 0.0 and 5.0.

func (*FeedbackCollector) GetTrends added in v0.2.0

func (fc *FeedbackCollector) GetTrends() string

GetTrends analyzes recent feedback to identify satisfaction trends.

func (*FeedbackCollector) IdentifyIssues added in v0.2.0

func (fc *FeedbackCollector) IdentifyIssues() []string

IdentifyIssues analyzes negative feedback patterns and returns actionable insights.

func (*FeedbackCollector) Load added in v0.2.0

func (fc *FeedbackCollector) Load() error

Load reads persisted feedback data from disk.

func (*FeedbackCollector) RecordExplicit added in v0.2.0

func (fc *FeedbackCollector) RecordExplicit(rating int, comment, category, sessionID, taskType string) error

RecordExplicit records explicit user feedback with a rating and optional comment. Rating must be between 1 and 5. Category must be one of: quality, speed, accuracy, helpfulness.

func (*FeedbackCollector) RecordImplicit added in v0.2.0

func (fc *FeedbackCollector) RecordImplicit(signal ImplicitSignal) error

RecordImplicit records an implicit satisfaction signal inferred from user behavior. Signal types: accepted (positive), rejected/undone/retried (negative), edited (neutral-negative).

func (*FeedbackCollector) Save added in v0.2.0

func (fc *FeedbackCollector) Save() error

Save persists the feedback data to disk.

type FewShotExample

type FewShotExample struct {
	Prompt    string    `json:"prompt"`
	Response  string    `json:"response"`
	TaskType  string    `json:"task_type"`
	Quality   float64   `json:"quality"` // 0-1, based on whether output was kept
	CreatedAt time.Time `json:"created_at"`
	UsedCount int       `json:"used_count"`
}

FewShotExample is a recorded successful interaction.

type FewShotStore

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

FewShotStore collects successful (prompt, response) pairs and injects the most relevant as few-shot examples into the system prompt.

func NewFewShotStore

func NewFewShotStore() *FewShotStore

NewFewShotStore creates a store backed by ~/.hawk/fewshot.json.

func (*FewShotStore) FormatForPrompt

func (fs *FewShotStore) FormatForPrompt(prompt string) string

FormatForPrompt returns few-shot examples formatted for system prompt injection.

func (*FewShotStore) Record

func (fs *FewShotStore) Record(prompt, response, taskType string)

Record saves a successful interaction as a potential few-shot example.

func (*FewShotStore) Retrieve

func (fs *FewShotStore) Retrieve(prompt string, topK int) []FewShotExample

Retrieve finds the most relevant few-shot examples for a given prompt.

type FieldDoc added in v0.2.0

type FieldDoc struct {
	Name string
	Type string
	Tag  string
	Desc string
}

FieldDoc represents documentation for a struct field.

type FieldSpec added in v0.2.0

type FieldSpec struct {
	Type        string // "string", "number", "boolean", "array", "object"
	Required    bool
	MinLength   int
	MaxLength   int
	Pattern     string
	Enum        []string
	Description string
}

FieldSpec describes constraints on a single field.

type FileChange added in v0.2.0

type FileChange struct {
	Path       string
	Type       string // "modified", "created", "deleted", "renamed"
	OldContent string
	NewContent string
	Hunks      []DiffHunk
	Stats      ChangeStats
	Approved   bool
	Rejected   bool
	Comment    string
}

FileChange represents a single file modification in the workspace.

type FileContextProvider added in v0.2.0

type FileContextProvider struct {
	RepoDir  string
	MaxFiles int
}

FileContextProvider provides recently modified files as context.

func (*FileContextProvider) Description added in v0.2.0

func (f *FileContextProvider) Description() string

func (*FileContextProvider) Gather added in v0.2.0

func (f *FileContextProvider) Gather(ctx context.Context, query string) ([]ContextItem, error)

func (*FileContextProvider) Name added in v0.2.0

func (f *FileContextProvider) Name() string

func (*FileContextProvider) TokenBudget added in v0.2.0

func (f *FileContextProvider) TokenBudget() int

type FileDiffReport added in v0.2.0

type FileDiffReport struct {
	Path       string
	Status     string // "added", "modified", "deleted"
	Additions  int
	Deletions  int
	Summary    string
	KeyChanges []string
}

FileDiffReport describes the diff status and summary for a single file.

type FileEvent added in v0.2.0

type FileEvent struct {
	Path string
	Type string // "create", "modify", "delete", "rename"
	Time time.Time
	Size int64
}

FileEvent represents a single file system change event.

func DedupEvents added in v0.2.0

func DedupEvents(events []FileEvent) []FileEvent

DedupEvents removes duplicate events for the same path within a batch, keeping only the latest event for each path.

type FileFix added in v0.2.0

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 added in v0.2.0

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

FileMentionDetector scans LLM response text for file path mentions, validates them against the filesystem, and suggests additions to context.

func NewFileMentionDetector added in v0.2.0

func NewFileMentionDetector(projectRoot string) *FileMentionDetector

NewFileMentionDetector creates a new detector rooted at the given project directory.

func (*FileMentionDetector) BuildSuggestion added in v0.2.0

func (d *FileMentionDetector) BuildSuggestion(newFiles []string) string

BuildSuggestion formats a human-readable suggestion message listing the given files that are mentioned but not yet in context.

func (*FileMentionDetector) DetectMentions added in v0.2.0

func (d *FileMentionDetector) DetectMentions(text string) []string

DetectMentions scans the given text for file paths, validates them on disk (relative to projectRoot), and returns a deduplicated list of valid paths.

func (*FileMentionDetector) FilterNew added in v0.2.0

func (d *FileMentionDetector) FilterNew(paths []string, alreadyInContext map[string]bool) []string

FilterNew removes paths that are already present in the context map.

func (*FileMentionDetector) InjectFileMentionContext added in v0.2.0

func (d *FileMentionDetector) InjectFileMentionContext(text string, messages []client.EyrieMessage) string

InjectFileMentionContext detects file mentions in the given text, filters out files already discussed in the message history, and returns a system context string if new files are found. Returns "" if none.

type FileSnapshot added in v0.2.0

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 FileState added in v0.2.0

type FileState struct {
	Path        string
	Size        int64
	ModTime     time.Time
	Language    string
	IsTest      bool
	IsGenerated bool
	Hash        string
}

FileState represents the tracked state of a single file in the workspace.

type FileSummary added in v0.2.0

type FileSummary struct {
	Path       string
	Action     string // "added", "modified", "deleted"
	Summary    string
	Additions  int
	Deletions  int
	KeyChanges []string
}

FileSummary describes summarized changes for a single file in the diff.

type FileTracker added in v0.2.0

type FileTracker struct {
	ReadFiles     map[string]int // path -> count of reads
	ModifiedFiles map[string]int // path -> count of modifications
}

FileTracker maintains a cumulative record of files read and modified across the session lifetime, persisting through compactions.

func NewFileTracker added in v0.2.0

func NewFileTracker() *FileTracker

NewFileTracker creates a new FileTracker with initialized maps.

func (*FileTracker) ExtractFromMessages added in v0.2.0

func (ft *FileTracker) ExtractFromMessages(messages []client.EyrieMessage)

ExtractFromMessages scans messages for tool calls and extracts file paths. Looks at Read tool calls for reads, Write/Edit for modifications.

func (*FileTracker) FormatForSummary added in v0.2.0

func (ft *FileTracker) FormatForSummary() string

FormatForSummary returns a text block suitable for injection into compaction summaries. Format: <tracked-files> Read: path1.go (3x), path2.go (1x) Modified: path3.go (2x), path4.go (1x) </tracked-files>

func (*FileTracker) Merge added in v0.2.0

func (ft *FileTracker) Merge(other *FileTracker)

Merge combines another FileTracker's data into this one.

func (*FileTracker) ParseFromSummary added in v0.2.0

func (ft *FileTracker) ParseFromSummary(summary string)

ParseFromSummary extracts previously tracked files from a compaction summary containing <tracked-files> blocks, merging with current state.

func (*FileTracker) RecordModified added in v0.2.0

func (ft *FileTracker) RecordModified(path string)

RecordModified notes that a file was modified.

func (*FileTracker) RecordRead added in v0.2.0

func (ft *FileTracker) RecordRead(path string)

RecordRead notes that a file was read.

type FileWatcher added in v0.2.0

type FileWatcher struct {
	RootDir        string
	Patterns       []string
	IgnorePatterns []string
	Debounce       time.Duration
	BatchWindow    time.Duration
	OnChange       func([]FileEvent)
	// contains filtered or unexported fields
}

FileWatcher monitors a directory tree for file changes using polling. It supports glob-based inclusion/exclusion patterns, debouncing of rapid changes, and batching of events within a configurable window.

func NewFileWatcher added in v0.2.0

func NewFileWatcher(rootDir string, config WatcherConfig) *FileWatcher

NewFileWatcher creates a FileWatcher with the given root directory and config. Defaults: Debounce 500ms, BatchWindow 100ms, PollInterval 1s.

func (*FileWatcher) ShouldIgnore added in v0.2.0

func (fw *FileWatcher) ShouldIgnore(path string) bool

ShouldIgnore checks whether a path matches any of the watcher's ignore patterns.

func (*FileWatcher) Start added in v0.2.0

func (fw *FileWatcher) Start(ctx context.Context) error

Start begins the polling-based file watcher. It walks the directory at each PollInterval, detects creates/modifies/deletes, batches events within BatchWindow, and debounces rapid changes (only fires OnChange after Debounce duration of quiet). It blocks until ctx is cancelled or Stop is called.

func (*FileWatcher) Stop added in v0.2.0

func (fw *FileWatcher) Stop()

Stop signals the watcher to stop polling.

type FormField added in v0.2.0

type FormField struct {
	Name       string
	Label      string
	Type       string // "text", "choice", "boolean", "number", "password"
	Required   bool
	Default    string
	Choices    []string
	Validation string // regex pattern
}

FormField defines a single input field in an action-required form.

type FormResponse added in v0.2.0

type FormResponse struct {
	Values      map[string]string
	SubmittedAt time.Time
	TimedOut    bool
}

FormResponse holds the user's submitted values for an action-required form.

type FormatRule added in v0.2.0

type FormatRule struct {
	Name    string
	Pattern *regexp.Regexp
	Fix     func(string) string
	Enabled bool
}

FormatRule defines a single formatting rule that can be applied to responses.

type FormattedResponse added in v0.2.0

type FormattedResponse struct {
	Original   string
	Formatted  string
	Changes    []string
	TokensDiff int
}

FormattedResponse holds the result of formatting a response.

type FunctionDoc added in v0.2.0

type FunctionDoc struct {
	Name        string
	Signature   string
	Description string
	Parameters  []ParamDoc
	Returns     string
	Example     string
	Exported    bool
}

FunctionDoc represents documentation for a function.

type GatePhase added in v0.2.0

type GatePhase int

GatePhase represents a phase in the spec-driven workflow.

const (
	GateSpec      GatePhase = iota // specification created
	GatePlan                       // plan covers all criteria
	GateImplement                  // code compiles, basic checks pass
	GateVerify                     // all acceptance criteria met
	GateDone                       // ready to commit
)

func (GatePhase) String added in v0.2.0

func (p GatePhase) String() string

type GateResult added in v0.2.0

type GateResult struct {
	Phase  GatePhase
	Passed bool
	Reason string
}

GateResult is the outcome of a quality gate check.

func RunQualityGates added in v0.2.0

func RunQualityGates(gates []QualityGate) ([]GateResult, bool)

QualityGates runs all gates in sequence. Stops at first failure.

type GenCheck added in v0.2.0

type GenCheck struct {
	Name     string
	Language string // empty means all languages
	CheckFn  func(code, language string) []GenIssue
	Severity string // "error", "warning", "info"
}

GenCheck defines a single validation check that can be applied to generated code.

type GenIssue added in v0.2.0

type GenIssue struct {
	Check       string
	Message     string
	Line        int
	Severity    string
	AutoFixable bool
	Fix         string
}

GenIssue represents a single problem found in generated code.

func CheckBalancedDelimiters added in v0.2.0

func CheckBalancedDelimiters(code string) []GenIssue

CheckBalancedDelimiters counts {}, [], (), and <> (for generics) and reports mismatches.

func CheckCompleteness added in v0.2.0

func CheckCompleteness(code string) []GenIssue

CheckCompleteness finds leftover placeholder markers like TODO, FIXME, ..., pass, NotImplementedError.

func ValidateGo added in v0.2.0

func ValidateGo(code string) []GenIssue

ValidateGo uses go/parser to check Go code for syntax errors and common generation issues.

func ValidatePython added in v0.2.0

func ValidatePython(code string) []GenIssue

ValidatePython checks Python code for indentation consistency and syntax patterns.

func ValidateTypeScript added in v0.2.0

func ValidateTypeScript(code string) []GenIssue

ValidateTypeScript checks TypeScript code for balanced braces and import/export patterns.

type GenValidation added in v0.2.0

type GenValidation struct {
	Valid    bool
	Issues   []GenIssue
	Language string
	Score    float64
}

GenValidation holds the complete result of validating generated code.

type GenValidator added in v0.2.0

type GenValidator struct {
	Checks []GenCheck
	// contains filtered or unexported fields
}

GenValidator checks generated code for correctness before writing to disk.

func NewGenValidator added in v0.2.0

func NewGenValidator() *GenValidator

NewGenValidator creates a GenValidator with built-in checks for common generation errors.

func (*GenValidator) Validate added in v0.2.0

func (gv *GenValidator) Validate(code, language string) *GenValidation

Validate runs all applicable checks on the given code and returns structured results.

type GitContext added in v0.2.0

type GitContext struct {
	RepoDir string
	// contains filtered or unexported fields
}

GitContext provides git-aware context enrichment for files and sessions.

func NewGitContext added in v0.2.0

func NewGitContext(repoDir string) *GitContext

NewGitContext creates a new GitContext for the given repo directory.

func (*GitContext) BuildContextForFile added in v0.2.0

func (gc *GitContext) BuildContextForFile(path string) string

BuildContextForFile gathers all git context for a file and formats it as a readable string.

func (*GitContext) BuildContextForSession added in v0.2.0

func (gc *GitContext) BuildContextForSession() string

BuildContextForSession returns overall repository context.

func (*GitContext) GetBlame added in v0.2.0

func (gc *GitContext) GetBlame(path string, startLine, endLine int) ([]BlameLine, error)

GetBlame returns blame info for lines startLine to endLine of the given file.

func (*GitContext) GetBranch added in v0.2.0

func (gc *GitContext) GetBranch() (string, error)

GetBranch returns the current branch name.

func (*GitContext) GetDiffSummary added in v0.2.0

func (gc *GitContext) GetDiffSummary() (string, error)

GetDiffSummary summarizes current uncommitted changes.

func (*GitContext) GetFileInfo added in v0.2.0

func (gc *GitContext) GetFileInfo(path string) (*GitFileInfo, error)

GetFileInfo returns git metadata for a file, using cache if available.

func (*GitContext) GetRecentChanges added in v0.2.0

func (gc *GitContext) GetRecentChanges(days int) ([]CommitInfo, error)

GetRecentChanges returns commits from the last N days.

func (*GitContext) GetRelatedFiles added in v0.2.0

func (gc *GitContext) GetRelatedFiles(path string) ([]string, error)

GetRelatedFiles finds files frequently modified together with the given file.

func (*GitContext) GetUncommitted added in v0.2.0

func (gc *GitContext) GetUncommitted() ([]string, error)

GetUncommitted returns a list of modified or staged files.

func (*GitContext) IsRecentlyModified added in v0.2.0

func (gc *GitContext) IsRecentlyModified(path string, within time.Duration) bool

IsRecentlyModified checks if the file was modified within the given duration.

type GitContextProvider added in v0.2.0

type GitContextProvider struct {
	RepoDir    string
	MaxCommits int
}

GitContextProvider provides recent git history as context.

func (*GitContextProvider) Description added in v0.2.0

func (g *GitContextProvider) Description() string

func (*GitContextProvider) Gather added in v0.2.0

func (g *GitContextProvider) Gather(ctx context.Context, query string) ([]ContextItem, error)

func (*GitContextProvider) Name added in v0.2.0

func (g *GitContextProvider) Name() string

func (*GitContextProvider) TokenBudget added in v0.2.0

func (g *GitContextProvider) TokenBudget() int

type GitFileInfo added in v0.2.0

type GitFileInfo struct {
	Path          string
	LastAuthor    string
	LastCommitMsg string
	LastModified  time.Time
	CommitCount   int
	Contributors  []string
	RecentCommits []CommitInfo
	Blame         []BlameLine
}

GitFileInfo holds git metadata about a specific file.

type GitIssue added in v0.2.0

type GitIssue struct {
	Number    int
	Title     string
	Body      string
	Labels    []string
	State     string
	Author    string
	CreatedAt time.Time
	URL       string
}

GitIssue represents a git provider issue.

type GitProvider added in v0.2.0

type GitProvider struct {
	Type    string // "github", "gitlab", "bitbucket"
	Token   string
	Owner   string
	Repo    string
	BaseURL string
	// contains filtered or unexported fields
}

GitProvider integrates with GitHub/GitLab/Bitbucket APIs for issue management, PR creation, and CI status checking via CLI tools.

func NewGitProvider added in v0.2.0

func NewGitProvider(providerType, token, owner, repo string) *GitProvider

NewGitProvider creates a new GitProvider with the given configuration.

func (*GitProvider) CreateIssue added in v0.2.0

func (gp *GitProvider) CreateIssue(title, body string, labels []string) (*GitIssue, error)

CreateIssue creates a new issue with the given title, body, and labels.

func (*GitProvider) CreatePR added in v0.2.0

func (gp *GitProvider) CreatePR(title, body, branch, baseBranch string) (*PullRequest, error)

CreatePR creates a new pull request.

func (*GitProvider) GetCIStatus added in v0.2.0

func (gp *GitProvider) GetCIStatus(branch string) (*CIStatus, error)

GetCIStatus returns the CI status for the given branch.

func (*GitProvider) GetIssue added in v0.2.0

func (gp *GitProvider) GetIssue(number int) (*GitIssue, error)

GetIssue returns a single issue by number.

func (*GitProvider) GetReviewComments added in v0.2.0

func (gp *GitProvider) GetReviewComments(prNumber int) ([]string, error)

GetReviewComments returns review comments for a PR.

func (*GitProvider) ListIssues added in v0.2.0

func (gp *GitProvider) ListIssues(state string, limit int) ([]GitIssue, error)

ListIssues returns issues matching the given state and limit.

func (*GitProvider) ListPRs added in v0.2.0

func (gp *GitProvider) ListPRs(state string, limit int) ([]PullRequest, error)

ListPRs returns pull requests matching the given state and limit.

type Goal added in v0.2.0

type Goal struct {
	ID           string
	Description  string
	Status       GoalStatus
	SubGoals     []Goal
	TokenBudget  int
	TokensUsed   int
	CreatedAt    time.Time
	CompletedAt  *time.Time
	Priority     int // 1=highest, 5=lowest
	Dependencies []string
	Tags         []string
	Progress     float64 // 0.0 - 1.0
	ParentID     string  // empty if top-level
}

Goal represents a tracked objective within a session.

type GoalEvent added in v0.2.0

type GoalEvent struct {
	GoalID    string
	EventType string // "created", "started", "completed", "failed", "blocked", "progress"
	Message   string
	Timestamp time.Time
}

GoalEvent records a state change in the goal lifecycle.

type GoalOption added in v0.2.0

type GoalOption func(*Goal)

GoalOption is a functional option for configuring a new goal.

func WithBudget added in v0.2.0

func WithBudget(tokens int) GoalOption

WithBudget sets the maximum token budget for the goal.

func WithDependencies added in v0.2.0

func WithDependencies(deps ...string) GoalOption

WithDependencies sets the IDs of goals that must complete before this one.

func WithPriority added in v0.2.0

func WithPriority(p int) GoalOption

WithPriority sets the goal's priority (1=highest, 5=lowest).

func WithTags added in v0.2.0

func WithTags(tags ...string) GoalOption

WithTags assigns tags to the goal for filtering/categorization.

type GoalStatus added in v0.2.0

type GoalStatus string

GoalStatus represents the current state of a goal.

const (
	GoalPending    GoalStatus = "pending"
	GoalInProgress GoalStatus = "in_progress"
	GoalCompleted  GoalStatus = "completed"
	GoalBlocked    GoalStatus = "blocked"
	GoalFailed     GoalStatus = "failed"
)

type GoalTracker added in v0.2.0

type GoalTracker struct {
	Goals      map[string]*Goal
	ActiveGoal *Goal

	History []GoalEvent
	// contains filtered or unexported fields
}

GoalTracker manages the lifecycle and scheduling of goals.

func NewGoalTracker added in v0.2.0

func NewGoalTracker() *GoalTracker

NewGoalTracker creates and returns an initialized GoalTracker.

func (*GoalTracker) AddGoal added in v0.2.0

func (gt *GoalTracker) AddGoal(description string, opts ...GoalOption) *Goal

AddGoal creates a new goal with an auto-generated ID and applies options.

func (*GoalTracker) BuildGoalContext added in v0.2.0

func (gt *GoalTracker) BuildGoalContext() string

BuildGoalContext formats the current goal state for injection into the system prompt.

func (*GoalTracker) CompleteGoal added in v0.2.0

func (gt *GoalTracker) CompleteGoal(id string) error

CompleteGoal marks a goal as completed and records the completion time. If the goal is a sub-goal, it checks whether the parent can advance.

func (*GoalTracker) ContinuationPrompt added in v0.2.0

func (gt *GoalTracker) ContinuationPrompt() string

ContinuationPrompt generates a prompt when goals remain incomplete.

func (*GoalTracker) DecomposeGoal added in v0.2.0

func (gt *GoalTracker) DecomposeGoal(id string, subDescriptions []string) error

DecomposeGoal splits a goal into sub-goals. The parent goal completes automatically when all sub-goals are completed.

func (*GoalTracker) FailGoal added in v0.2.0

func (gt *GoalTracker) FailGoal(id string, reason string) error

FailGoal marks a goal as failed with a reason.

func (*GoalTracker) GetNextGoal added in v0.2.0

func (gt *GoalTracker) GetNextGoal() *Goal

GetNextGoal returns the highest-priority unblocked goal. It prefers goals already in_progress, then pending goals ordered by priority.

func (*GoalTracker) IsBudgetExceeded added in v0.2.0

func (gt *GoalTracker) IsBudgetExceeded(id string) bool

IsBudgetExceeded returns true if the goal has exceeded its token budget.

func (*GoalTracker) RecordTokens added in v0.2.0

func (gt *GoalTracker) RecordTokens(id string, tokens int)

RecordTokens adds token usage to a goal's running total.

func (*GoalTracker) StartGoal added in v0.2.0

func (gt *GoalTracker) StartGoal(id string) error

StartGoal transitions a goal to in_progress and sets it as the active goal.

func (*GoalTracker) UpdateProgress added in v0.2.0

func (gt *GoalTracker) UpdateProgress(id string, progress float64)

UpdateProgress sets the progress for a goal (clamped to 0.0-1.0).

type GroundingResult added in v0.2.0

type GroundingResult struct {
	Score             float64
	SupportedClaims   []string
	UnsupportedClaims []string
	TotalClaims       int
	Grounded          bool
}

GroundingResult holds the outcome of checking a response against context.

type HallucinationGuard added in v0.2.0

type HallucinationGuard struct {
	Enabled    bool
	Threshold  float64 // fraction of claims that must be grounded (e.g. 0.7 = 70%)
	MaxRetries int
	// contains filtered or unexported fields
}

HallucinationGuard validates agent outputs against source context, rejecting responses that contain unsupported factual claims.

func NewHallucinationGuard added in v0.2.0

func NewHallucinationGuard() *HallucinationGuard

NewHallucinationGuard creates a HallucinationGuard with sensible defaults.

func (*HallucinationGuard) Check added in v0.2.0

func (hg *HallucinationGuard) Check(response string, context []string) *GroundingResult

Check validates a response against the provided context sources. It extracts factual claims, verifies each against context, and returns a grounding result indicating whether the response is sufficiently supported.

func (*HallucinationGuard) ExtractClaims added in v0.2.0

func (hg *HallucinationGuard) ExtractClaims(text string) []string

ExtractClaims splits text into sentences and filters to those that contain specific factual assertions (names, numbers, paths, technical terms). Opinions, questions, and hedged statements are excluded.

func (*HallucinationGuard) ExtractKeyTerms added in v0.2.0

func (hg *HallucinationGuard) ExtractKeyTerms(claim string) []string

ExtractKeyTerms removes stop words and returns nouns, numbers, paths, and identifiers from the claim text.

func (*HallucinationGuard) VerifyClaim added in v0.2.0

func (hg *HallucinationGuard) VerifyClaim(claim string, context []string) bool

VerifyClaim checks whether a claim's key terms appear sufficiently in the provided context. A word overlap threshold of > 0.5 is required.

type HeadTailWindow added in v0.2.0

type HeadTailWindow struct {
	HeadSize       int
	TailSize       int
	MaxTokens      int
	IncludeSummary bool
	// contains filtered or unexported fields
}

HeadTailWindow implements a context window strategy that keeps the first N and last M messages, dropping the middle. Inspired by autogen's HeadAndTailChatCompletionContext.

func NewHeadTailWindow added in v0.2.0

func NewHeadTailWindow(headSize, tailSize, maxTokens int) *HeadTailWindow

NewHeadTailWindow creates a new HeadTailWindow with the given sizes. If headSize <= 0, defaults to 4. If tailSize <= 0, defaults to 12. maxTokens sets the token budget; if <= 0, no token limit is enforced.

func (*HeadTailWindow) Apply added in v0.2.0

func (w *HeadTailWindow) Apply(messages []WindowMessage) *WindowResult

Apply keeps the first HeadSize messages and last TailSize messages, dropping the middle. If IncludeSummary is true, a brief summary of dropped messages is generated. The result is verified to fit within MaxTokens.

type HealAttempt added in v0.2.0

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 added in v0.2.0

type HealResult struct {
	Attempts      []HealAttempt
	FinalSuccess  bool
	TotalDuration time.Duration
	FixesApplied  int
}

HealResult summarizes the outcome of a complete healing session.

type HintsLoader added in v0.2.0

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 NewHintsLoader added in v0.2.0

func NewHintsLoader() *HintsLoader

NewHintsLoader creates a hints loader.

func (*HintsLoader) IsLoaded added in v0.2.0

func (h *HintsLoader) IsLoaded(dir string) bool

IsLoaded reports whether a directory has already been scanned.

func (*HintsLoader) LoadHints added in v0.2.0

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 added in v0.2.0

func (h *HintsLoader) LoadHintsRecursive(dir string) string

LoadHintsRecursive loads hints from dir and all parent dirs up to root.

func (*HintsLoader) Reset added in v0.2.0

func (h *HintsLoader) Reset()

Reset clears the loaded state (e.g., on /new session).

type Hypothesis added in v0.2.0

type Hypothesis struct {
	Description string `json:"description"`
	Tested      bool   `json:"tested"`
	Confirmed   bool   `json:"confirmed"`
	Evidence    string `json:"evidence,omitempty"`
}

Hypothesis represents a debugging hypothesis that can be tested and confirmed or rejected.

type ImpactAnalysis added in v0.2.0

type ImpactAnalysis struct {
	ChangedFiles         []string
	DirectlyAffected     []string
	TransitivelyAffected []string
	RiskScore            float64
	TestCoverage         float64
	Suggestions          []string
}

ImpactAnalysis holds the results of analyzing the blast radius of code changes.

type ImpactAnalyzer added in v0.2.0

type ImpactAnalyzer struct {
	ProjectDir  string
	ImportGraph map[string][]string // reverse dependency: pkg -> list of packages that import it
	TestMapping map[string][]string // pkg -> list of test files for that pkg
	// contains filtered or unexported fields
}

ImpactAnalyzer predicts the blast radius of code changes before they're applied.

func NewImpactAnalyzer added in v0.2.0

func NewImpactAnalyzer(projectDir string) *ImpactAnalyzer

NewImpactAnalyzer creates a new ImpactAnalyzer for the given project directory.

func (*ImpactAnalyzer) Analyze added in v0.2.0

func (ia *ImpactAnalyzer) Analyze(changedFiles []string) (*ImpactAnalysis, error)

Analyze performs a full impact analysis for the given changed files.

func (*ImpactAnalyzer) FindDirectDependents added in v0.2.0

func (ia *ImpactAnalyzer) FindDirectDependents(pkg string) []string

FindDirectDependents returns packages that directly import the given package.

func (*ImpactAnalyzer) FindTestCoverage added in v0.2.0

func (ia *ImpactAnalyzer) FindTestCoverage(packages []string) float64

FindTestCoverage checks which affected packages have test files and returns the percentage of packages with at least one test file.

func (*ImpactAnalyzer) FindTransitiveDependents added in v0.2.0

func (ia *ImpactAnalyzer) FindTransitiveDependents(pkg string, depth int) []string

FindTransitiveDependents performs BFS up to depth levels of reverse dependencies.

func (*ImpactAnalyzer) GenerateSuggestions added in v0.2.0

func (ia *ImpactAnalyzer) GenerateSuggestions(analysis *ImpactAnalysis) []string

GenerateSuggestions produces actionable suggestions based on the analysis.

func (*ImpactAnalyzer) QuickImpact added in v0.2.0

func (ia *ImpactAnalyzer) QuickImpact(file string) string

QuickImpact provides a fast single-file impact summary (one line).

func (*ImpactAnalyzer) ScoreRisk added in v0.2.0

func (ia *ImpactAnalyzer) ScoreRisk(analysis *ImpactAnalysis) float64

ScoreRisk calculates a risk score from 0.0 to 1.0 based on various factors.

type ImplicitSignal added in v0.2.0

type ImplicitSignal struct {
	Type      string    `json:"type"`
	SessionID string    `json:"session_id"`
	ToolName  string    `json:"tool_name"`
	Timestamp time.Time `json:"timestamp"`
}

ImplicitSignal represents an inferred satisfaction signal from user behavior.

type InjectionScanner added in v0.2.0

type InjectionScanner struct {
	Patterns []injectionPattern
	// contains filtered or unexported fields
}

InjectionScanner detects potential prompt-injection attempts in user input.

func NewInjectionScanner added in v0.2.0

func NewInjectionScanner() *InjectionScanner

NewInjectionScanner creates an InjectionScanner with built-in detection patterns.

func (*InjectionScanner) Scan added in v0.2.0

func (is *InjectionScanner) Scan(input string) *ScanResult

Scan checks the input for injection patterns and returns a risk assessment.

type Insight added in v0.2.0

type Insight struct {
	ID           string    `json:"id"`
	Content      string    `json:"content"`
	Category     string    `json:"category"` // "approach", "tool_usage", "avoidance", "preference"
	Language     string    `json:"language"`
	Confidence   float64   `json:"confidence"`
	SuccessCount int       `json:"success_count"`
	CreatedAt    time.Time `json:"created_at"`
	LastUsed     time.Time `json:"last_used"`
}

Insight represents a learned insight from a previous session.

type InspectionAction added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

func (r InspectionResult) ShouldExecute() bool

ShouldExecute returns true if the tool can proceed without user input.

type IntegrationPipeline added in v0.2.0

type IntegrationPipeline struct {
	// Pre-query pipeline
	IntentClassifier *IntentClassifier
	ToolSelector     *ToolSelector
	ContextDecay     *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 added in v0.2.0

func NewIntegrationPipeline() *IntegrationPipeline

NewIntegrationPipeline initializes all subsystems and returns a ready-to-use pipeline orchestrator.

func (*IntegrationPipeline) EndSession added in v0.2.0

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 added in v0.2.0

func (p *IntegrationPipeline) FormatPipelineStatus() string

FormatPipelineStatus returns a human-readable view of which subsystems are active or inactive in the pipeline.

func (*IntegrationPipeline) PostResponse added in v0.2.0

func (p *IntegrationPipeline) PostResponse(response string, messages []client.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 added in v0.2.0

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 added in v0.2.0

func (p *IntegrationPipeline) PreQuery(messages []client.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 added in v0.2.0

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 added in v0.2.0

type Intent struct {
	Category            string
	Confidence          float64
	SubCategory         string
	Keywords            []string
	SuggestedTools      []string
	EstimatedComplexity string
}

Intent represents a classified user intent with confidence and metadata.

type IntentClassifier added in v0.2.0

type IntentClassifier struct {
	Rules   []IntentRule
	History []ClassifiedInput
	// contains filtered or unexported fields
}

IntentClassifier categorizes user messages to route them to appropriate handling strategies before involving the LLM.

func NewIntentClassifier added in v0.2.0

func NewIntentClassifier() *IntentClassifier

NewIntentClassifier creates an IntentClassifier with default keyword rules for each intent category.

func (*IntentClassifier) Classify added in v0.2.0

func (ic *IntentClassifier) Classify(input string) *Intent

Classify analyzes the input string and returns the best matching Intent.

func (*IntentClassifier) ClassifyForRouting added in v0.2.0

func (ic *IntentClassifier) ClassifyForRouting(input string) (model, tools string)

ClassifyForRouting performs quick classification returning recommended model tier and tool set string.

func (*IntentClassifier) EstimateComplexity added in v0.2.0

func (ic *IntentClassifier) EstimateComplexity(input string) string

EstimateComplexity estimates how complex a request is based on word count, keyword density, and file mentions.

func (*IntentClassifier) GetPatterns added in v0.2.0

func (ic *IntentClassifier) GetPatterns() map[string]int

GetPatterns returns a map of intent categories to their occurrence count from classification history.

func (*IntentClassifier) RecordClassification added in v0.2.0

func (ic *IntentClassifier) RecordClassification(input string, intent *Intent)

RecordClassification stores a classification result in history for pattern analysis.

func (*IntentClassifier) SuggestTools added in v0.2.0

func (ic *IntentClassifier) SuggestTools(intent *Intent) []string

SuggestTools returns the recommended tool set for the given intent category.

type IntentRule added in v0.2.0

type IntentRule struct {
	Category    string
	SubCategory string
	Patterns    []string
	Weight      float64
	Tools       []string
}

IntentRule defines a pattern-matching rule for intent classification.

type InvestigatePhase added in v0.2.0

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 added in v0.2.0

func (p InvestigatePhase) String() string

type Issue added in v0.2.0

type Issue struct {
	ID         string     `json:"id"`
	Title      string     `json:"title"`
	Body       string     `json:"body"`
	Labels     []string   `json:"labels"`
	State      string     `json:"state"`      // "open", "closed"
	Resolution string     `json:"resolution"` // how the issue was resolved
	CreatedAt  time.Time  `json:"created_at"`
	ClosedAt   *time.Time `json:"closed_at"`
	Tokens     []string   `json:"tokens"` // tokenized title+body for search
}

Issue represents a project issue (bug, feature request, etc.) for similarity search.

type IssueIndex added in v0.2.0

type IssueIndex struct {
	Issues        []*Issue         `json:"issues"`
	InvertedIndex map[string][]int `json:"inverted_index"`
	// contains filtered or unexported fields
}

IssueIndex provides BM25-based similarity search over a collection of issues.

func NewIssueIndex added in v0.2.0

func NewIssueIndex() *IssueIndex

NewIssueIndex creates a new empty IssueIndex ready for use.

func (*IssueIndex) AddIssue added in v0.2.0

func (idx *IssueIndex) AddIssue(issue *Issue)

AddIssue adds an issue to the index, tokenizing its title and body for search.

func (*IssueIndex) FindSimilar added in v0.2.0

func (idx *IssueIndex) FindSimilar(query string, limit int) []*SimilarIssue

FindSimilar searches for issues similar to the given query using BM25 scoring. It returns up to limit results sorted by relevance score.

func (*IssueIndex) ImportFromCommits added in v0.2.0

func (idx *IssueIndex) ImportFromCommits(projectDir string) error

ImportFromCommits extracts issue resolution info from git commit history. It parses "fixes #N" style references and maps them to commit messages.

func (*IssueIndex) ImportFromGitHub added in v0.2.0

func (idx *IssueIndex) ImportFromGitHub(projectDir string) error

ImportFromGitHub imports issues from GitHub using the gh CLI tool. It requires the gh CLI to be installed and authenticated.

type KnowledgeBase added in v0.2.0

type KnowledgeBase struct {
	Entries    map[string]*KnowledgeEntry `json:"entries"`
	Categories map[string][]string        `json:"categories"`
	Dir        string                     `json:"-"`
	// contains filtered or unexported fields
}

KnowledgeBase stores distilled patterns extracted from successful sessions.

func NewKnowledgeBase added in v0.2.0

func NewKnowledgeBase(dir string) *KnowledgeBase

NewKnowledgeBase creates a new KnowledgeBase that persists to the given directory.

func (*KnowledgeBase) Add added in v0.2.0

func (kb *KnowledgeBase) Add(entry *KnowledgeEntry) error

Add inserts a new knowledge entry into the base.

func (*KnowledgeBase) BuildContextForTask added in v0.2.0

func (kb *KnowledgeBase) BuildContextForTask(task string, maxTokens int) string

BuildContextForTask formats relevant knowledge for prompt injection, respecting a token budget.

func (*KnowledgeBase) ExtractFromSession added in v0.2.0

func (kb *KnowledgeBase) ExtractFromSession(messages []string, outcome string) []*KnowledgeEntry

ExtractFromSession uses heuristics to extract knowledge entries from a session's messages and outcome.

func (*KnowledgeBase) FormatEntry added in v0.2.0

func (kb *KnowledgeBase) FormatEntry(entry *KnowledgeEntry) string

FormatEntry formats a knowledge entry for display or prompt injection.

func (*KnowledgeBase) GetByCategory added in v0.2.0

func (kb *KnowledgeBase) GetByCategory(category string) []*KnowledgeEntry

GetByCategory returns all entries in the given category.

func (*KnowledgeBase) Load added in v0.2.0

func (kb *KnowledgeBase) Load() error

Load reads the knowledge base from disk.

func (*KnowledgeBase) Merge added in v0.2.0

func (kb *KnowledgeBase) Merge(other *KnowledgeBase)

Merge combines another KnowledgeBase into this one, deduplicating by content similarity.

func (*KnowledgeBase) Prune added in v0.2.0

func (kb *KnowledgeBase) Prune(minConfidence float64, maxAge time.Duration)

Prune removes entries below minimum confidence or older than maxAge.

func (*KnowledgeBase) Save added in v0.2.0

func (kb *KnowledgeBase) Save() error

Save persists the knowledge base to JSON files in the configured directory.

func (*KnowledgeBase) Search added in v0.2.0

func (kb *KnowledgeBase) Search(query string, limit int) []*KnowledgeEntry

Search performs keyword search ranked by relevance, usage, and recency.

func (*KnowledgeBase) Stats added in v0.2.0

func (kb *KnowledgeBase) Stats() KnowledgeStats

Stats returns aggregate statistics about the knowledge base.

type KnowledgeEntry added in v0.2.0

type KnowledgeEntry struct {
	ID         string    `json:"id"`
	Title      string    `json:"title"`
	Content    string    `json:"content"`
	Category   string    `json:"category"` // "pattern", "anti-pattern", "convention", "shortcut", "gotcha"
	Language   string    `json:"language"`
	Tags       []string  `json:"tags"`
	Examples   []string  `json:"examples"`
	Confidence float64   `json:"confidence"`
	UsageCount int       `json:"usage_count"`
	LastUsed   time.Time `json:"last_used"`
	CreatedAt  time.Time `json:"created_at"`
	Source     string    `json:"source"`
}

KnowledgeEntry represents a single piece of distilled knowledge.

type KnowledgeStats added in v0.2.0

type KnowledgeStats struct {
	TotalEntries  int            `json:"total_entries"`
	ByCategory    map[string]int `json:"by_category"`
	ByLanguage    map[string]int `json:"by_language"`
	AvgConfidence float64        `json:"avg_confidence"`
	MostUsed      []string       `json:"most_used"`
}

KnowledgeStats holds aggregate statistics about the knowledge base.

type LLMClient

type LLMClient interface {
	Chat(ctx context.Context, msgs []client.EyrieMessage, opts client.ChatOptions) (*client.EyrieResponse, error)
}

LLMClient is the minimal interface for calling an LLM from engine components.

type LanguageConfig added in v0.2.0

type LanguageConfig struct {
	Name            string
	Extensions      []string
	TestCommand     string
	LintCommand     string
	FormatCommand   string
	BuildCommand    string
	PackageManager  string
	PackageFile     string
	ImportPattern   *regexp.Regexp
	FunctionPattern *regexp.Regexp
	CommentStyle    string // "//", "#", "--"
}

LanguageConfig describes a programming language's tooling and conventions.

type LanguageRegistry added in v0.2.0

type LanguageRegistry struct {
	Languages map[string]*LanguageConfig
	// contains filtered or unexported fields
}

LanguageRegistry manages a collection of language configurations.

func NewLanguageRegistry added in v0.2.0

func NewLanguageRegistry() *LanguageRegistry

NewLanguageRegistry creates a registry pre-populated with common languages.

func (*LanguageRegistry) Detect added in v0.2.0

func (r *LanguageRegistry) Detect(projectDir string) *LanguageConfig

Detect returns the primary language for a project directory by counting source files and checking for package manifest files.

func (*LanguageRegistry) DetectAll added in v0.2.0

func (r *LanguageRegistry) DetectAll(projectDir string) []*LanguageConfig

DetectAll returns all languages detected in a project, sorted by file count (most prevalent first). It walks the directory tree and matches extensions.

func (*LanguageRegistry) FormatCommand added in v0.2.0

func (r *LanguageRegistry) FormatCommand(projectDir string) string

FormatCommand returns the format command for the primary detected language.

func (*LanguageRegistry) GetByExtension added in v0.2.0

func (r *LanguageRegistry) GetByExtension(ext string) *LanguageConfig

GetByExtension finds a language by file extension (including the dot).

func (*LanguageRegistry) GetByName added in v0.2.0

func (r *LanguageRegistry) GetByName(name string) *LanguageConfig

GetByName looks up a language by its name (case-insensitive).

func (*LanguageRegistry) LintCommand added in v0.2.0

func (r *LanguageRegistry) LintCommand(projectDir string) string

LintCommand returns the lint command for the primary detected language.

func (*LanguageRegistry) Register added in v0.2.0

func (r *LanguageRegistry) Register(config *LanguageConfig)

Register adds or replaces a language configuration in the registry.

func (*LanguageRegistry) TestCommand added in v0.2.0

func (r *LanguageRegistry) TestCommand(projectDir string) string

TestCommand returns the test command for the primary detected language.

type LargeResponseHandler added in v0.2.0

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 added in v0.2.0

func NewLargeResponseHandler() *LargeResponseHandler

NewLargeResponseHandler creates a handler with defaults tuned for coding.

func (*LargeResponseHandler) Process added in v0.2.0

func (h *LargeResponseHandler) Process(content string) *ChunkedResponse

Process splits a large response into chunks. Returns the first chunk with metadata.

type LearnedPattern added in v0.2.0

type LearnedPattern struct {
	ID           string    `json:"id"`
	Category     string    `json:"category"`     // "build", "test", "lint", "runtime"
	Language     string    `json:"language"`     // "go", "python", "js", "ts", "rust", "generic"
	Pattern      string    `json:"pattern"`      // regex that matches this error
	Example      string    `json:"example"`      // actual error message example
	Fix          string    `json:"fix"`          // description of how to fix
	FixTemplate  string    `json:"fix_template"` // template for automated fix
	Confidence   float64   `json:"confidence"`   // how reliable this fix is (0-1)
	SuccessCount int       `json:"success_count"`
	FailureCount int       `json:"failure_count"`
	LastSeen     time.Time `json:"last_seen"`
}

LearnedPattern represents a learned error pattern with its fix information.

type LearnerStats added in v0.2.0

type LearnerStats struct {
	InsightCount    int     `json:"insight_count"`
	ConventionCount int     `json:"convention_count"`
	FailureCount    int     `json:"failure_count"`
	AvgConfidence   float64 `json:"avg_confidence"`
}

LearnerStats holds aggregate statistics about the cross-session learner.

type LensGenerator added in v0.2.0

type LensGenerator func(file, content string) []CodeLens

LensGenerator is a function that produces code lenses for a given file and its content.

type LimitTracker

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

LimitTracker tracks usage against limits.

func NewLimitTracker

func NewLimitTracker(limits SafetyLimits) *LimitTracker

NewLimitTracker creates a LimitTracker with the given limits.

func (*LimitTracker) IsExceeded

func (lt *LimitTracker) IsExceeded() (bool, string)

IsExceeded returns true and a human-readable reason when any limit is breached.

func (*LimitTracker) RecordCost

func (lt *LimitTracker) RecordCost(usd float64)

RecordCost adds to the running cost total.

func (*LimitTracker) RecordTokens

func (lt *LimitTracker) RecordTokens(n int)

RecordTokens adds output tokens to the running total.

func (*LimitTracker) RecordToolCall

func (lt *LimitTracker) RecordToolCall(toolName string)

RecordToolCall records a tool invocation. Tools named "Bash" or "bash" also increment the bash command counter; "Write" or "Edit" increment file writes.

func (*LimitTracker) RecordTurn

func (lt *LimitTracker) RecordTurn()

RecordTurn increments the turn counter.

func (*LimitTracker) Summary

func (lt *LimitTracker) Summary() string

Summary returns a one-line summary of usage vs limits.

type LintLoop added in v0.2.0

type LintLoop struct {
	// MaxReflections is the maximum number of lint-fix retries per file per session.
	// Default is 3.
	MaxReflections int

	// LintCommands maps file extensions to lint commands. The placeholder {file}
	// in the command string is replaced with the actual file path.
	LintCommands map[string]string

	// Enabled controls whether the lint loop is active.
	Enabled bool
	// contains filtered or unexported fields
}

LintLoop implements the "reflected_message" pattern from Aider: when an edit tool produces a lint/syntax error, the error is automatically fed back as context for the next iteration so the agent can self-correct.

func NewLintLoop added in v0.2.0

func NewLintLoop() *LintLoop

NewLintLoop creates a LintLoop with sensible defaults.

func (*LintLoop) BuildReflectedMessage added in v0.2.0

func (ll *LintLoop) BuildReflectedMessage(result *LintResult) string

BuildReflectedMessage formats a LintResult into a message the agent can understand and act upon in the next iteration.

func (*LintLoop) RecordReflection added in v0.2.0

func (ll *LintLoop) RecordReflection(path string) int

RecordReflection increments the reflection counter for a file and returns the new count. Thread-safe.

func (*LintLoop) ReflectionCount added in v0.2.0

func (ll *LintLoop) ReflectionCount(path string) int

ReflectionCount returns the current reflection count for a file. Thread-safe.

func (*LintLoop) Reset added in v0.2.0

func (ll *LintLoop) Reset()

Reset clears all reflection counts.

func (*LintLoop) ResetFile added in v0.2.0

func (ll *LintLoop) ResetFile(path string)

ResetFile clears the reflection count for a specific file.

func (*LintLoop) RunLint added in v0.2.0

func (ll *LintLoop) RunLint(path string) (*LintResult, error)

RunLint executes the appropriate lint command for the given file path. It returns nil if no lint command is configured for the file type, or if the lint passes cleanly. Returns a LintResult with errors if lint fails.

func (*LintLoop) ShouldRetry added in v0.2.0

func (ll *LintLoop) ShouldRetry(reflectionCount int) bool

ShouldRetry returns true if the number of lint reflections for this file has not yet reached MaxReflections.

type LintResult added in v0.2.0

type LintResult struct {
	// File is the path that was linted.
	File string

	// Errors contains the individual error/warning lines from the linter.
	Errors []string

	// ExitCode is the process exit code (0 = pass, non-zero = failure).
	ExitCode int
}

LintResult holds the output of a lint command execution.

type LogEntry added in v0.2.0

type LogEntry struct {
	Level     string                 `json:"level"`
	Message   string                 `json:"message"`
	Timestamp time.Time              `json:"timestamp"`
	SessionID string                 `json:"session_id,omitempty"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
	Caller    string                 `json:"caller,omitempty"`
}

LogEntry represents a single structured log record.

type LogLevel added in v0.2.0

type LogLevel int

LogLevel represents the severity of a log entry.

const (
	LevelDebug LogLevel = 0
	LevelInfo  LogLevel = 1
	LevelWarn  LogLevel = 2
	LevelError LogLevel = 3
	LevelFatal LogLevel = 4
)

func ParseLevel added in v0.2.0

func ParseLevel(s string) LogLevel

ParseLevel converts a string to a LogLevel.

type LoopDetector

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

LoopDetector detects repeated identical tool call patterns using SHA-256 signatures. Supports two severity levels: warning (soft) and doom loop (hard escalation).

func NewLoopDetector

func NewLoopDetector(windowSize, maxRepeats int) *LoopDetector

NewLoopDetector creates a detector with a sliding window.

func (*LoopDetector) DoomLoopWarning

func (ld *LoopDetector) DoomLoopWarning() string

DoomLoopWarning returns the hard escalation message (repeated loops).

func (*LoopDetector) Escalated

func (ld *LoopDetector) Escalated() bool

Escalated returns whether the detector has already fired a warning.

func (*LoopDetector) IsDoomLoop

func (ld *LoopDetector) IsDoomLoop() bool

IsDoomLoop returns true when the agent has been stuck for DoomLoopThreshold consecutive escalation attempts — it should hard-stop and ask the user.

func (*LoopDetector) IsLooping

func (ld *LoopDetector) IsLooping() bool

IsLooping returns true if any signature appears more than maxRepeats times in the window.

func (*LoopDetector) LoopWarning

func (ld *LoopDetector) LoopWarning() string

LoopWarning returns the soft warning message (first detection).

func (*LoopDetector) MarkEscalated

func (ld *LoopDetector) MarkEscalated()

MarkEscalated records that a warning was shown.

func (*LoopDetector) RecordStep

func (ld *LoopDetector) RecordStep(toolNames []string, inputs []string, outputs []string)

RecordStep hashes the tool calls and results from a single agent step.

func (*LoopDetector) Reset

func (ld *LoopDetector) Reset()

Reset clears the escalation state (e.g., after user provides new direction).

type MemoryConsolidator added in v0.2.0

type MemoryConsolidator struct {
	RawMemories          []RawMemory          `json:"raw_memories"`
	ConsolidatedMemories []ConsolidatedMemory `json:"consolidated_memories"`
	Dir                  string               `json:"-"`
	LastConsolidation    time.Time            `json:"last_consolidation"`
	// contains filtered or unexported fields
}

MemoryConsolidator processes raw session data into structured long-term memory during idle time, inspired by the "sleeptime" pattern.

func NewMemoryConsolidator added in v0.2.0

func NewMemoryConsolidator(dir string) *MemoryConsolidator

NewMemoryConsolidator creates a new MemoryConsolidator that persists data in dir.

func (*MemoryConsolidator) Consolidate added in v0.2.0

func (mc *MemoryConsolidator) Consolidate() ([]ConsolidatedMemory, error)

Consolidate processes unprocessed raw memories into structured consolidated memories. It extracts facts, conventions, decisions, and warnings, deduplicates them against existing consolidated memories, and marks raw memories as processed.

func (*MemoryConsolidator) Expire added in v0.2.0

func (mc *MemoryConsolidator) Expire()

Expire removes memories that have passed their expiration time.

func (*MemoryConsolidator) ExtractConventions added in v0.2.0

func (mc *MemoryConsolidator) ExtractConventions(raw []RawMemory) []ConsolidatedMemory

ExtractConventions identifies convention statements from raw memories. Patterns: "always", "never", "must", "should"

func (*MemoryConsolidator) ExtractDecisions added in v0.2.0

func (mc *MemoryConsolidator) ExtractDecisions(raw []RawMemory) []ConsolidatedMemory

ExtractDecisions identifies decision statements from raw memories. Patterns: "decided", "chose", "went with", "because"

func (*MemoryConsolidator) ExtractFacts added in v0.2.0

func (mc *MemoryConsolidator) ExtractFacts(raw []RawMemory) []ConsolidatedMemory

ExtractFacts identifies factual statements from raw memories. Patterns: "X is Y", "X uses Y", "X has Y"

func (*MemoryConsolidator) FormatMemories added in v0.2.0

func (mc *MemoryConsolidator) FormatMemories(memories []ConsolidatedMemory) string

FormatMemories formats consolidated memories into a human-readable string.

func (*MemoryConsolidator) Ingest added in v0.2.0

func (mc *MemoryConsolidator) Ingest(content, source, sessionID string)

Ingest adds raw content to the memory queue for later consolidation.

func (*MemoryConsolidator) Load added in v0.2.0

func (mc *MemoryConsolidator) Load() error

Load restores the consolidator state from disk.

func (*MemoryConsolidator) Recall added in v0.2.0

func (mc *MemoryConsolidator) Recall(query string, limit int) []ConsolidatedMemory

Recall searches consolidated memories by keyword relevance and returns up to limit results.

func (*MemoryConsolidator) Save added in v0.2.0

func (mc *MemoryConsolidator) Save() error

Save persists the consolidator state to disk.

func (*MemoryConsolidator) Stats added in v0.2.0

Stats returns aggregate statistics about the consolidator state.

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 struct {
	CompactableTools map[string]bool
	TimeGapMins      float64
	KeepRecent       int
}

MicroCompactConfig controls micro-compaction behavior.

func DefaultMicroCompactConfig

func DefaultMicroCompactConfig() MicroCompactConfig

DefaultMicroCompactConfig returns the default micro-compaction settings.

type MicroCompactStrategy

type MicroCompactStrategy struct{}

MicroCompactStrategy clears old tool result content while preserving message structure.

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 []client.EyrieMessage, tokenCount, threshold int) bool

ShouldTrigger fires when there are enough messages with compactable tool results and sufficient time has passed since the last assistant message (cache is cold).

type MigrationPlan added in v0.2.0

type MigrationPlan struct {
	Name             string
	Description      string
	Steps            []MigrationStep
	AffectedFiles    []string
	EstimatedChanges int
	RiskLevel        string
	Validated        bool
	CreatedAt        time.Time
}

MigrationPlan represents a complete plan for a large-scale code migration.

type MigrationPlanner added in v0.2.0

type MigrationPlanner struct {
	ProjectDir string
	// contains filtered or unexported fields
}

MigrationPlanner plans and executes large-scale code migrations.

func NewMigrationPlanner added in v0.2.0

func NewMigrationPlanner(projectDir string) *MigrationPlanner

NewMigrationPlanner creates a new MigrationPlanner for the given project directory.

func (*MigrationPlanner) Execute added in v0.2.0

func (mp *MigrationPlanner) Execute(plan *MigrationPlan) (*MigrationResult, error)

Execute applies all auto steps in the plan, skipping manual ones.

func (*MigrationPlanner) PlanAPIChange added in v0.2.0

func (mp *MigrationPlanner) PlanAPIChange(oldSig, newSig string) (*MigrationPlan, error)

PlanAPIChange creates a migration plan for changing a function/method signature.

func (*MigrationPlanner) PlanDependencyUpgrade added in v0.2.0

func (mp *MigrationPlanner) PlanDependencyUpgrade(pkg, fromVersion, toVersion string) (*MigrationPlan, error)

PlanDependencyUpgrade creates a migration plan for upgrading a dependency from one version to another.

func (*MigrationPlanner) PlanPatternReplace added in v0.2.0

func (mp *MigrationPlanner) PlanPatternReplace(pattern, replacement, fileGlob string) (*MigrationPlan, error)

PlanPatternReplace creates a migration plan to replace all matches of pattern in files matching fileGlob with the given replacement.

func (*MigrationPlanner) PlanRename added in v0.2.0

func (mp *MigrationPlanner) PlanRename(oldName, newName string) (*MigrationPlan, error)

PlanRename creates a migration plan to rename oldName to newName across the project. It orders definitions first, then usages.

func (*MigrationPlanner) Preview added in v0.2.0

func (mp *MigrationPlanner) Preview(plan *MigrationPlan) string

Preview returns a human-readable preview of the migration plan.

func (*MigrationPlanner) Rollback added in v0.2.0

func (mp *MigrationPlanner) Rollback(plan *MigrationPlan) error

Rollback undoes applied steps in reverse order.

func (*MigrationPlanner) Validate added in v0.2.0

func (mp *MigrationPlanner) Validate(plan *MigrationPlan) []string

Validate checks the plan for potential issues and returns a list of warnings.

type MigrationResult added in v0.2.0

type MigrationResult struct {
	Completed    int
	Skipped      int
	Failed       int
	ManualReview []MigrationStep
}

MigrationResult holds the outcome of executing a migration plan.

type MigrationStep added in v0.2.0

type MigrationStep struct {
	Order       int
	Description string
	Pattern     string // regex to find
	Replacement string
	Files       []string
	Manual      bool // needs human review
	Completed   bool
	Error       string
}

MigrationStep represents a single step within a migration plan.

type ModelPrice added in v0.2.0

type ModelPrice struct {
	InputPerMillion      float64
	OutputPerMillion     float64
	CacheReadPerMillion  float64
	CacheWritePerMillion float64
}

ModelPrice holds the pricing for a model per million tokens.

type ModelTier

type ModelTier int

ModelTier represents the cost tier of a model.

const (
	TierCheap     ModelTier = iota // haiku-class
	TierMid                        // sonnet-class
	TierExpensive                  // opus-class
)

type ModuleInfo added in v0.2.0

type ModuleInfo struct {
	Name         string
	Path         string
	Purpose      string
	PublicAPI    []string
	Dependencies []string
	Size         int
}

ModuleInfo describes a single module/package within the project.

type MultiRepoConfig added in v0.2.0

type MultiRepoConfig struct {
	Repos []RepoRelation `yaml:"repos"`
}

MultiRepoConfig is loaded from .hawk/repos.yaml.

type MultiRepoContext added in v0.2.0

type MultiRepoContext struct {
	Config  MultiRepoConfig
	BaseDir string
}

MultiRepoContext loads and manages cross-repo context.

func LoadMultiRepoConfig added in v0.2.0

func LoadMultiRepoConfig(projectDir string) *MultiRepoContext

LoadMultiRepoConfig reads .hawk/repos.yaml from the project root.

func (*MultiRepoContext) HasRelatedRepos added in v0.2.0

func (mrc *MultiRepoContext) HasRelatedRepos() bool

HasRelatedRepos reports whether any related repos are configured.

func (*MultiRepoContext) LoadBoundaryContext added in v0.2.0

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 added in v0.2.0

type Observability struct {
	Tracer  *trace.Tracer
	Metrics *metrics.Registry
	Log     *logger.Logger
}

Observability groups telemetry and diagnostics so that tracing, metrics, and structured logging are co-located.

type OptimizationStep added in v0.2.0

type OptimizationStep struct {
	Timestamp time.Time      `json:"timestamp"`
	Parameter string         `json:"parameter"`
	OldValue  string         `json:"old_value"`
	NewValue  string         `json:"new_value"`
	OldScore  float64        `json:"old_score"`
	NewScore  float64        `json:"new_score"`
	Gradient  PromptGradient `json:"gradient"`
}

OptimizationStep records one optimization iteration.

type OptimizedResult added in v0.2.0

type OptimizedResult struct {
	Original    string
	Optimized   string
	TokensSaved int
	Applied     []string
}

OptimizedResult contains the result of optimizing a single prompt.

type Optimizer added in v0.2.0

type Optimizer struct {
	Cost        Cost
	CostTracker *CostTracker
	Cascade     *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 added in v0.2.0

func (o *Optimizer) WithinBudget() bool

WithinBudget returns true if the session has not exceeded MaxBudget. Nil-safe: returns true (no limit) when Optimizer is nil.

type OutputRedactor added in v0.2.0

type OutputRedactor struct {
	Patterns     []*RedactPattern
	KnownSecrets map[string]string
	Stats        RedactStats
	// contains filtered or unexported fields
}

OutputRedactor strips sensitive information from tool outputs before they reach the LLM.

func NewOutputRedactor added in v0.2.0

func NewOutputRedactor() *OutputRedactor

NewOutputRedactor creates an OutputRedactor pre-loaded with 25+ built-in patterns covering common secret formats.

func (*OutputRedactor) AddKnownSecret added in v0.2.0

func (r *OutputRedactor) AddKnownSecret(name, value string)

AddKnownSecret registers a specific value to always redact from outputs. The name is used in the replacement placeholder.

func (*OutputRedactor) AddPattern added in v0.2.0

func (r *OutputRedactor) AddPattern(name string, pattern string, category string) error

AddPattern registers a new redaction pattern at runtime. Returns an error if the pattern cannot be compiled.

func (*OutputRedactor) FormatStats added in v0.2.0

func (r *OutputRedactor) FormatStats() string

FormatStats returns a human-readable summary of redaction statistics.

func (*OutputRedactor) IsClean added in v0.2.0

func (r *OutputRedactor) IsClean(output string) bool

IsClean performs a quick check to determine whether the output contains any detectable secrets. Returns true if no secrets are found.

func (*OutputRedactor) Redact added in v0.2.0

func (r *OutputRedactor) Redact(output string) string

Redact applies all patterns and known secrets to the output, replacing matches with [REDACTED:<category>] placeholders. Returns the sanitized string.

func (*OutputRedactor) RedactEnvVars added in v0.2.0

func (r *OutputRedactor) RedactEnvVars(output string) string

RedactEnvVars scans the output for values of known environment variables whose names suggest they contain secrets, and replaces them.

func (*OutputRedactor) RedactPaths added in v0.2.0

func (r *OutputRedactor) RedactPaths(output string, homedir string) string

RedactPaths replaces the user's home directory in output with ~/ to avoid leaking the full filesystem path structure.

type PRCompressor added in v0.2.0

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 added in v0.2.0

func NewPRCompressor(maxTokens int) *PRCompressor

NewPRCompressor creates a PRCompressor with the given token budget.

func (*PRCompressor) CompressDiff added in v0.2.0

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 added in v0.2.0

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 PackageDoc added in v0.2.0

type PackageDoc struct {
	Name        string
	Path        string
	Description string
	Functions   []FunctionDoc
	Types       []TypeDoc
	FileCount   int
}

PackageDoc represents documentation for a single package.

type PackingResult added in v0.2.0

type PackingResult struct {
	KeptMessages    []int   // indices of kept messages
	DroppedMessages []int   // indices of dropped messages
	TotalTokens     int     // total tokens of kept messages
	Utilization     float64 // percentage of context used (0.0 - 1.0)
	Summary         string  // summary of dropped content
}

PackingResult contains the outcome of a context packing operation.

type PackingStrategy added in v0.2.0

type PackingStrategy string

PackingStrategy determines how the context packer selects messages to keep.

const (
	// StrategyRecent keeps the most recent messages (simple truncation).
	StrategyRecent PackingStrategy = "recent"

	// StrategyRelevance scores messages by relevance to the current task.
	StrategyRelevance PackingStrategy = "relevance"

	// StrategyHybrid combines recency and relevance scoring (default).
	StrategyHybrid PackingStrategy = "hybrid"

	// StrategyCompression summarizes old messages, keeps recent verbatim.
	StrategyCompression PackingStrategy = "compression"
)

type ParamDoc added in v0.2.0

type ParamDoc struct {
	Name string
	Type string
	Desc string
}

ParamDoc represents documentation for a function parameter.

type PartySession added in v0.2.0

type PartySession struct {
	Topic    string
	Personas []Persona
	Turns    []PartyTurn
}

PartySession manages a multi-persona discussion.

func NewPartySession added in v0.2.0

func NewPartySession(topic string, personaCodes []string) *PartySession

NewPartySession creates a party mode session with selected personas.

func (*PartySession) GeneratePrompt added in v0.2.0

func (ps *PartySession) GeneratePrompt(roundNum int) string

GeneratePrompt creates the system prompt for a party mode round.

type PartyTurn added in v0.2.0

type PartyTurn struct {
	Persona Persona
	Content string
}

PartyTurn is a single contribution from a persona.

type PatchVerdict

type PatchVerdict struct {
	Likely     string   // "correct", "incorrect", "uncertain"
	Issues     []string // specific issues found
	Confidence float64  // 0-1
}

PatchVerdict is the result of a critic's pre-screening of a patch.

type Pattern added in v0.2.0

type Pattern struct {
	Name        string
	Description string
	Files       []string
	Confidence  float64
}

Pattern represents an architectural or design pattern detected in the codebase.

func DetectPatterns added in v0.2.0

func DetectPatterns(dir string) []Pattern

DetectPatterns identifies design patterns used in the codebase.

type PatternLibrary added in v0.2.0

type PatternLibrary struct {
	Patterns map[string]*PromptPattern
	Dir      string
	// contains filtered or unexported fields
}

PatternLibrary holds a collection of prompt patterns and supports loading, searching, and chaining them.

func NewPatternLibrary added in v0.2.0

func NewPatternLibrary(dir string) *PatternLibrary

NewPatternLibrary creates a new PatternLibrary with the given directory for custom pattern storage.

func (*PatternLibrary) Apply added in v0.2.0

func (pl *PatternLibrary) Apply(patternName string, input string) (string, string, error)

Apply resolves a pattern by name and injects the input into its template. Returns the system prompt, composed user prompt, and any error.

func (*PatternLibrary) Chain added in v0.2.0

func (pl *PatternLibrary) Chain(patterns []string, input string) []string

Chain applies multiple patterns sequentially, where the output prompt of one becomes the input for the next. Returns the list of user prompts generated at each step.

func (*PatternLibrary) Get added in v0.2.0

func (pl *PatternLibrary) Get(name string) *PromptPattern

Get retrieves a pattern by name. Returns nil if not found.

func (*PatternLibrary) ListByTag added in v0.2.0

func (pl *PatternLibrary) ListByTag(tag string) []*PromptPattern

ListByTag returns all patterns that have the specified tag.

func (*PatternLibrary) LoadBuiltins added in v0.2.0

func (pl *PatternLibrary) LoadBuiltins()

LoadBuiltins populates the library with built-in prompt patterns.

func (*PatternLibrary) LoadFromDir added in v0.2.0

func (pl *PatternLibrary) LoadFromDir(dir string) error

LoadFromDir loads custom patterns from markdown files with YAML frontmatter in the specified directory. Each .md file is parsed for frontmatter fields (name, description, system_prompt, output_format, tags, version, author) and the body becomes the UserTemplate.

func (*PatternLibrary) Register added in v0.2.0

func (pl *PatternLibrary) Register(pattern *PromptPattern)

Register adds a new pattern to the library. If a pattern with the same name exists, it is overwritten.

func (*PatternLibrary) Remove added in v0.2.0

func (pl *PatternLibrary) Remove(name string)

Remove deletes a pattern from the library by name.

func (*PatternLibrary) Search added in v0.2.0

func (pl *PatternLibrary) Search(query string) []*PromptPattern

Search performs a fuzzy search across pattern names, descriptions, and tags. Returns all patterns that match the query substring (case-insensitive).

type PendingChange

type PendingChange struct {
	Path       string
	Action     string // "create", "edit", "overwrite"
	OldContent string
	NewContent string
	Diff       string
	CreatedAt  time.Time
}

PendingChange represents a staged file modification that has not yet been applied to disk.

type PermissionEngine

type PermissionEngine struct {
	Memory     *PermissionMemory
	AutoMode   *permissions.AutoModeState
	Classifier *permissions.Classifier
	BypassKill *permissions.BypassKillswitch
	Mode       PermissionMode
	Autonomy   AutonomyLevel
	PromptFn   func(PermissionRequest) // callback to ask user
}

PermissionEngine encapsulates all permission-checking logic. Extracted from Session to keep the god object lean.

func NewPermissionEngine

func NewPermissionEngine() *PermissionEngine

NewPermissionEngine creates a PermissionEngine with sensible defaults.

func (*PermissionEngine) ApplyToolState

func (pe *PermissionEngine) ApplyToolState(name string)

ApplyToolState updates permission mode based on plan mode tools.

func (*PermissionEngine) CheckTool

func (pe *PermissionEngine) CheckTool(ctx context.Context, tc toolCallInfo) (bool, string)

CheckTool determines if a tool call is allowed, denied, or needs user prompt. Returns (granted bool, denyReason string). If the user must be asked, it blocks on PromptFn with a 5-minute timeout.

func (*PermissionEngine) SetMode

func (pe *PermissionEngine) SetMode(mode string) error

SetMode applies a permission mode string.

type PermissionMemory

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

PermissionMemory stores always-allow and always-deny rules.

func NewPermissionMemory

func NewPermissionMemory() *PermissionMemory

func (*PermissionMemory) AllowSpec

func (pm *PermissionMemory) AllowSpec(spec string)

AllowSpec applies an archive-style permission rule, e.g. "Bash(git:*)".

func (*PermissionMemory) AlwaysAllow

func (pm *PermissionMemory) AlwaysAllow(toolName string)

AlwaysAllow marks a tool as always allowed.

func (*PermissionMemory) AlwaysAllowPattern

func (pm *PermissionMemory) AlwaysAllowPattern(pattern string)

AlwaysAllowPattern adds a pattern rule (e.g. "bash:go *").

func (*PermissionMemory) AlwaysDeny

func (pm *PermissionMemory) AlwaysDeny(toolName string)

AlwaysDeny marks a tool as always denied.

func (*PermissionMemory) AlwaysDenyPattern

func (pm *PermissionMemory) AlwaysDenyPattern(pattern string)

AlwaysDenyPattern adds a deny pattern rule.

func (*PermissionMemory) Check

func (pm *PermissionMemory) Check(toolName string, summary string) *bool

Check returns: true=allowed, false=denied, nil=ask user.

func (*PermissionMemory) DenySpec

func (pm *PermissionMemory) DenySpec(spec string)

DenySpec applies an archive-style deny rule, e.g. "Write(*.env)".

type PermissionMode

type PermissionMode string

PermissionMode controls how permission prompts are handled.

const (
	PermissionModeDefault           PermissionMode = "default"
	PermissionModeAcceptEdits       PermissionMode = "acceptEdits"
	PermissionModeBypassPermissions PermissionMode = "bypassPermissions"
	PermissionModeDontAsk           PermissionMode = "dontAsk"
	PermissionModePlan              PermissionMode = "plan"
)

type PermissionRequest

type PermissionRequest struct {
	ToolName string
	ToolID   string
	Summary  string
	Response chan bool
}

PermissionRequest is sent from engine to TUI when a tool needs approval.

type Persona added in v0.2.0

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 PlanState

type PlanState struct {
	Name     string
	Subtasks []Subtask
	Current  int
	Active   bool
}

PlanState tracks progress through a set of subtasks.

func NewPlanState

func NewPlanState(name string) *PlanState

NewPlanState creates a new plan with the given name and no subtasks.

func (*PlanState) Format

func (ps *PlanState) Format() string

Format returns a human-readable display of the plan state.

func (*PlanState) MarkDone

func (ps *PlanState) MarkDone(id int)

MarkDone sets the subtask with the given ID to "done".

func (*PlanState) Next

func (ps *PlanState) Next() *Subtask

Next returns the next pending subtask and marks it as in_progress, or nil if none remain.

func (*PlanState) Progress

func (ps *PlanState) Progress() string

Progress returns a short progress string like "3/7 subtasks complete".

func (*PlanState) Skip

func (ps *PlanState) Skip(id int)

Skip sets the subtask with the given ID to "skipped".

type PlanStep added in v0.2.0

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 added in v0.2.0

type PlannedCall struct {
	ToolName string
	Args     map[string]interface{}
	Targets  []string // files affected by this call
}

PlannedCall describes a tool call to be planned, including which files it targets.

type PostResponseResult added in v0.2.0

type PostResponseResult struct {
	FormattedResponse string
	QualityScore      float64
	MentionedFiles    []string
	TokensUsed        int
}

PostResponseResult holds the aggregated results of the post-response pipeline.

type PostToolResult added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

type Prediction struct {
	InputTokens   int
	OutputTokens  int
	TotalTokens   int
	EstimatedCost float64
	Confidence    float64
	Reasoning     string
}

Prediction holds a token usage estimate for a task.

type PredictionRecord added in v0.2.0

type PredictionRecord struct {
	TaskType  string
	Predicted int
	Actual    int
	Model     string
	Timestamp time.Time
	Accuracy  float64
}

PredictionRecord stores one prediction-vs-actual pair for calibration.

type ProfileSpan added in v0.2.0

type ProfileSpan struct {
	Name     string
	Start    time.Time
	End      time.Time
	Duration time.Duration
	Metadata map[string]string
	Children []ProfileSpan
}

ProfileSpan represents a timed span of execution.

type Profiler added in v0.2.0

type Profiler struct {
	Enabled  bool
	Spans    []ProfileSpan
	Counters map[string]*Counter
	Timers   map[string]*Timer
	// contains filtered or unexported fields
}

Profiler tracks and reports on agent performance metrics including response times, token efficiency, and tool call patterns.

func NewProfiler added in v0.2.0

func NewProfiler() *Profiler

NewProfiler creates a new enabled Profiler with initialized maps.

func (*Profiler) EndSpan added in v0.2.0

func (p *Profiler) EndSpan(span *ProfileSpan)

EndSpan completes a span and records it.

func (*Profiler) ExportJSON added in v0.2.0

func (p *Profiler) ExportJSON() string

ExportJSON returns a JSON representation of all profiling data.

func (*Profiler) GetP50 added in v0.2.0

func (p *Profiler) GetP50(timer string) time.Duration

GetP50 returns the 50th percentile duration for a timer.

func (*Profiler) GetP95 added in v0.2.0

func (p *Profiler) GetP95(timer string) time.Duration

GetP95 returns the 95th percentile duration for a timer.

func (*Profiler) GetP99 added in v0.2.0

func (p *Profiler) GetP99(timer string) time.Duration

GetP99 returns the 99th percentile duration for a timer.

func (*Profiler) HotPaths added in v0.2.0

func (p *Profiler) HotPaths() [][]string

HotPaths finds the most time-consuming span sequences.

func (*Profiler) Increment added in v0.2.0

func (p *Profiler) Increment(counter string, delta int64)

Increment adds delta to the named counter.

func (*Profiler) Recommendations added in v0.2.0

func (p *Profiler) Recommendations() []string

Recommendations provides optimization suggestions based on profile data.

func (*Profiler) RecordDuration added in v0.2.0

func (p *Profiler) RecordDuration(timer string, d time.Duration)

RecordDuration adds a duration sample to the named timer.

func (*Profiler) Report added in v0.2.0

func (p *Profiler) Report() string

Report generates a human-readable performance profile report.

func (*Profiler) Reset added in v0.2.0

func (p *Profiler) Reset()

Reset clears all profiling data.

func (*Profiler) StartSpan added in v0.2.0

func (p *Profiler) StartSpan(name string) *ProfileSpan

StartSpan begins a new profiling span with the given name.

type ProjectAnalysis added in v0.2.0

type ProjectAnalysis struct {
	Name         string
	Language     string
	Framework    string
	Architecture string
	EntryPoints  []string
	KeyModules   []ModuleInfo
	Patterns     []Pattern
	Conventions  []string
	Dependencies int
	TestCoverage string
	LOC          int
	Complexity   string
}

ProjectAnalysis holds the full analysis of a project's architecture, patterns, and conventions.

type ProjectAnalyzer added in v0.2.0

type ProjectAnalyzer struct {
	Dir string
	// contains filtered or unexported fields
}

ProjectAnalyzer performs deep analysis of a codebase to understand its architecture, patterns, and conventions. Inspired by gpt-pilot's importer agent.

func NewProjectAnalyzer added in v0.2.0

func NewProjectAnalyzer(dir string) *ProjectAnalyzer

NewProjectAnalyzer creates a new ProjectAnalyzer for the given directory.

func (*ProjectAnalyzer) Analyze added in v0.2.0

func (pa *ProjectAnalyzer) Analyze() (*ProjectAnalysis, error)

Analyze performs a full project scan: detects language/framework, maps architecture, identifies entry points, detects patterns, and extracts conventions.

func (*ProjectAnalyzer) AnalyzeModule added in v0.2.0

func (pa *ProjectAnalyzer) AnalyzeModule(path string) *ModuleInfo

AnalyzeModule scans a package directory and extracts its public API, line count, and purpose.

type ProjectContext added in v0.2.0

type ProjectContext struct {
	ProjectDir string
	Loaded     map[string]string // filename → content
}

ProjectContext loads and manages persistent project knowledge files.

func NewProjectContext added in v0.2.0

func NewProjectContext(projectDir string) *ProjectContext

NewProjectContext creates a context loader for the given project directory.

func (*ProjectContext) HasContext added in v0.2.0

func (pc *ProjectContext) HasContext() bool

HasContext reports whether any project context files exist.

func (*ProjectContext) InitPrompt added in v0.2.0

func (pc *ProjectContext) InitPrompt() string

InitPrompt returns a prompt for hawk to generate initial project-context.md.

func (*ProjectContext) Load added in v0.2.0

func (pc *ProjectContext) Load() string

Load reads all project context files and returns combined content.

type ProjectDoc added in v0.2.0

type ProjectDoc struct {
	Name         string
	Description  string
	Packages     []PackageDoc
	Architecture string
	QuickStart   string
	GeneratedAt  time.Time
}

ProjectDoc represents the full documentation for a project.

type ProjectSnapshot added in v0.2.0

type ProjectSnapshot struct {
	DirectoryListing string    // ls -1 output of the project root
	RecentCommits    string    // git log --oneline -10
	GitStatus        string    // git status --short
	GatheredAt       time.Time // when this snapshot was created
}

ProjectSnapshot holds a point-in-time view of project state gathered via shell commands. Inspired by herm's projectSnapshot pattern.

func (*ProjectSnapshot) ForExploreMode added in v0.2.0

func (s *ProjectSnapshot) ForExploreMode() *ProjectSnapshot

ForExploreMode returns a copy of the snapshot with GitStatus cleared. This is useful for read-only agents that don't need working tree state, saving tokens in the prompt.

type ProjectSnapshotCache added in v0.2.0

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

ProjectSnapshotCache caches a ProjectSnapshot for a given directory, refreshing it only after the TTL expires. This avoids redundant shell commands when multiple sub-agents spawn in rapid succession against an unchanged repo.

func NewProjectSnapshotCache added in v0.2.0

func NewProjectSnapshotCache(dir string, ttl time.Duration) *ProjectSnapshotCache

NewProjectSnapshotCache creates a new ProjectSnapshotCache for the given directory. If ttl is zero, DefaultProjectSnapshotTTL is used.

func (*ProjectSnapshotCache) Get added in v0.2.0

Get returns a cached project snapshot if it's still valid, or gathers a fresh one by running shell commands. The provided context controls overall cancellation but individual commands have a 2s timeout.

func (*ProjectSnapshotCache) Invalidate added in v0.2.0

func (c *ProjectSnapshotCache) Invalidate()

Invalidate forces the next Get call to gather a fresh snapshot.

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 added in v0.2.0

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 PromptExample added in v0.2.0

type PromptExample struct {
	Input    string  `json:"input"`
	Output   string  `json:"output"`
	Score    float64 `json:"score"`
	Category string  `json:"category"`
}

PromptExample is a single example for few-shot prompting in the optimizer.

type PromptFewShotSelector added in v0.2.0

type PromptFewShotSelector struct {
	Examples []PromptExample
}

PromptFewShotSelector picks the best few-shot examples from a pool based on similarity.

func (*PromptFewShotSelector) Select added in v0.2.0

func (fs *PromptFewShotSelector) Select(query string, k int) []PromptExample

Select picks the top-k examples most relevant to the query.

type PromptGradient added in v0.2.0

type PromptGradient struct {
	Parameter string  `json:"parameter"`
	Feedback  string  `json:"feedback"`  // what went wrong
	Direction string  `json:"direction"` // how to improve
	Magnitude float64 `json:"magnitude"` // 0.0-1.0 how much to change
}

PromptGradient is textual feedback on how to improve a prompt (like a gradient).

type PromptMsg added in v0.2.0

type PromptMsg struct {
	Role    string
	Content string
	Tokens  int
}

PromptMsg represents a message in a conversation with role, content, and token count.

type PromptOpt added in v0.2.0

type PromptOpt struct {
	Name    string
	ApplyFn func(string) string
	Enabled bool
}

PromptOpt represents a single optimization strategy that can be applied to prompts.

type PromptOptimizer added in v0.2.0

type PromptOptimizer struct {
	Parameters map[string]*PromptParameter
	History    []OptimizationStep
	Path       string
}

PromptOptimizer auto-improves hawk's prompts based on success/failure signals.

func NewPromptOptimizer added in v0.2.0

func NewPromptOptimizer() *PromptOptimizer

NewPromptOptimizer creates an optimizer that persists to ~/.hawk/prompt_params.json.

func (*PromptOptimizer) ApplyGradient added in v0.2.0

func (po *PromptOptimizer) ApplyGradient(paramName, newValue string, gradient PromptGradient)

ApplyGradient updates a parameter with an optimized value.

func (*PromptOptimizer) Get added in v0.2.0

func (po *PromptOptimizer) Get(name string) string

Get returns the current optimized value of a parameter.

func (*PromptOptimizer) NeedsOptimization added in v0.2.0

func (po *PromptOptimizer) NeedsOptimization(threshold float64) []*PromptParameter

NeedsOptimization returns parameters with scores below threshold.

func (*PromptOptimizer) RecordFailure added in v0.2.0

func (po *PromptOptimizer) RecordFailure(paramName, feedback string)

RecordFailure signals that a prompt produced bad results.

func (*PromptOptimizer) RecordSuccess added in v0.2.0

func (po *PromptOptimizer) RecordSuccess(paramName string)

RecordSuccess signals that the current prompts worked well.

func (*PromptOptimizer) Register added in v0.2.0

func (po *PromptOptimizer) Register(name, initialValue string)

Register adds a tunable prompt parameter.

type PromptParameter added in v0.2.0

type PromptParameter struct {
	Name    string  `json:"name"`
	Value   string  `json:"value"`
	Score   float64 `json:"score"` // 0.0-1.0 performance score
	Version int     `json:"version"`
}

PromptParameter is a tunable prompt component (like a neural network weight).

type PromptPattern added in v0.2.0

type PromptPattern struct {
	Name         string
	Description  string
	SystemPrompt string
	UserTemplate string
	OutputFormat string
	Tags         []string
	Version      string
	Author       string
}

PromptPattern represents a composable, reusable prompt pattern for common tasks.

type PromptSection added in v0.2.0

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 added in v0.2.0

func DefaultSections(ctx PromptBuildContext) []PromptSection

DefaultSections returns the built-in prompt sections that hawk uses.

type PromptTuner

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

PromptTuner optimizes system prompt sections based on session outcomes. Tracks which prompt configurations lead to successful sessions and adjusts over time (OPRO/EvoPrompt pattern without LLM calls).

func NewPromptTuner

func NewPromptTuner() *PromptTuner

NewPromptTuner creates a tuner backed by ~/.hawk/prompt_tuning.json.

func (*PromptTuner) BestVariant

func (pt *PromptTuner) BestVariant(section string) (string, float64)

BestVariant returns the highest-scoring variant for a section.

func (*PromptTuner) RecordOutcome

func (pt *PromptTuner) RecordOutcome(section, content string, success bool)

RecordOutcome updates the variant score based on a session outcome.

func (*PromptTuner) Report

func (pt *PromptTuner) Report() string

Report returns a summary of all tracked variants sorted by score.

type PromptVariant

type PromptVariant struct {
	Section   string    `json:"section"`   // which section was varied
	Content   string    `json:"content"`   // the variant content
	Score     float64   `json:"score"`     // success rate (0-1)
	Uses      int       `json:"uses"`      // times used
	Successes int       `json:"successes"` // successful sessions with this variant
	LastUsed  time.Time `json:"last_used"`
}

PromptVariant is a tracked prompt configuration with its performance score.

type ProtectedPaths

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

ProtectedPaths tracks file paths that are read-only within the session. Tools that write or edit files should check IsProtected before proceeding.

func NewProtectedPaths

func NewProtectedPaths() *ProtectedPaths

NewProtectedPaths creates an empty ProtectedPaths set.

func (*ProtectedPaths) Add

func (p *ProtectedPaths) Add(path string)

Add marks a path as protected (read-only). The path is cleaned before storage for consistent lookups.

func (*ProtectedPaths) Format

func (p *ProtectedPaths) Format() string

Format returns a human-readable block suitable for system prompt injection.

func (*ProtectedPaths) IsProtected

func (p *ProtectedPaths) IsProtected(path string) bool

IsProtected returns true when path (or any ancestor directory) is protected.

func (*ProtectedPaths) List

func (p *ProtectedPaths) List() []string

List returns a sorted slice of all protected paths.

func (*ProtectedPaths) Remove

func (p *ProtectedPaths) Remove(path string)

Remove unmarks a path so it is no longer protected.

type PullRequest added in v0.2.0

type PullRequest struct {
	Number     int
	Title      string
	Body       string
	Branch     string
	BaseBranch string
	State      string
	Draft      bool
	Labels     []string
	URL        string
	Mergeable  bool
}

PullRequest represents a pull/merge request.

type QualityGate added in v0.2.0

type QualityGate struct {
	Phase GatePhase
	Check func() GateResult
}

QualityGate defines a checkpoint between phases.

func ImplementGate added in v0.2.0

func ImplementGate(validateCmd string, workDir string) QualityGate

ImplementGate checks that code compiles and basic tests pass.

func SpecGate added in v0.2.0

func SpecGate(spec *Spec) QualityGate

SpecGate checks that a spec is complete.

type QualityScorer added in v0.2.0

type QualityScorer struct {
	Weights ScoreWeights
	History []ScoredResponse
	// contains filtered or unexported fields
}

QualityScorer evaluates LLM response quality across multiple dimensions and provides feedback for the self-improvement loop.

func NewQualityScorer added in v0.2.0

func NewQualityScorer() *QualityScorer

NewQualityScorer creates a QualityScorer with default weights.

func (*QualityScorer) AverageScore added in v0.2.0

func (qs *QualityScorer) AverageScore(n int) float64

AverageScore computes the average composite score over the last n responses.

func (*QualityScorer) FormatReport added in v0.2.0

func (qs *QualityScorer) FormatReport(last int) string

FormatReport generates a formatted quality report for the last n responses.

func (*QualityScorer) GenerateFeedback added in v0.2.0

func (qs *QualityScorer) GenerateFeedback(scored *ScoredResponse) []string

GenerateFeedback produces human-readable suggestions based on the scored response.

func (*QualityScorer) Score added in v0.2.0

Score evaluates a response across all quality dimensions and returns a composite result.

func (*QualityScorer) TrendAnalysis added in v0.2.0

func (qs *QualityScorer) TrendAnalysis() string

TrendAnalysis returns a human-readable description of quality trends.

type QuickDevPhase added in v0.2.0

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 added in v0.2.0

func (p QuickDevPhase) String() string

type QuickDevState added in v0.2.0

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 RawMemory added in v0.2.0

type RawMemory struct {
	Content   string    `json:"content"`
	Source    string    `json:"source"` // "session", "tool_output", "user_feedback"
	SessionID string    `json:"session_id"`
	Timestamp time.Time `json:"timestamp"`
	Processed bool      `json:"processed"`
}

RawMemory represents an unprocessed memory ingested from a session.

type ReadOnlyContext added in v0.2.0

type ReadOnlyContext struct {
	Files          map[string]*ContextFile
	Patterns       []string
	MaxTokenBudget int
	// contains filtered or unexported fields
}

ReadOnlyContext manages a set of files loaded for agent reference that cannot be edited. Files are tracked with token budgets and can be auto-refreshed when they change on disk.

func NewReadOnlyContext added in v0.2.0

func NewReadOnlyContext(maxBudget int) *ReadOnlyContext

NewReadOnlyContext creates a new ReadOnlyContext with the given token budget.

func (*ReadOnlyContext) AddFile added in v0.2.0

func (rc *ReadOnlyContext) AddFile(path string, opts ...ContextFileOption) error

AddFile reads a file from disk and adds it to the read-only context. Returns an error if the file cannot be read or would exceed the token budget.

func (*ReadOnlyContext) AddPattern added in v0.2.0

func (rc *ReadOnlyContext) AddPattern(pattern string) error

AddPattern adds a glob pattern and immediately resolves matching files. Files that match the pattern are added to the read-only context.

func (*ReadOnlyContext) BuildContextBlock added in v0.2.0

func (rc *ReadOnlyContext) BuildContextBlock() string

BuildContextBlock formats all context files for system prompt injection.

func (*ReadOnlyContext) Evict added in v0.2.0

func (rc *ReadOnlyContext) Evict() []string

Evict removes unpinned files by LRU (oldest AddedAt first) until within budget. Returns the list of evicted file paths.

func (*ReadOnlyContext) IsReadOnly added in v0.2.0

func (rc *ReadOnlyContext) IsReadOnly(path string) bool

IsReadOnly checks if a path is in the read-only context. Used by Edit/Write tools to block modifications to context files.

func (*ReadOnlyContext) RefreshStale added in v0.2.0

func (rc *ReadOnlyContext) RefreshStale() error

RefreshStale re-reads files that have been modified on disk since last refresh. Only refreshes files with AutoRefresh=true.

func (*ReadOnlyContext) RemoveFile added in v0.2.0

func (rc *ReadOnlyContext) RemoveFile(path string)

RemoveFile removes a file from the read-only context.

func (*ReadOnlyContext) Stats added in v0.2.0

func (rc *ReadOnlyContext) Stats() ContextStats

Stats returns statistics about the current read-only context state.

type Recipe added in v0.2.0

type Recipe struct {
	ID          string                 `json:"id,omitempty"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Prompt      string                 `json:"prompt"`
	Tools       []string               `json:"tools"`
	Model       string                 `json:"model"`
	Provider    string                 `json:"provider"`
	Settings    map[string]interface{} `json:"settings,omitempty"`
	Author      string                 `json:"author"`
	Version     string                 `json:"version"`
	CreatedAt   time.Time              `json:"created_at"`
}

Recipe represents a shareable task recipe that captures instructions, tools, settings, and metadata for one-click execution via deeplinks.

type RecipeRegistry added in v0.2.0

type RecipeRegistry struct {
	Recipes map[string]*Recipe
	Dir     string
	// contains filtered or unexported fields
}

RecipeRegistry manages a collection of recipes with thread-safe access.

func NewRecipeRegistry added in v0.2.0

func NewRecipeRegistry(dir string) *RecipeRegistry

NewRecipeRegistry creates a new RecipeRegistry that stores recipes in dir.

func (*RecipeRegistry) Create added in v0.2.0

func (r *RecipeRegistry) Create(recipe *Recipe) string

Create adds a recipe to the registry and returns its generated ID.

func (*RecipeRegistry) Decode added in v0.2.0

func (r *RecipeRegistry) Decode(deeplink string) (*Recipe, error)

Decode parses a hawk:// deeplink URL, base64url-decodes the payload, and deserializes it into a Recipe.

func (*RecipeRegistry) Encode added in v0.2.0

func (r *RecipeRegistry) Encode(recipe *Recipe) string

Encode serializes a recipe to JSON, base64url-encodes it, and returns a hawk:// deeplink URL.

func (*RecipeRegistry) Execute added in v0.2.0

func (r *RecipeRegistry) Execute(ctx context.Context, recipe *Recipe, execFn func(context.Context, string) (string, error)) (string, error)

Execute applies the recipe settings and runs the prompt using the provided execution function. The execFn receives the context and the recipe prompt, and returns the output or an error.

func (*RecipeRegistry) FormatRecipe added in v0.2.0

func (r *RecipeRegistry) FormatRecipe(recipe *Recipe) string

FormatRecipe returns a human-readable formatted string representation of the recipe.

func (*RecipeRegistry) Get added in v0.2.0

func (r *RecipeRegistry) Get(id string) *Recipe

Get returns a recipe by ID, or nil if not found.

func (*RecipeRegistry) ImportFromURL added in v0.2.0

func (r *RecipeRegistry) ImportFromURL(url string) (*Recipe, error)

ImportFromURL decodes a hawk:// deeplink URL and imports the recipe into the registry.

func (*RecipeRegistry) List added in v0.2.0

func (r *RecipeRegistry) List() []*Recipe

List returns all recipes in the registry.

func (*RecipeRegistry) Load added in v0.2.0

func (r *RecipeRegistry) Load() error

Load reads recipes from the registry's directory on disk.

func (*RecipeRegistry) Save added in v0.2.0

func (r *RecipeRegistry) Save() error

Save persists all recipes in the registry to disk as a JSON file.

func (*RecipeRegistry) Share added in v0.2.0

func (r *RecipeRegistry) Share(recipe *Recipe) string

Share generates a compact shareable deeplink URL for the recipe.

func (*RecipeRegistry) Validate added in v0.2.0

func (r *RecipeRegistry) Validate(recipe *Recipe) []string

Validate checks a recipe for required fields and returns a list of validation error messages. An empty slice means the recipe is valid.

type Recommendation added in v0.2.0

type Recommendation struct {
	Type             string // "model_switch", "caching", "compression", "batching"
	Description      string
	EstimatedSavings float64 // USD per day
	Priority         string  // "high", "medium", "low"
	Action           string  // what to do
}

Recommendation represents a cost optimization recommendation.

type RecoveryAttempt added in v0.2.0

type RecoveryAttempt struct {
	Error     string
	Strategy  string
	Recovered bool
	Duration  time.Duration
	Timestamp time.Time
}

RecoveryAttempt records a single recovery attempt for history tracking.

type RecoveryContext added in v0.2.0

type RecoveryContext struct {
	Error         error
	ErrorMsg      string
	LastToolCall  string
	LastArgs      map[string]interface{}
	Messages      []string
	FilesModified []string
	Attempt       int
}

RecoveryContext provides information about the error and its surrounding context.

type RecoveryResult added in v0.2.0

type RecoveryResult struct {
	Recovered bool
	Action    string
	Message   string
	RetryWith string
}

RecoveryResult describes the outcome and suggested action of a recovery attempt.

type RecoveryStrategy added in v0.2.0

type RecoveryStrategy struct {
	Name         string
	ErrorPattern *regexp.Regexp
	RecoverFn    func(err error, context *RecoveryContext) (*RecoveryResult, error)
	Priority     int
	SuccessCount int
	FailureCount int
}

RecoveryStrategy defines a pattern-matched recovery approach for a class of errors.

type RedactPattern added in v0.2.0

type RedactPattern struct {
	Name        string
	Pattern     *regexp.Regexp
	Replacement string
	Category    string // "api_key", "token", "password", "cert", "connection_string"
}

RedactPattern defines a regex pattern used to detect and redact sensitive information.

type RedactStats added in v0.2.0

type RedactStats struct {
	TotalRedacted int
	ByCategory    map[string]int
	BytesSaved    int
}

RedactStats tracks cumulative redaction statistics.

type ReflectionEntry added in v0.2.0

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

func NewReflector(llm LLMClient, model string) *Reflector

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

func (r *Reflector) InjectReflections() string

InjectReflections formats reflection history as a string for system prompt injection.

func (*Reflector) Reflect

func (r *Reflector) Reflect(ctx context.Context, goal string, msgs []client.EyrieMessage, errorContext string) (*ReflectionEntry, error)

Reflect analyzes a failure and records a lesson.

func (*Reflector) Reset

func (r *Reflector) Reset()

Reset clears all reflection history.

type Release added in v0.2.0

type Release struct {
	Version         string
	Date            time.Time
	Changes         []ChangeEntry
	BreakingChanges []ChangeEntry
	Contributors    []string
	Stats           ReleaseStats
}

Release represents a prepared release with all associated metadata.

type ReleaseManager added in v0.2.0

type ReleaseManager struct {
	ProjectDir     string
	CurrentVersion string
	// contains filtered or unexported fields
}

ReleaseManager handles release automation including changelog generation, version bumping, and release preparation.

func NewReleaseManager added in v0.2.0

func NewReleaseManager(projectDir string) *ReleaseManager

NewReleaseManager creates a new ReleaseManager for the given project directory.

func (*ReleaseManager) DetectCurrentVersion added in v0.2.0

func (rm *ReleaseManager) DetectCurrentVersion() (string, error)

DetectCurrentVersion reads the current version from git tags, go.mod, package.json, or Cargo.toml.

func (*ReleaseManager) GatherChanges added in v0.2.0

func (rm *ReleaseManager) GatherChanges(sinceTag string) ([]ChangeEntry, error)

GatherChanges collects and parses all commits since the given tag.

func (*ReleaseManager) PrepareRelease added in v0.2.0

func (rm *ReleaseManager) PrepareRelease() (*Release, error)

PrepareRelease gathers changes since the last tag, bumps the version, generates changelog, and returns the release ready for review.

func (*ReleaseManager) ValidateRelease added in v0.2.0

func (rm *ReleaseManager) ValidateRelease(release *Release) []string

ValidateRelease checks that a release is valid and ready to be published. Returns a list of validation issues (empty if valid).

type ReleaseStats added in v0.2.0

type ReleaseStats struct {
	Commits      int
	FilesChanged int
	Additions    int
	Deletions    int
	Contributors int
}

ReleaseStats holds numerical statistics for a release.

type RepoRelation added in v0.2.0

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 RequestCost added in v0.2.0

type RequestCost struct {
	Model        string
	Provider     string
	InputTokens  int
	OutputTokens int
	CostUSD      float64
	TaskType     string // "chat", "code", "review", "summarize"
	Duration     time.Duration
	CacheHit     bool
	Timestamp    time.Time
}

RequestCost records the cost details of a single API request.

type ResearchAgent added in v0.2.0

type ResearchAgent struct {
	MaxWorkers int
	Timeout    time.Duration
	Results    []ResearchResult
	// contains filtered or unexported fields
}

ResearchAgent gathers information from multiple sources in parallel, inspired by gpt-researcher's parallel crawler pattern.

func NewResearchAgent added in v0.2.0

func NewResearchAgent(maxWorkers int) *ResearchAgent

NewResearchAgent creates a ResearchAgent with the given worker pool size. If maxWorkers <= 0, it defaults to 5.

func (*ResearchAgent) DecomposeQuestion added in v0.2.0

func (ra *ResearchAgent) DecomposeQuestion(question string) []string

DecomposeQuestion breaks a complex question into searchable sub-queries.

func (*ResearchAgent) FormatResult added in v0.2.0

func (ra *ResearchAgent) FormatResult(result *ResearchResult) string

FormatResult produces a human-readable formatted output of a ResearchResult.

func (*ResearchAgent) ParallelSearch added in v0.2.0

func (ra *ResearchAgent) ParallelSearch(ctx context.Context, queries []string, searchFn func(string) (string, error)) []ResearchFinding

ParallelSearch runs searches concurrently using a worker pool and collects results.

func (*ResearchAgent) RankFindings added in v0.2.0

func (ra *ResearchAgent) RankFindings(findings []ResearchFinding, query string) []ResearchFinding

RankFindings scores findings by relevance to the original query and returns them sorted.

func (*ResearchAgent) Research added in v0.2.0

func (ra *ResearchAgent) Research(ctx context.Context, query ResearchQuery, searchFn func(string) (string, error)) (*ResearchResult, error)

Research executes a full research cycle: decompose, search in parallel, rank, and synthesize.

func (*ResearchAgent) Synthesize added in v0.2.0

func (ra *ResearchAgent) Synthesize(findings []ResearchFinding, query string) string

Synthesize combines findings into a coherent summary, deduplicating overlapping information.

type ResearchFinding added in v0.2.0

type ResearchFinding struct {
	Content    string
	Source     string
	Relevance  float64
	Confidence float64
}

ResearchFinding represents a single piece of discovered information.

type ResearchQuery added in v0.2.0

type ResearchQuery struct {
	Question     string
	SubQuestions []string
	Sources      []string
	MaxTokens    int
}

ResearchQuery defines a research task with a main question and optional sub-questions.

type ResearchResult added in v0.2.0

type ResearchResult struct {
	Query       string
	Findings    []ResearchFinding
	Sources     []string
	Duration    time.Duration
	TotalTokens int
}

ResearchResult holds the aggregated output of a research operation.

type ResponseCache added in v0.2.0

type ResponseCache struct {
	Entries    map[string]*CacheEntry
	MaxEntries int
	MaxAge     time.Duration
	HitCount   int64
	MissCount  int64
	// contains filtered or unexported fields
}

ResponseCache caches LLM responses for identical or similar prompts.

func NewResponseCache added in v0.2.0

func NewResponseCache(maxEntries int, maxAge time.Duration) *ResponseCache

NewResponseCache creates a new ResponseCache with the given parameters. If maxEntries is 0, DefaultMaxEntries is used. If maxAge is 0, DefaultMaxAge is used.

func (*ResponseCache) EvictLRU added in v0.2.0

func (rc *ResponseCache) EvictLRU()

EvictLRU removes the least-recently-hit entry from the cache.

func (*ResponseCache) Export added in v0.2.0

func (rc *ResponseCache) Export() ([]byte, error)

Export serializes the cache to JSON bytes.

func (*ResponseCache) FormatStats added in v0.2.0

func (rc *ResponseCache) FormatStats() string

FormatStats returns a human-readable summary of cache statistics.

func (*ResponseCache) Get added in v0.2.0

func (rc *ResponseCache) Get(prompt, model string) (*CacheEntry, bool)

Get retrieves a cached response for the given prompt and model. It first tries an exact hash match, then falls back to similarity matching.

func (*ResponseCache) Import added in v0.2.0

func (rc *ResponseCache) Import(data []byte) error

Import loads cache entries from JSON bytes, merging with existing entries.

func (*ResponseCache) Invalidate added in v0.2.0

func (rc *ResponseCache) Invalidate(pattern string)

Invalidate removes entries whose prompt matches the given pattern (regex).

func (*ResponseCache) InvalidateByAge added in v0.2.0

func (rc *ResponseCache) InvalidateByAge(maxAge time.Duration)

InvalidateByAge removes entries older than maxAge.

func (*ResponseCache) Set added in v0.2.0

func (rc *ResponseCache) Set(prompt, response, model string, tokens int)

Set stores a prompt/response pair in the cache. If the cache is at capacity, it evicts the least recently used entry.

func (*ResponseCache) SimilarityMatch added in v0.2.0

func (rc *ResponseCache) SimilarityMatch(prompt string, threshold float64) (*CacheEntry, float64)

SimilarityMatch finds the most similar cached prompt above the threshold. Uses word-level Jaccard similarity.

func (*ResponseCache) Stats added in v0.2.0

func (rc *ResponseCache) Stats() CacheStats

Stats returns current cache statistics.

type ResponseContext added in v0.2.0

type ResponseContext struct {
	UserPrompt        string
	AssistantResponse string
	ToolCallCount     int
	ToolErrors        int
	FilesModified     []string
	TestsPassed       bool
	LintPassed        bool
	TokensUsed        int
	Duration          time.Duration
}

ResponseContext provides the context needed to evaluate a response's quality.

type ResponseFormatter added in v0.2.0

type ResponseFormatter struct {
	Rules []FormatRule
	// contains filtered or unexported fields
}

ResponseFormatter post-processes LLM responses to ensure consistent formatting, fix common issues, and enhance readability.

func NewResponseFormatter added in v0.2.0

func NewResponseFormatter() *ResponseFormatter

NewResponseFormatter creates a ResponseFormatter with built-in rules.

func (*ResponseFormatter) AddRule added in v0.2.0

func (rf *ResponseFormatter) AddRule(rule FormatRule)

AddRule adds a new formatting rule to the formatter.

func (*ResponseFormatter) DisableRule added in v0.2.0

func (rf *ResponseFormatter) DisableRule(name string)

DisableRule disables a rule by name.

func (*ResponseFormatter) EnableRule added in v0.2.0

func (rf *ResponseFormatter) EnableRule(name string)

EnableRule enables a rule by name.

func (*ResponseFormatter) Format added in v0.2.0

func (rf *ResponseFormatter) Format(response string) *FormattedResponse

Format applies all enabled rules to the response and tracks changes.

type RetryDecision added in v0.2.0

type RetryDecision struct {
	ShouldRetry      bool
	Delay            time.Duration
	Reason           string
	FallbackProvider string // switch provider if this one is failing
	FallbackModel    string
}

RetryDecision describes what the caller should do after a failure.

type RetryItem added in v0.2.0

type RetryItem struct {
	ID          string
	Operation   string
	Args        map[string]interface{}
	Error       string
	Attempts    int
	MaxAttempts int
	NextRetry   time.Time
	Priority    int
	CreatedAt   time.Time
	Status      string // "pending", "retrying", "succeeded", "failed_permanent"
}

RetryItem represents a single operation queued for retry.

type RetryQueue added in v0.2.0

type RetryQueue struct {
	Items       []*RetryItem
	MaxSize     int
	BackoffBase time.Duration
	BackoffMax  time.Duration
	// contains filtered or unexported fields
}

RetryQueue manages failed operations with exponential backoff, priority ordering, and deduplication of identical operations.

func NewRetryQueue added in v0.2.0

func NewRetryQueue() *RetryQueue

NewRetryQueue creates a RetryQueue with sensible defaults.

func (*RetryQueue) CalculateBackoff added in v0.2.0

func (rq *RetryQueue) CalculateBackoff(attempts int) time.Duration

CalculateBackoff computes exponential backoff with jitter for the given attempt count. The result is capped at BackoffMax.

func (*RetryQueue) Clear added in v0.2.0

func (rq *RetryQueue) Clear()

Clear removes all items from the queue.

func (*RetryQueue) Dequeue added in v0.2.0

func (rq *RetryQueue) Dequeue() *RetryItem

Dequeue returns the highest-priority item whose NextRetry time has passed. Returns nil if no items are ready.

func (*RetryQueue) Enqueue added in v0.2.0

func (rq *RetryQueue) Enqueue(operation string, args map[string]interface{}, err string, priority int) *RetryItem

Enqueue adds an operation to the retry queue. If an identical operation+args combination is already queued, it increments the attempt count instead of creating a duplicate entry.

func (*RetryQueue) FormatQueue added in v0.2.0

func (rq *RetryQueue) FormatQueue() string

FormatQueue returns a human-readable representation of the retry queue.

func (*RetryQueue) GetPending added in v0.2.0

func (rq *RetryQueue) GetPending() []*RetryItem

GetPending returns all items that are still pending or retrying.

func (*RetryQueue) GetReady added in v0.2.0

func (rq *RetryQueue) GetReady() []*RetryItem

GetReady returns all items that are ready to be retried now.

func (*RetryQueue) MarkFailed added in v0.2.0

func (rq *RetryQueue) MarkFailed(id string, err string)

MarkFailed records a failure for an item. If the item has reached its max attempts, it is marked as permanently failed. Otherwise, the next retry time is recalculated with exponential backoff.

func (*RetryQueue) MarkSuccess added in v0.2.0

func (rq *RetryQueue) MarkSuccess(id string)

MarkSuccess marks an item as successfully completed.

func (*RetryQueue) Prune added in v0.2.0

func (rq *RetryQueue) Prune()

Prune removes succeeded and permanently failed items that are older than 1 hour.

func (*RetryQueue) Size added in v0.2.0

func (rq *RetryQueue) Size() int

Size returns the total number of items in the queue.

type RetryStrategy added in v0.2.0

type RetryStrategy struct {
	Provider          string
	BaseDelay         time.Duration
	MaxDelay          time.Duration
	MaxRetries        int
	BackoffMultiplier float64
	JitterPct         float64  // 0-100, adds randomness
	RetryOn           []string // error patterns to retry on
	AbortOn           []string // error patterns to immediately fail on
}

RetryStrategy defines the retry behavior for a specific provider.

type ReviewBot added in v0.2.0

type ReviewBot struct {
	Rules    []ReviewRule
	Severity string // minimum severity to report: "error", "warning", "info"
	// contains filtered or unexported fields
}

ReviewBot is a rule-based code review engine that produces structured feedback without requiring an LLM call.

func NewReviewBot added in v0.2.0

func NewReviewBot() *ReviewBot

NewReviewBot creates a ReviewBot pre-loaded with 20+ built-in rules.

func (*ReviewBot) ReviewDiff added in v0.2.0

func (rb *ReviewBot) ReviewDiff(diff string) (*ReviewReport, error)

ReviewDiff parses a unified diff and reviews only changed lines.

func (*ReviewBot) ReviewFile added in v0.2.0

func (rb *ReviewBot) ReviewFile(path, content string) (*ReviewReport, error)

ReviewFile reviews a full file's content.

type ReviewComment added in v0.2.0

type ReviewComment struct {
	File       string
	Line       int
	Severity   string // "error", "warning", "info"
	Category   string
	Message    string
	Suggestion string
	RuleID     string
}

ReviewComment represents a single piece of review feedback.

func FilterBySeverity added in v0.2.0

func FilterBySeverity(comments []ReviewComment, minSeverity string) []ReviewComment

FilterBySeverity returns only comments at or above the specified minimum severity.

type ReviewFinding added in v0.2.0

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 added in v0.2.0

type ReviewReport struct {
	Comments      []ReviewComment
	FilesReviewed int
	IssuesFound   int
	BySeverity    map[string]int
	Duration      time.Duration
}

ReviewReport summarizes the results of a code review.

type ReviewResult added in v0.2.0

type ReviewResult struct {
	Best          *Solution
	All           []Solution
	Attempts      int
	TotalDuration time.Duration
	TotalTokens   int
	Agreement     float64
}

ReviewResult holds the outcome of the multi-attempt review process.

type ReviewRule added in v0.2.0

type ReviewRule struct {
	ID       string
	Name     string
	Category string // "security", "performance", "correctness", "style", "testing"
	Language string
	Check    func(file string, lines []string, diff []DiffLine) []ReviewComment
}

ReviewRule defines a single review check that can be applied to code.

type RiskAssessment added in v0.2.0

type RiskAssessment struct {
	Score          float64
	Level          string
	Factors        []RiskFactor
	Mitigations    []string
	Recommendation string
}

RiskAssessment holds the result of evaluating how risky a proposed code change is.

type RiskAssessor added in v0.2.0

type RiskAssessor struct {
	Factors []RiskFactorDef
	// contains filtered or unexported fields
}

RiskAssessor evaluates risk of proposed code changes.

func NewRiskAssessor added in v0.2.0

func NewRiskAssessor() *RiskAssessor

NewRiskAssessor creates a new RiskAssessor with built-in factors.

func (*RiskAssessor) Assess added in v0.2.0

func (ra *RiskAssessor) Assess(ctx *RiskContext) *RiskAssessment

Assess evaluates all risk factors and returns a RiskAssessment.

type RiskContext added in v0.2.0

type RiskContext struct {
	Files             []string
	Diff              string
	TestsExist        bool
	IsExported        bool
	HasBreakingChange bool
	LinesChanged      int
	FilesAffected     int
	Complexity        int
}

RiskContext provides the context needed to assess risk of a change.

type RiskFactor added in v0.2.0

type RiskFactor struct {
	Name        string
	Weight      float64
	Score       float64
	Description string
}

RiskFactor represents an individual evaluated risk factor.

type RiskFactorDef added in v0.2.0

type RiskFactorDef struct {
	Name       string
	Weight     float64
	EvaluateFn func(ctx *RiskContext) float64
}

RiskFactorDef defines a risk factor with its evaluation function.

type RotatingWriter added in v0.2.0

type RotatingWriter struct {
	Dir      string
	Prefix   string
	MaxSize  int64
	MaxFiles int
	// contains filtered or unexported fields
}

RotatingWriter implements io.Writer with automatic log file rotation.

func NewRotatingWriter added in v0.2.0

func NewRotatingWriter(dir, prefix string) (*RotatingWriter, error)

NewRotatingWriter creates a RotatingWriter with sensible defaults.

func (*RotatingWriter) Close added in v0.2.0

func (rw *RotatingWriter) Close() error

Close closes the underlying file.

func (*RotatingWriter) Write added in v0.2.0

func (rw *RotatingWriter) Write(p []byte) (n int, err error)

Write implements io.Writer. It rotates the file when MaxSize is exceeded.

type RoutingDecision

type RoutingDecision struct {
	OriginalModel string    `json:"original_model"`
	SelectedModel string    `json:"selected_model"`
	TaskType      string    `json:"task_type"`
	Reason        string    `json:"reason"`
	Timestamp     time.Time `json:"timestamp"`
}

RoutingDecision records a single model selection event.

type SafetyLayer added in v0.2.0

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 added in v0.2.0

func (sl *SafetyLayer) IsPermitted(action string) bool

IsPermitted is a nil-safe convenience that delegates to the PermissionEngine.

type SafetyLimits

type SafetyLimits struct {
	MaxToolCalls    int     // max total tool invocations (default: 200)
	MaxFileWrites   int     // max files created/modified (default: 50)
	MaxBashCommands int     // max bash executions (default: 100)
	MaxCostUSD      float64 // max spend (default: from MaxBudgetUSD)
	MaxTurns        int     // max LLM turns (default: from MaxTurns)
	MaxOutputTokens int     // max total output tokens (default: 500K)
}

SafetyLimits caps what the agent can do in a single session.

func DefaultLimits

func DefaultLimits() SafetyLimits

DefaultLimits returns conservative safety limits for normal interactive use.

func ResearchLimits

func ResearchLimits() SafetyLimits

ResearchLimits returns strict per-iteration limits suitable for research tasks.

func VibeLimits

func VibeLimits() SafetyLimits

VibeLimits returns more permissive limits for autonomous/vibe mode.

type Sample added in v0.2.0

type Sample struct {
	ID         int
	Content    string
	Score      float64
	Duration   time.Duration
	TokensUsed int
}

Sample represents a single generated solution with metadata.

func BestScore added in v0.2.0

func BestScore(samples []Sample) *Sample

BestScore picks the highest-scored solution.

func MajorityVote added in v0.2.0

func MajorityVote(samples []Sample) *Sample

MajorityVote finds the most similar/common solution using pairwise similarity. The sample with the highest average similarity to all others wins.

func Synthesize added in v0.2.0

func Synthesize(samples []Sample) *Sample

Synthesize combines elements from all solutions, weighted by score. It selects unique paragraphs from higher-scoring samples first.

type Scaffolder added in v0.2.0

type Scaffolder struct {
	Templates   map[string]*Template
	TemplateDir string
	// contains filtered or unexported fields
}

Scaffolder manages templates and generates projects.

func NewScaffolder added in v0.2.0

func NewScaffolder() *Scaffolder

NewScaffolder creates a new Scaffolder with built-in templates.

func (*Scaffolder) Generate added in v0.2.0

func (s *Scaffolder) Generate(templateName string, vars map[string]string, outputDir string) error

Generate creates a project from a template.

func (*Scaffolder) ListTemplates added in v0.2.0

func (s *Scaffolder) ListTemplates() []*Template

ListTemplates returns all registered templates sorted by name.

func (*Scaffolder) LoadTemplate added in v0.2.0

func (s *Scaffolder) LoadTemplate(path string) (*Template, error)

LoadTemplate loads a template from a JSON file.

func (*Scaffolder) Preview added in v0.2.0

func (s *Scaffolder) Preview(templateName string, vars map[string]string) string

Preview shows what would be created without actually creating files.

func (*Scaffolder) RegisterTemplate added in v0.2.0

func (s *Scaffolder) RegisterTemplate(t *Template)

RegisterTemplate adds a new template to the scaffolder.

func (*Scaffolder) ValidateVars added in v0.2.0

func (s *Scaffolder) ValidateVars(tmpl *Template, vars map[string]string) []string

ValidateVars checks that required variables are provided and choices are valid.

type ScaleBehavior added in v0.2.0

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 added in v0.2.0

func GetBehavior(scale TaskScale) ScaleBehavior

GetBehavior returns the behavior config for a given scale.

type ScanResult added in v0.2.0

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 added in v0.2.0

type Schema struct {
	Name     string
	Type     string // "json", "yaml", "code", "structured"
	Required []string
	Fields   map[string]FieldSpec
	Pattern  *regexp.Regexp
	Examples []string
}

Schema defines the expected structure of an LLM output.

type SchemaValidationError added in v0.2.0

type SchemaValidationError struct {
	Field    string
	Message  string
	Expected string
	Got      string
}

SchemaValidationError describes a single schema validation failure.

type SchemaValidationResult added in v0.2.0

type SchemaValidationResult struct {
	Valid     bool
	Errors    []SchemaValidationError
	Warnings  []string
	Extracted interface{}
}

SchemaValidationResult holds the outcome of a schema validation pass.

type SchemaValidator added in v0.2.0

type SchemaValidator struct {
	Schemas map[string]*Schema
	// contains filtered or unexported fields
}

SchemaValidator validates LLM output against registered schemas.

func NewSchemaValidator added in v0.2.0

func NewSchemaValidator() *SchemaValidator

NewSchemaValidator creates a SchemaValidator pre-loaded with built-in schemas.

func (*SchemaValidator) Register added in v0.2.0

func (sv *SchemaValidator) Register(name string, schema *Schema)

Register adds or replaces a schema by name.

func (*SchemaValidator) Validate added in v0.2.0

func (sv *SchemaValidator) Validate(schemaName string, output string) *SchemaValidationResult

Validate dispatches validation based on the schema's Type.

func (*SchemaValidator) ValidateJSON added in v0.2.0

func (sv *SchemaValidator) ValidateJSON(output string, schema *Schema) *SchemaValidationResult

ValidateJSON extracts JSON from output and validates against the schema.

type ScoreWeights added in v0.2.0

type ScoreWeights struct {
	Completeness float64 // did it address the full request?
	Correctness  float64 // is the code syntactically valid?
	Conciseness  float64 // not overly verbose?
	ToolUsage    float64 // efficient use of tools?
	Safety       float64 // no dangerous operations?
}

ScoreWeights defines the relative importance of each quality dimension. All values should be in [0,1] and sum to 1.

func DefaultWeights added in v0.2.0

func DefaultWeights() ScoreWeights

DefaultWeights returns a balanced set of scoring weights.

type ScoredMessage added in v0.2.0

type ScoredMessage struct {
	Index    int
	Role     string
	Content  string
	Tokens   int
	Score    float64
	MustKeep bool // pinned messages, tool pairs
}

ScoredMessage represents a message with scoring metadata for packing decisions.

type ScoredResponse added in v0.2.0

type ScoredResponse struct {
	Score     float64            // 0-1 overall composite score
	Breakdown map[string]float64 // per-dimension scores
	Feedback  []string           // human-readable improvement suggestions
	Timestamp time.Time
	Model     string
	TaskType  string
}

ScoredResponse holds the quality evaluation of a single LLM response.

type ScrapeResult added in v0.2.0

type ScrapeResult struct {
	URL           string
	Title         string
	Content       string
	ContentType   string // "html", "json", "text", "code", "markdown"
	StatusCode    int
	FetchedAt     time.Time
	TokenEstimate int
}

ScrapeResult holds the extracted content from a fetched URL.

type SelectedTests added in v0.2.0

type SelectedTests struct {
	Tests    []string
	Packages []string
	Reason   map[string]string
	Coverage float64
}

SelectedTests holds the result of a diff-aware test selection.

type SelfAssessor added in v0.2.0

type SelfAssessor struct {
	History []Assessment
	// contains filtered or unexported fields
}

SelfAssessor evaluates agent performance after each task and tracks trends.

func NewSelfAssessor added in v0.2.0

func NewSelfAssessor() *SelfAssessor

NewSelfAssessor creates a new SelfAssessor with an empty history.

func (*SelfAssessor) Assess added in v0.2.0

func (sa *SelfAssessor) Assess(ctx TaskContext) *Assessment

Assess evaluates the agent's performance on a completed task across multiple dimensions and records the assessment in history.

func (*SelfAssessor) AverageScore added in v0.2.0

func (sa *SelfAssessor) AverageScore(n int) float64

AverageScore computes the average overall score of the last n assessments. If n is 0 or exceeds history length, all assessments are averaged.

func (*SelfAssessor) GetTrend added in v0.2.0

func (sa *SelfAssessor) GetTrend(dimension string) string

GetTrend analyzes the trend of a given dimension over the last 10 assessments. Returns "improving", "stable", or "declining".

func (*SelfAssessor) IdentifyStrengths added in v0.2.0

func (sa *SelfAssessor) IdentifyStrengths(ctx TaskContext) []string

IdentifyStrengths returns a list of things that went well.

func (*SelfAssessor) IdentifyWeaknesses added in v0.2.0

func (sa *SelfAssessor) IdentifyWeaknesses(ctx TaskContext) []string

IdentifyWeaknesses returns a list of things that went poorly.

func (*SelfAssessor) SuggestImprovements added in v0.2.0

func (sa *SelfAssessor) SuggestImprovements(ctx TaskContext) []string

SuggestImprovements returns actionable suggestions for future tasks.

type SelfAwareness added in v0.2.0

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 added in v0.2.0

func (sa *SelfAwareness) DelegationPrompt(prompt string, reason string) string

DelegationPrompt generates a prompt explaining why delegation is needed.

func (*SelfAwareness) ShouldDelegate added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

func NewSelfHealer(chatFn func(context.Context, string) (string, error)) *SelfHealer

NewSelfHealer creates a SelfHealer with sensible defaults.

func (*SelfHealer) ApplyFixes added in v0.2.0

func (sh *SelfHealer) ApplyFixes(fixes []FileFix) error

ApplyFixes applies a slice of file fixes to disk.

func (*SelfHealer) BuildFixPrompt added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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.

func (*SelfHealer) ParseFix added in v0.2.0

func (sh *SelfHealer) ParseFix(response string) ([]FileFix, error)

ParseFix parses the structured LLM response into a slice of FileFix values.

func (*SelfHealer) RunScript added in v0.2.0

func (sh *SelfHealer) RunScript(ctx context.Context, path string) (stdout, stderr string, exitCode int, err error)

RunScript executes a script at the given path and returns stdout, stderr, exit code, and any error.

type SelfImproveEntry added in v0.2.0

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 added in v0.2.0

type SelfImprover struct {
	Path    string
	Entries []SelfImproveEntry
}

SelfImprover tracks mistakes and lessons across sessions.

func NewSelfImprover added in v0.2.0

func NewSelfImprover() *SelfImprover

NewSelfImprover loads or creates the improvement log.

func (*SelfImprover) ForPrompt added in v0.2.0

func (si *SelfImprover) ForPrompt(maxEntries int) string

ForPrompt formats recent lessons as context for the system prompt.

func (*SelfImprover) Learn added in v0.2.0

func (si *SelfImprover) Learn(what, why, lesson, category string)

Learn records a new lesson.

func (*SelfImprover) Lessons added in v0.2.0

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 added in v0.2.0

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

SemanticAnalyzer performs semantic diff analysis on Go source code.

func NewSemanticAnalyzer added in v0.2.0

func NewSemanticAnalyzer() *SemanticAnalyzer

NewSemanticAnalyzer creates a new SemanticAnalyzer instance.

func (*SemanticAnalyzer) AnalyzeDiff added in v0.2.0

func (sa *SemanticAnalyzer) AnalyzeDiff(diff string) (*SemanticDiff, error)

AnalyzeDiff parses a unified diff and performs semantic analysis on Go code changes.

func (*SemanticAnalyzer) FindAffectedAPIs added in v0.2.0

func (sa *SemanticAnalyzer) FindAffectedAPIs(changes []SemanticChange, content string) []string

FindAffectedAPIs traces changed functions to HTTP handlers/routes in the content.

type SemanticChange added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

type SemanticDiff struct {
	Changes      []SemanticChange
	Summary      string
	RiskLevel    string
	AffectedAPIs []string
}

SemanticDiff holds the result of semantic analysis of a diff.

type ServiceOption added in v0.2.0

type ServiceOption func(*SessionServices)

ServiceOption configures a SessionServices during construction.

func WithCascade added in v0.2.0

func WithCascade(cascade *CascadeRouter) ServiceOption

WithCascade sets the CascadeRouter on the Optimizer.

func WithGuardian added in v0.2.0

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 added in v0.2.0

func WithLogger(log *logger.Logger) ServiceOption

WithLogger sets the logger on both CoreLoop and Observability.

func WithMaxBudget added in v0.2.0

func WithMaxBudget(budget float64) ServiceOption

WithMaxBudget sets the maximum budget on the Optimizer.

func WithMemory added in v0.2.0

func WithMemory(mem MemoryRecaller) ServiceOption

WithMemory sets the MemoryRecaller on the Intelligence service.

func WithProvider added in v0.2.0

func WithProvider(provider, model string) ServiceOption

WithProvider sets the LLM provider and model on the CoreLoop.

func WithSandbox added in v0.2.0

func WithSandbox(sandbox *DiffSandbox) ServiceOption

WithSandbox sets the DiffSandbox on the SafetyLayer.

func WithTools added in v0.2.0

func WithTools(registry *tool.Registry) ServiceOption

WithTools sets the tool registry on the CoreLoop.

func WithTracing added in v0.2.0

func WithTracing(tracer *trace.Tracer) ServiceOption

WithTracing sets the Tracer on the Observability service.

type Session

type Session struct {
	Cost   Cost
	Router *modelPkg.Router
	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

	PinnedMessages          int // messages to protect from compaction (from /pin)
	AutoCompactThresholdPct int // token % to trigger auto-compact (default 85)

	// Cost optimization
	Cascade     *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         *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         *trace.Tracer           // trace.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.

func NewSession

func NewSession(provider, model, systemPrompt string, registry *tool.Registry) *Session

NewSession creates a new conversation session.

func (*Session) AddAssistant

func (s *Session) AddAssistant(content string)

func (*Session) AddUser

func (s *Session) AddUser(content string)

func (*Session) AppendSystemContext

func (s *Session) AppendSystemContext(content string)

AppendSystemContext adds runtime context, such as /add-dir, to future model calls.

func (*Session) AutoCompactIfNeeded

func (s *Session) AutoCompactIfNeeded() bool

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) ConvoHead

func (s *Session) ConvoHead() string

ConvoHead returns the current conversation head node ID.

func (*Session) ForkConversation

func (s *Session) ForkConversation(nodeID string) (string, error)

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

func (s *Session) ListBranches(nodeID string) ([]*storage.DAGNode, error)

ListBranches returns child nodes (alternative branches) from a given node.

func (*Session) LoadMessages

func (s *Session) LoadMessages(msgs []client.EyrieMessage)

func (*Session) MessageCount

func (s *Session) MessageCount() int

func (*Session) Metrics

func (s *Session) Metrics() *metrics.Registry

func (*Session) Model

func (s *Session) Model() string

func (*Session) Provider

func (s *Session) Provider() string

func (*Session) RawMessages

func (s *Session) RawMessages() []client.EyrieMessage

RawMessages returns the conversation messages for persistence.

func (*Session) RemoveLastExchange

func (s *Session) RemoveLastExchange()

RemoveLastExchange removes the last user+assistant message pair.

func (*Session) Services added in v0.2.0

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) SetAPIKey

func (s *Session) SetAPIKey(provider, apiKey string)

SetAPIKey updates a provider API key for subsequent requests.

func (*Session) SetAPIKeys

func (s *Session) SetAPIKeys(apiKeys map[string]string)

SetAPIKeys updates all known provider API keys for subsequent requests.

func (*Session) SetAllowedDirs

func (s *Session) SetAllowedDirs(dirs []string)

SetAllowedDirs sets directories that file tools are allowed to access.

func (*Session) SetLogger

func (s *Session) SetLogger(l *logger.Logger)

SetLogger replaces the session logger.

func (*Session) SetMaxBudgetUSD

func (s *Session) SetMaxBudgetUSD(amount float64) error

SetMaxBudgetUSD caps estimated API spend for this session.

func (*Session) SetMaxTurns

func (s *Session) SetMaxTurns(turns int) error

SetMaxTurns caps the number of model turns in the agent loop.

func (*Session) SetModel

func (s *Session) SetModel(model string)

SetModel updates the active model for subsequent requests.

func (*Session) SetPermissionMode

func (s *Session) SetPermissionMode(mode string) error

SetPermissionMode applies an archive-compatible permission mode.

func (*Session) SetProvider

func (s *Session) SetProvider(provider string)

SetProvider updates the active provider for subsequent requests.

func (*Session) SetTestClient added in v0.2.0

func (s *Session) SetTestClient(c ChatClient)

SetTestClient replaces the session's LLM client. For testing only.

func (*Session) ShouldAutoCompact

func (s *Session) ShouldAutoCompact() bool

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 added in v0.2.0

func (s *Session) SplitTurnNeeded(keepCount int) bool

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) SwitchBranch

func (s *Session) SwitchBranch(nodeID string) error

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 added in v0.2.0

type SessionCompressor struct {
	Strategy         CompressStrategy
	PreservePatterns []string
	MinMessages      int
	// contains filtered or unexported fields
}

SessionCompressor performs intelligent session compression using configurable strategies.

func NewSessionCompressor added in v0.2.0

func NewSessionCompressor(strategy CompressStrategy) *SessionCompressor

NewSessionCompressor creates a new compressor with the given strategy.

func (*SessionCompressor) Compress added in v0.2.0

func (sc *SessionCompressor) Compress(messages []CompressMessage, budget int) (*CompressionResult, []CompressMessage, error)

Compress applies the configured strategy to reduce messages to fit within the token budget. It returns the compression result with statistics and the new compressed message list.

type SessionConvention added in v0.2.0

type SessionConvention struct {
	ID           string   `json:"id"`
	Rule         string   `json:"rule"`
	Examples     []string `json:"examples"`
	Source       string   `json:"source"`
	Confidence   float64  `json:"confidence"`
	AppliedCount int      `json:"applied_count"`
}

SessionConvention represents a project convention discovered during a session.

type SessionLifecycle

type SessionLifecycle struct {
	Memory      EvolvingMemoryInterface
	SkillStore  SkillStoreInterface
	CostTracker CostTrackerInterface
}

SessionLifecycle manages the start and end of agent sessions, implementing the self-improvement loop that makes hawk better over time.

Research basis: - Reflexion (NeurIPS 2023): 91% HumanEval via episodic memory of reflections - ExpeL (AAAI 2024): extract insights from task experiences - Voyager: 15.3x faster with accumulated skill library - DSPy (Stanford): 25-65% improvement via curated few-shot examples

The closed loop: SESSION START:

  1. Retrieve relevant EvolvingMemory guidelines
  2. Inject few-shot examples from prior successes
  3. Load yaad context (conventions, active tasks, stale warnings)

SESSION END:

  1. Generate LLM reflection ("what worked, what failed, why")
  2. Extract guidelines via EvolvingMemory.Learn()
  3. Distill successful approaches into skills
  4. Record cost/performance metrics
  5. Trigger yaad consolidation

func (*SessionLifecycle) OnSessionEnd

func (l *SessionLifecycle) OnSessionEnd(_ context.Context, session *Session, outcome SessionOutcome) error

OnSessionEnd performs post-session learning.

func (*SessionLifecycle) OnSessionStart

func (l *SessionLifecycle) OnSessionStart(_ context.Context, initialPrompt string) string

OnSessionStart prepares context for a new session. Returns context to inject into the system prompt.

type SessionMemoryConfig

type SessionMemoryConfig struct {
	MinTokens            int
	MinTextBlockMessages int
	MaxTokens            int
}

SessionMemoryConfig controls session memory compaction thresholds.

func DefaultSessionMemoryConfig

func DefaultSessionMemoryConfig() SessionMemoryConfig

DefaultSessionMemoryConfig returns defaults matching the archive.

type SessionMemoryStrategy

type SessionMemoryStrategy struct{}

SessionMemoryStrategy uses the session memory file as a compaction summary instead of making an LLM call.

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 []client.EyrieMessage, tokenCount, threshold int) bool

type SessionOutcome

type SessionOutcome struct {
	Success      bool
	TaskGoal     string
	FilesChanged []string
	ToolsUsed    []string
	TotalCost    float64
	Duration     time.Duration
	UserFeedback string // empty if none
}

SessionOutcome captures the results of a completed session.

type SessionReflection added in v0.2.0

type SessionReflection struct {
	WentWell   string
	WentBadly  string
	ToImprove  string
	Confidence int
	Lesson     string
}

SessionReflection holds the structured output of a reflection.

type SessionServices added in v0.2.0

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     *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 added in v0.2.0

func NewSessionServices(opts ...ServiceOption) *SessionServices

NewSessionServices creates a SessionServices with defaults and applies the given functional options.

type SessionSummary added in v0.2.0

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 ShadowWorkspace

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

ShadowWorkspace provides a temporary directory where file edits can be validated (e.g. via `go vet`, `tsc`, `pylint`) without touching the original source tree.

func NewShadowWorkspace

func NewShadowWorkspace() (*ShadowWorkspace, error)

NewShadowWorkspace creates a new temporary directory for shadow validation.

func (*ShadowWorkspace) Close

func (sw *ShadowWorkspace) Close()

Close removes the shadow workspace temp directory and all its contents.

func (*ShadowWorkspace) TempDir

func (sw *ShadowWorkspace) TempDir() string

TempDir returns the path to the shadow workspace temp directory.

func (*ShadowWorkspace) ValidateEdit

func (sw *ShadowWorkspace) ValidateEdit(originalPath, newContent string) []ValidationError

ValidateEdit copies a file into the shadow workspace, writes newContent to the copy, runs the language-appropriate validation tool, and returns any errors found. The temp copy is cleaned up before returning.

func (*ShadowWorkspace) ValidateMultipleEdits

func (sw *ShadowWorkspace) ValidateMultipleEdits(edits map[string]string) map[string][]ValidationError

ValidateMultipleEdits validates several files at once and returns a map of file path to validation errors.

type SignatureChange added in v0.2.0

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 added in v0.2.0

func CompareSignatures(oldSig, newSig string) *SignatureChange

CompareSignatures compares two function signature strings and returns the differences.

type SimilarIssue added in v0.2.0

type SimilarIssue struct {
	Issue         *Issue   `json:"issue"`
	Score         float64  `json:"score"`
	MatchingTerms []string `json:"matching_terms"`
}

SimilarIssue represents a search result with similarity scoring.

type SingleFileWatcher added in v0.2.0

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

SingleFileWatcher provides a simpler API for watching a single file.

func WatchSingle added in v0.2.0

func WatchSingle(path string, onChange func()) *SingleFileWatcher

WatchSingle creates a SingleFileWatcher for monitoring a single file.

func (*SingleFileWatcher) Start added in v0.2.0

func (sw *SingleFileWatcher) Start(ctx context.Context) error

Start begins polling the single file for changes. Blocks until ctx is cancelled or Stop is called.

func (*SingleFileWatcher) Stop added in v0.2.0

func (sw *SingleFileWatcher) Stop()

Stop signals the single file watcher to stop.

type Skill added in v0.2.0

type Skill struct {
	ID          string      `json:"id"`
	Name        string      `json:"name"`
	Description string      `json:"description"`
	Steps       []SkillStep `json:"steps"`
	Tags        []string    `json:"tags"`
	Language    string      `json:"language"`
	SuccessRate float64     `json:"success_rate"`
	UsageCount  int         `json:"usage_count"`
	CreatedAt   time.Time   `json:"created_at"`
	Author      string      `json:"author"` // "agent", "user", "community"
}

Skill represents a reusable agent skill — a learned task sequence that can be replayed.

type SkillDistillerAdapter

type SkillDistillerAdapter struct {
	SD *memory.SkillDistiller
}

SkillDistillerAdapter bridges memory.SkillDistiller to SkillStoreInterface. Skill distillation builds a prompt for LLM extraction — the actual distilled skills are stored as files in hawk-skills/.

func (*SkillDistillerAdapter) Distill

func (a *SkillDistillerAdapter) Distill(goal string, steps []string, outcome string) error

func (*SkillDistillerAdapter) Retrieve

func (a *SkillDistillerAdapter) Retrieve(_ string) []string

type SkillRegistry added in v0.2.0

type SkillRegistry struct {
	Skills map[string]*Skill `json:"skills"`
	Dir    string            `json:"dir"`
	// contains filtered or unexported fields
}

SkillRegistry manages a collection of reusable skills.

func NewSkillRegistry added in v0.2.0

func NewSkillRegistry(dir string) *SkillRegistry

NewSkillRegistry creates a new SkillRegistry backed by the given directory.

func (*SkillRegistry) Execute added in v0.2.0

func (r *SkillRegistry) Execute(ctx context.Context, skillID string, vars map[string]string, execFn func(string) (string, error)) (*SkillResult, error)

Execute runs a skill step-by-step, substituting variables and tracking results.

func (*SkillRegistry) Get added in v0.2.0

func (r *SkillRegistry) Get(id string) *Skill

Get retrieves a skill by ID.

func (*SkillRegistry) LearnFromSession added in v0.2.0

func (r *SkillRegistry) LearnFromSession(goal string, toolCalls []string, outcome string) *Skill

LearnFromSession extracts a reusable skill from a successful session.

func (*SkillRegistry) ListByTag added in v0.2.0

func (r *SkillRegistry) ListByTag(tag string) []*Skill

ListByTag returns all skills with the given tag.

func (*SkillRegistry) Load added in v0.2.0

func (r *SkillRegistry) Load() error

Load reads the registry from disk.

func (*SkillRegistry) Register added in v0.2.0

func (r *SkillRegistry) Register(skill *Skill) error

Register adds a skill to the registry.

func (*SkillRegistry) Remove added in v0.2.0

func (r *SkillRegistry) Remove(id string) error

Remove deletes a skill from the registry.

func (*SkillRegistry) Save added in v0.2.0

func (r *SkillRegistry) Save() error

Save persists the registry to disk as JSON.

func (*SkillRegistry) Search added in v0.2.0

func (r *SkillRegistry) Search(query string, tags []string) []*Skill

Search finds skills matching the query and/or tags, ranked by relevance and success rate.

func (*SkillRegistry) UpdateStats added in v0.2.0

func (r *SkillRegistry) UpdateStats(id string, success bool)

UpdateStats updates the success rate and usage count for a skill.

type SkillResult added in v0.2.0

type SkillResult struct {
	SkillID        string        `json:"skill_id"`
	Success        bool          `json:"success"`
	StepsCompleted int           `json:"steps_completed"`
	TotalSteps     int           `json:"total_steps"`
	Duration       time.Duration `json:"duration"`
	Outputs        []string      `json:"outputs"`
}

SkillResult captures the outcome of executing a skill.

type SkillStep added in v0.2.0

type SkillStep struct {
	Order           int    `json:"order"`
	Action          string `json:"action"` // "prompt", "tool_call", "check"
	Content         string `json:"content"`
	ToolName        string `json:"tool_name,omitempty"`
	ExpectedOutcome string `json:"expected_outcome,omitempty"`
	Fallback        string `json:"fallback,omitempty"`
}

SkillStep represents a single step in a skill sequence.

type SkillStoreInterface

type SkillStoreInterface interface {
	Distill(goal string, steps []string, outcome string) error
	Retrieve(query string) []string
}

SkillStoreInterface abstracts skill distillation and retrieval.

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 []client.EyrieMessage, tokenCount, threshold int) bool

type SmartRetry added in v0.2.0

type SmartRetry struct {
	Strategies     map[string]*RetryStrategy
	FailureHistory []FailureRecord
	MaxHistorySize int
	// contains filtered or unexported fields
}

SmartRetry provides intelligent retry handling that learns from failure patterns and adapts retry strategies per-provider.

func NewSmartRetry added in v0.2.0

func NewSmartRetry() *SmartRetry

NewSmartRetry creates a SmartRetry with default strategies per provider.

func (*SmartRetry) AdaptStrategy added in v0.2.0

func (sr *SmartRetry) AdaptStrategy(provider string)

AdaptStrategy learns from failure history and adjusts the strategy for a provider.

func (*SmartRetry) CalculateDelay added in v0.2.0

func (sr *SmartRetry) CalculateDelay(strategy *RetryStrategy, attempt int) time.Duration

CalculateDelay computes the delay for a given attempt using exponential backoff with jitter.

func (*SmartRetry) ClassifyError added in v0.2.0

func (sr *SmartRetry) ClassifyError(err error) string

ClassifyError categorizes an error into a known error type.

func (*SmartRetry) Decide added in v0.2.0

func (sr *SmartRetry) Decide(provider, model string, err error, attempt int) *RetryDecision

Decide evaluates whether a request should be retried based on the provider, error, and attempt count. It classifies the error, checks strategy, calculates delay with jitter, and may suggest fallback providers.

func (*SmartRetry) FormatStatus added in v0.2.0

func (sr *SmartRetry) FormatStatus() string

FormatStatus returns a human-readable summary of provider health.

func (*SmartRetry) GetProviderHealth added in v0.2.0

func (sr *SmartRetry) GetProviderHealth() map[string]string

GetProviderHealth returns the health status of all known providers.

func (*SmartRetry) RecordRecovery added in v0.2.0

func (sr *SmartRetry) RecordRecovery(provider, model string, recoveryDelay time.Duration)

RecordRecovery marks that a provider has recovered from failures.

func (*SmartRetry) ResetProvider added in v0.2.0

func (sr *SmartRetry) ResetProvider(provider string)

ResetProvider clears failure history for a specific provider.

func (*SmartRetry) ShouldFallback added in v0.2.0

func (sr *SmartRetry) ShouldFallback(provider string) (bool, string)

ShouldFallback checks if a provider has too many recent failures and suggests an alternative.

type SnapshotCache

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

SnapshotCache is a TTL-based cache for project snapshots.

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.

func (*SnapshotCache) GetOrCompute

func (sc *SnapshotCache) GetOrCompute(key string, fn func() (string, error)) (string, error)

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.

type SnapshotTracker

type SnapshotTracker interface {
	Track(message string) (string, error)
}

SnapshotTracker abstracts the snapshot system so engine doesn't import snapshot directly.

type SnowballDetector

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

SnowballDetector detects when token consumption is growing faster than progress, signalling that the agent is stuck in a snowball pattern where each turn consumes more tokens without proportional progress.

func NewSnowballDetector

func NewSnowballDetector(maxTokens int) *SnowballDetector

NewSnowballDetector creates a detector with the given absolute token ceiling. The default growth threshold is 2.0x (last 3 turns vs first 3 turns).

func (*SnowballDetector) IsSnowballing

func (sd *SnowballDetector) IsSnowballing() bool

IsSnowballing returns true if the last 3 turns consumed 2x+ tokens compared to the first 3 turns AND progress per token is declining.

func (*SnowballDetector) RecordTurn

func (sd *SnowballDetector) RecordTurn(tokens int, progress float64)

RecordTurn records token usage and estimated progress for a single turn. Progress should be in the range [0, 1].

func (*SnowballDetector) Reset

func (sd *SnowballDetector) Reset()

Reset clears all recorded data.

func (*SnowballDetector) ShouldAbort

func (sd *SnowballDetector) ShouldAbort() bool

ShouldAbort returns true if total tokens exceed maxTokens or the growth rate exceeds 3x between the first and last 3-turn windows.

func (*SnowballDetector) String

func (sd *SnowballDetector) String() string

String implements the Stringer interface for SnowballDetector.

func (*SnowballDetector) Summary

func (sd *SnowballDetector) Summary() string

Summary returns a human-readable summary of the snowball state.

type Solution added in v0.2.0

type Solution struct {
	ID            int
	Content       string
	Score         float64
	Duration      time.Duration
	TokensUsed    int
	Errors        []string
	FilesModified []string
}

Solution represents a single attempted solution with metadata.

type SolutionReviewer added in v0.2.0

type SolutionReviewer struct {
	MaxAttempts int
	ScoreFn     func(solution string) float64
	// contains filtered or unexported fields
}

SolutionReviewer implements a multi-attempt solution review pattern inspired by SWE-agent's reviewer: run the agent N times, score each solution, and select the best one. This improves reliability by sampling multiple approaches.

func NewSolutionReviewer added in v0.2.0

func NewSolutionReviewer(maxAttempts int) *SolutionReviewer

NewSolutionReviewer creates a SolutionReviewer with the given max attempts. If maxAttempts is <= 0, it defaults to 3.

func (*SolutionReviewer) ReviewAndSelect added in v0.2.0

func (sr *SolutionReviewer) ReviewAndSelect(ctx context.Context, task string, solveFn func(context.Context, string) (*Solution, error)) (*ReviewResult, error)

ReviewAndSelect runs solveFn up to MaxAttempts times, scores each solution, selects the best one, and calculates agreement across attempts.

func (*SolutionReviewer) ScoreSolution added in v0.2.0

func (sr *SolutionReviewer) ScoreSolution(solution *Solution) float64

ScoreSolution evaluates a solution using default scoring criteria:

  • Has code changes (+0.3)
  • No errors (+0.3)
  • Reasonable length (+0.2)
  • Files modified (+0.2)

type SourceRoot added in v0.2.0

type SourceRoot struct {
	Path       string
	ExploredAt time.Time
	FileCount  int
}

SourceRoot tracks a directory the agent has explored.

type SourceRoots added in v0.2.0

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

SourceRoots tracks which directories the agent has explored to avoid re-scanning.

func NewSourceRoots added in v0.2.0

func NewSourceRoots() *SourceRoots

NewSourceRoots creates a source root tracker.

func (*SourceRoots) Invalidate added in v0.2.0

func (sr *SourceRoots) Invalidate(path string)

Invalidate removes a root (e.g., after files changed).

func (*SourceRoots) IsExplored added in v0.2.0

func (sr *SourceRoots) IsExplored(path string) bool

IsExplored reports whether a directory has been explored.

func (*SourceRoots) List added in v0.2.0

func (sr *SourceRoots) List() []*SourceRoot

List returns all explored roots.

func (*SourceRoots) Mark added in v0.2.0

func (sr *SourceRoots) Mark(path string, fileCount int)

Mark records that a directory has been explored.

func (*SourceRoots) Stale added in v0.2.0

func (sr *SourceRoots) Stale(maxAge time.Duration) []*SourceRoot

Stale returns roots explored more than maxAge ago.

type SpawnDecision added in v0.2.0

type SpawnDecision struct {
	ShouldParallelize bool
	SubTasks          []SubTask
	Strategy          SpawnStrategy
}

SpawnDecision determines whether and how to parallelize a task.

type SpawnStrategy added in v0.2.0

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 added in v0.2.0

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.

func (*Spec) Format added in v0.2.0

func (s *Spec) Format() string

FormatSpec renders a spec for display.

type StagedChange added in v0.2.0

type StagedChange struct {
	File        string
	Original    string
	Modified    string
	Hunks       []StagedHunk
	Status      string // "staged", "applied", "rejected"
	StagedAt    time.Time
	Description string
}

StagedChange represents a file modification held in the staging area.

type StagedHunk added in v0.2.0

type StagedHunk struct {
	StartLine int
	EndLine   int
	OldLines  []string
	NewLines  []string
	Approved  bool
}

StagedHunk represents a contiguous block of changes within a staged file.

type StagingArea added in v0.2.0

type StagingArea struct {
	Staged map[string]*StagedChange
	// contains filtered or unexported fields
}

StagingArea provides a local staging area for agent edits, allowing review before changes are applied to disk — like a git staging area for the agent's modifications.

func NewStagingArea added in v0.2.0

func NewStagingArea() *StagingArea

NewStagingArea creates a new empty StagingArea.

func (*StagingArea) ApplyAll added in v0.2.0

func (sa *StagingArea) ApplyAll() ([]string, error)

ApplyAll writes all staged changes to disk and returns the list of files modified.

func (*StagingArea) ApplyFile added in v0.2.0

func (sa *StagingArea) ApplyFile(file string) error

ApplyFile applies a single file's staged changes to disk.

func (*StagingArea) ApproveHunk added in v0.2.0

func (sa *StagingArea) ApproveHunk(file string, hunkIndex int)

ApproveHunk marks a specific hunk as approved within a staged file.

func (*StagingArea) Clear added in v0.2.0

func (sa *StagingArea) Clear()

Clear discards all staged changes.

func (*StagingArea) FormatStaging added in v0.2.0

func (sa *StagingArea) FormatStaging() string

FormatStaging returns a human-readable summary of the staging area.

func (*StagingArea) GetDiff added in v0.2.0

func (sa *StagingArea) GetDiff(file string) string

GetDiff returns a unified diff for a staged file.

func (*StagingArea) GetStaged added in v0.2.0

func (sa *StagingArea) GetStaged() map[string]*StagedChange

GetStaged returns a copy of all staged changes.

func (*StagingArea) HasPending added in v0.2.0

func (sa *StagingArea) HasPending() bool

HasPending returns true if there are any changes in "staged" status.

func (*StagingArea) Reject added in v0.2.0

func (sa *StagingArea) Reject(file string)

Reject removes a file from staging without applying its changes.

func (*StagingArea) RejectHunk added in v0.2.0

func (sa *StagingArea) RejectHunk(file string, hunkIndex int)

RejectHunk rejects a specific hunk within a staged file (partial staging).

func (*StagingArea) Stage added in v0.2.0

func (sa *StagingArea) Stage(file, original, modified, description string)

Stage computes a diff between original and modified content and adds it to the staging area.

type StallDetector added in v0.2.0

type StallDetector struct {
	Window        []StallEntry
	WindowSize    int
	SoftThreshold int // repeats before a warning
	HardThreshold int // repeats before escalation
	// contains filtered or unexported fields
}

StallDetector monitors recent tool calls for repetition patterns that indicate the agent is stuck. Inspired by goose's repetition inspector and cline's loop detection.

func NewStallDetector added in v0.2.0

func NewStallDetector() *StallDetector

NewStallDetector creates a StallDetector with sensible defaults.

func (*StallDetector) BuildEscalation added in v0.2.0

func (sd *StallDetector) BuildEscalation(result *StallResult) string

BuildEscalation formats a human-readable escalation message from a StallResult.

func (*StallDetector) Check added in v0.2.0

func (sd *StallDetector) Check() *StallResult

Check analyzes the window for stall patterns and returns the result.

func (*StallDetector) DetectErrorLoop added in v0.2.0

func (sd *StallDetector) DetectErrorLoop() bool

DetectErrorLoop returns true if the same output hash appears 3+ times in the window.

func (*StallDetector) DetectOscillation added in v0.2.0

func (sd *StallDetector) DetectOscillation() bool

DetectOscillation returns true if the window shows an A→B→A→B pattern.

func (*StallDetector) DetectRepetition added in v0.2.0

func (sd *StallDetector) DetectRepetition() (int, string)

DetectRepetition finds the longest run of identical (tool+args) entries in the window. Returns the count and a human-readable pattern description.

func (*StallDetector) FormatWindow added in v0.2.0

func (sd *StallDetector) FormatWindow() string

FormatWindow returns a human-readable representation of the current window for debugging.

func (*StallDetector) Record added in v0.2.0

func (sd *StallDetector) Record(toolName string, args map[string]interface{}, output string)

Record adds a tool invocation to the sliding window.

func (*StallDetector) Reset added in v0.2.0

func (sd *StallDetector) Reset()

Reset clears the window after successful unstalling.

type StallEntry added in v0.2.0

type StallEntry struct {
	ToolName   string
	ArgsHash   string
	OutputHash string
	Timestamp  time.Time
}

StallEntry represents a single recorded tool invocation in the stall detection window.

type StallResult added in v0.2.0

type StallResult struct {
	IsStalled   bool
	Level       string // "none", "soft", "hard"
	RepeatCount int
	Pattern     string
	Suggestion  string
}

StallResult describes the outcome of a stall analysis.

type SteeringMessage added in v0.2.0

type SteeringMessage struct {
	Content  string // user guidance text
	Priority int    // 0 = normal, 1 = high (inject immediately)
}

SteeringMessage represents a user guidance message injected into the agent loop.

type SteeringQueue added in v0.2.0

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

SteeringQueue allows external callers (TUI, daemon) to inject messages into the agent loop between tool execution batches. This enables users to guide the agent without interrupting ongoing work.

func NewSteeringQueue added in v0.2.0

func NewSteeringQueue() *SteeringQueue

NewSteeringQueue creates a new SteeringQueue with an initialized notify channel.

func (*SteeringQueue) Clear added in v0.2.0

func (sq *SteeringQueue) Clear()

Clear discards all pending messages.

func (*SteeringQueue) Drain added in v0.2.0

func (sq *SteeringQueue) Drain() []SteeringMessage

Drain returns all pending steering messages and clears the queue. Called from agent loop goroutine between tool batches.

func (*SteeringQueue) Enqueue added in v0.2.0

func (sq *SteeringQueue) Enqueue(msg SteeringMessage)

Enqueue adds a steering message. Thread-safe — called from TUI goroutine.

func (*SteeringQueue) HasPending added in v0.2.0

func (sq *SteeringQueue) HasPending() bool

HasPending returns true if there are queued messages.

func (*SteeringQueue) Notify added in v0.2.0

func (sq *SteeringQueue) Notify() <-chan struct{}

Notify returns the channel that is signaled when a message is enqueued. Consumers can select on this to wake up when steering input arrives.

type StepResult added in v0.2.0

type StepResult struct {
	StepName string        `json:"step_name"`
	Status   string        `json:"status"` // "success", "failed", "skipped"
	Output   string        `json:"output"`
	Duration time.Duration `json:"duration"`
	Error    string        `json:"error"`
}

StepResult holds the result of a single step execution.

type StrategyRegistry

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

StrategyRegistry manages compaction strategies in priority order.

func NewStrategyRegistry

func NewStrategyRegistry(config CompactConfig) *StrategyRegistry

NewStrategyRegistry creates a registry with default strategies.

func (*StrategyRegistry) SelectStrategy

func (r *StrategyRegistry) SelectStrategy(msgs []client.EyrieMessage, tokenCount int) CompactStrategy

SelectStrategy picks the highest-priority strategy whose trigger fires.

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 added in v0.2.0

type StreamOptimizer struct {
	BufferSize         int
	MinFlushInterval   time.Duration
	DeduplicateRepeats bool
	ProgressiveRender  bool
	// contains filtered or unexported fields
}

StreamOptimizer buffers, deduplicates, and progressively renders LLM streaming output to improve perceived speed and terminal rendering quality.

func NewStreamOptimizer added in v0.2.0

func NewStreamOptimizer() *StreamOptimizer

NewStreamOptimizer creates a StreamOptimizer with sensible defaults.

func (*StreamOptimizer) DetectIncomplete added in v0.2.0

func (s *StreamOptimizer) DetectIncomplete(buffer string) (complete, remainder string)

DetectIncomplete splits the buffer at the last safe break point. Safe breaks are: newline, space, period, comma. If inside an unclosed code fence, no flush happens until the fence is closed.

func (*StreamOptimizer) DetectStutter added in v0.2.0

func (s *StreamOptimizer) DetectStutter(buffer string) string

DetectStutter removes repeated content from the buffer. If the last N chars repeat the previous N chars, the duplicate is removed.

func (*StreamOptimizer) OptimizeToolOutput added in v0.2.0

func (s *StreamOptimizer) OptimizeToolOutput(output string) string

OptimizeToolOutput optimizes non-streaming tool output for display. It collapses long paths and repeated similar lines.

func (*StreamOptimizer) Process added in v0.2.0

func (s *StreamOptimizer) Process(ch <-chan string) <-chan string

Process takes raw stream chunks and returns optimized chunks that are buffered, deduplicated, and split at safe boundaries.

func (*StreamOptimizer) ProgressIndicator added in v0.2.0

func (s *StreamOptimizer) ProgressIndicator(elapsed time.Duration, charsReceived int) string

ProgressIndicator returns a progress indicator string based on elapsed time and characters received.

func (*StreamOptimizer) Reset added in v0.2.0

func (s *StreamOptimizer) Reset()

Reset clears all state and statistics.

func (*StreamOptimizer) ShouldFlush added in v0.2.0

func (s *StreamOptimizer) ShouldFlush() bool

ShouldFlush reports whether the buffer should be flushed now.

func (*StreamOptimizer) Stats added in v0.2.0

func (s *StreamOptimizer) Stats() StreamStats

Stats returns statistics about the stream processing session.

func (*StreamOptimizer) WordWrap added in v0.2.0

func (s *StreamOptimizer) WordWrap(text string, width int) string

WordWrap wraps text at word boundaries for terminal display.

type StreamStats added in v0.2.0

type StreamStats struct {
	TotalChars        int
	FlushCount        int
	AvgFlushSize      int
	Duration          time.Duration
	CharsPerSecond    float64
	DeduplicatedChars int
	BufferedChars     int
}

StreamStats holds statistics about stream processing.

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 added in v0.2.0

type StructuredLogger struct {
	Level     LogLevel
	Output    io.Writer
	Format    string // "json" or "text"
	Fields    map[string]interface{}
	SessionID string
	// contains filtered or unexported fields
}

StructuredLogger provides context-rich structured logging.

func NewStructuredLogger added in v0.2.0

func NewStructuredLogger(level LogLevel, output io.Writer) *StructuredLogger

NewStructuredLogger creates a new StructuredLogger with the given level and output.

func (*StructuredLogger) Debug added in v0.2.0

func (l *StructuredLogger) Debug(msg string, fields ...map[string]interface{})

Debug logs a message at debug level.

func (*StructuredLogger) Error added in v0.2.0

func (l *StructuredLogger) Error(msg string, fields ...map[string]interface{})

Error logs a message at error level.

func (*StructuredLogger) Info added in v0.2.0

func (l *StructuredLogger) Info(msg string, fields ...map[string]interface{})

Info logs a message at info level.

func (*StructuredLogger) Warn added in v0.2.0

func (l *StructuredLogger) Warn(msg string, fields ...map[string]interface{})

Warn logs a message at warn level.

func (*StructuredLogger) WithFields added in v0.2.0

func (l *StructuredLogger) WithFields(fields map[string]interface{}) *StructuredLogger

WithFields returns a new logger with additional context fields merged in.

func (*StructuredLogger) WithSession added in v0.2.0

func (l *StructuredLogger) WithSession(sessionID string) *StructuredLogger

WithSession returns a new logger with the given session ID.

type SubAgentBudget added in v0.2.0

type SubAgentBudget struct {
	Mode      SubAgentMode
	TurnsUsed int
	MaxTurns  int
}

SubAgentBudget tracks turn usage against a mode-derived limit.

func NewSubAgentBudget added in v0.2.0

func NewSubAgentBudget(mode SubAgentMode, cfg SubAgentConfig) *SubAgentBudget

NewSubAgentBudget creates a budget tracker for the given mode and config.

func (*SubAgentBudget) Remaining added in v0.2.0

func (b *SubAgentBudget) Remaining() int

Remaining returns how many turns are left before synthesis is triggered.

func (*SubAgentBudget) ShouldSynthesize added in v0.2.0

func (b *SubAgentBudget) ShouldSynthesize() bool

ShouldSynthesize returns true when the sub-agent has exceeded its turn budget and should produce a final synthesis response instead of continuing tool use.

func (*SubAgentBudget) Tick added in v0.2.0

func (b *SubAgentBudget) Tick()

Tick increments the turn counter by one.

type SubAgentConfig added in v0.2.0

type SubAgentConfig struct {
	ExploreMaxTurns int // turn budget for explore-mode sub-agents
	GeneralMaxTurns int // turn budget for general-mode sub-agents
	MaxDepth        int // maximum nesting depth (1 = sub-agents cannot spawn children)
}

SubAgentConfig holds configuration for sub-agent budget and depth limits. Zero-value int fields receive defaults via DefaultSubAgentConfig().

func DefaultSubAgentConfig added in v0.2.0

func DefaultSubAgentConfig() SubAgentConfig

DefaultSubAgentConfig returns a SubAgentConfig with sane production defaults.

type SubAgentMode

type SubAgentMode string

SubAgentMode determines the capabilities and cost profile of a sub-agent.

const (
	SubAgentExplore SubAgentMode = "explore"
	SubAgentGeneral SubAgentMode = "general"
)

type SubTask added in v0.2.0

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 Subtask

type Subtask struct {
	ID          int
	Title       string
	Description string
	Files       []string
	Status      string // "pending", "in_progress", "done", "skipped"
}

Subtask represents a single unit of work within a plan.

func ParseSubtasks

func ParseSubtasks(output string) []Subtask

ParseSubtasks parses LLM output formatted as numbered subtasks. Expected format:

  1. Title here Description of what to do Files: path/to/file.go, another/file.go

type SuggestedTask added in v0.2.0

type SuggestedTask struct {
	ID          string
	Title       string
	Description string
	Priority    int    // 1=highest (critical), 5=lowest (nice-to-have)
	Category    string // "fix", "improve", "test", "docs", "cleanup", "security"
	Source      string // "git", "lint", "test", "todo", "pr"
	Actionable  bool
	Command     string // suggested hawk command to run
}

SuggestedTask represents a proactive task suggestion based on repository state.

func ScanGitTasks added in v0.2.0

func ScanGitTasks(projectDir string) []*SuggestedTask

ScanGitTasks scans the git repository for actionable git-related tasks.

func ScanTODOs added in v0.2.0

func ScanTODOs(projectDir string) []*SuggestedTask

ScanTODOs walks source files looking for TODO, FIXME, and HACK comments.

func ScanTestFailures added in v0.2.0

func ScanTestFailures(projectDir string) []*SuggestedTask

ScanTestFailures runs a quick test check and generates tasks for failures.

type SuggestionEngine added in v0.2.0

type SuggestionEngine struct {
	Rules   []SuggestionRule
	History []string
	Context map[string]string
	// contains filtered or unexported fields
}

SuggestionEngine evaluates rules against the current context to produce proactive command suggestions.

func NewSuggestionEngine added in v0.2.0

func NewSuggestionEngine() *SuggestionEngine

NewSuggestionEngine creates a SuggestionEngine with built-in rules.

func (*SuggestionEngine) AddRule added in v0.2.0

func (se *SuggestionEngine) AddRule(rule SuggestionRule)

AddRule adds a custom rule to the engine.

func (*SuggestionEngine) Dismiss added in v0.2.0

func (se *SuggestionEngine) Dismiss(command string)

Dismiss marks a command as dismissed so it won't be suggested again soon. The dismissal expires after 10 minutes.

func (*SuggestionEngine) GetTopSuggestion added in v0.2.0

func (se *SuggestionEngine) GetTopSuggestion() *CommandSuggestion

GetTopSuggestion returns the single best suggestion based on the engine's current internal context, or nil if no rules match.

func (*SuggestionEngine) RecordCommand added in v0.2.0

func (se *SuggestionEngine) RecordCommand(cmd string)

RecordCommand records a command in the engine's history for context tracking.

func (*SuggestionEngine) Suggest added in v0.2.0

func (se *SuggestionEngine) Suggest(ctx map[string]string) []*CommandSuggestion

Suggest evaluates all rules against the current context and returns top suggestions sorted by confidence (highest first).

func (*SuggestionEngine) UpdateContext added in v0.2.0

func (se *SuggestionEngine) UpdateContext(key, value string)

UpdateContext updates a key-value pair in the engine's internal context state.

type SuggestionRule added in v0.2.0

type SuggestionRule struct {
	Name      string
	Condition func(ctx map[string]string) bool
	Suggest   func(ctx map[string]string) *CommandSuggestion
	Priority  int
}

SuggestionRule defines a conditional rule that produces a suggestion.

type SumMessage added in v0.2.0

type SumMessage struct {
	Role     string
	Content  string
	ToolName string
	IsError  bool
}

SumMessage represents a single message in the conversation for summarization.

type Summary added in v0.2.0

type Summary struct {
	Level          string
	Content        string
	Topics         []string
	Decisions      []string
	FilesDiscussed []string
	ToolsUsed      map[string]int
	TokensSaved    int
}

Summary holds a structured summary of a conversation at the requested level.

type SummaryLevel added in v0.2.0

type SummaryLevel string

SummaryLevel defines the granularity of a conversation summary.

const (
	// SummaryOneLine produces a single concise sentence.
	SummaryOneLine SummaryLevel = "one_line"
	// SummaryParagraph produces a 3-5 sentence overview.
	SummaryParagraph SummaryLevel = "paragraph"
	// SummaryDetailed produces a full multi-section summary.
	SummaryDetailed SummaryLevel = "detailed"
	// SummaryStructured populates all fields of a Summary struct.
	SummaryStructured SummaryLevel = "structured"
)

type SystemPromptBuilder added in v0.2.0

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 added in v0.2.0

func NewSystemPromptBuilder(basePrompt string, maxTokens int) *SystemPromptBuilder

NewSystemPromptBuilder creates a SystemPromptBuilder with a base prompt and token limit.

func (*SystemPromptBuilder) AdaptForModel added in v0.2.0

func (b *SystemPromptBuilder) AdaptForModel(model string) *SystemPromptBuilder

AdaptForModel adjusts verbosity and section limits based on the target model.

func (*SystemPromptBuilder) AdaptForTask added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

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 added in v0.2.0

func (b *SystemPromptBuilder) RemoveSection(name string)

RemoveSection removes a section by name.

type Task added in v0.2.0

type Task struct {
	ID              string
	Description     string
	Type            string // "read", "analyze", "plan", "implement", "test", "review"
	Dependencies    []string
	EstimatedTokens int
	Priority        int
	Status          string // "pending", "running", "done", "failed"
	Result          string
}

Task represents a single unit of work within a decomposed plan.

type TaskContext added in v0.2.0

type TaskContext struct {
	Goal          string
	ToolCalls     int
	Errors        int
	Retries       int
	FilesModified int
	TestsPassed   bool
	Duration      time.Duration
	TokensUsed    int
	UserFeedback  string
}

TaskContext captures all relevant metrics from a completed task for assessment.

type TaskDecomposer added in v0.2.0

type TaskDecomposer struct {
	MaxTasks int
	// contains filtered or unexported fields
}

TaskDecomposer breaks complex goals into ordered sub-tasks.

func NewTaskDecomposer added in v0.2.0

func NewTaskDecomposer() *TaskDecomposer

NewTaskDecomposer creates a TaskDecomposer with default settings.

func (*TaskDecomposer) DebuggingPlan added in v0.2.0

func (td *TaskDecomposer) DebuggingPlan(goal string) []Task

DebuggingPlan returns the task sequence for fixing a bug.

func (*TaskDecomposer) Decompose added in v0.2.0

func (td *TaskDecomposer) Decompose(goal string) *TaskPlan

Decompose analyzes a goal and returns a structured TaskPlan.

func (*TaskDecomposer) DetectPattern added in v0.2.0

func (td *TaskDecomposer) DetectPattern(goal string) string

DetectPattern determines the type of work from goal keywords.

func (*TaskDecomposer) EstimateComplexity added in v0.2.0

func (td *TaskDecomposer) EstimateComplexity(goal string) int

EstimateComplexity scores a goal's complexity based on word count and keyword multipliers.

func (*TaskDecomposer) FindParallelGroups added in v0.2.0

func (td *TaskDecomposer) FindParallelGroups(tasks []Task) [][]string

FindParallelGroups groups tasks by dependency level so independent tasks can run concurrently within the same group.

func (*TaskDecomposer) FormatPlan added in v0.2.0

func (td *TaskDecomposer) FormatPlan(plan *TaskPlan) string

FormatPlan returns a human-readable display of the task plan.

func (*TaskDecomposer) ImplementationPlan added in v0.2.0

func (td *TaskDecomposer) ImplementationPlan(goal string) []Task

ImplementationPlan returns the task sequence for implementing a feature.

func (*TaskDecomposer) RefactoringPlan added in v0.2.0

func (td *TaskDecomposer) RefactoringPlan(goal string) []Task

RefactoringPlan returns the task sequence for refactoring code.

func (*TaskDecomposer) TestingPlan added in v0.2.0

func (td *TaskDecomposer) TestingPlan(goal string) []Task

TestingPlan returns the task sequence for adding tests.

type TaskPlan added in v0.2.0

type TaskPlan struct {
	Goal           string
	Tasks          []Task
	EstimatedTotal int
	Parallel       [][]string // groups of task IDs that can run concurrently
}

TaskPlan holds a full decomposition of a goal into ordered tasks.

type TaskQueue added in v0.2.0

type TaskQueue struct {
	Tasks     []*SuggestedTask
	Dismissed []string
	// contains filtered or unexported fields
}

TaskQueue manages a queue of suggested tasks with dismissal tracking.

func NewTaskQueue added in v0.2.0

func NewTaskQueue() *TaskQueue

NewTaskQueue creates a new empty TaskQueue.

func (*TaskQueue) Dismiss added in v0.2.0

func (tq *TaskQueue) Dismiss(taskID string)

Dismiss marks a task as dismissed so it won't appear in future GetTop calls.

func (*TaskQueue) GetTop added in v0.2.0

func (tq *TaskQueue) GetTop(n int) []*SuggestedTask

GetTop returns the top N suggested tasks by priority, excluding dismissed ones.

func (*TaskQueue) Refresh added in v0.2.0

func (tq *TaskQueue) Refresh(projectDir string) error

Refresh rescans the project directory and updates the task queue.

func (*TaskQueue) Scan added in v0.2.0

func (tq *TaskQueue) Scan(projectDir string) ([]*SuggestedTask, error)

Scan scans the project directory for actionable items from multiple sources.

type TaskScale added in v0.2.0

type TaskScale int

TaskScale represents the complexity/scope of a user request.

const (
	ScalePatch TaskScale = iota // typo, one-liner, rename
	ScaleMinor                  // add error handling, small feature
	ScaleMajor                  // refactor module, multi-file change
	ScaleEpic                   // new system, architecture change
)

func ClassifyScale added in v0.2.0

func ClassifyScale(prompt string) TaskScale

ClassifyScale determines the task scale from user input.

func (TaskScale) String added in v0.2.0

func (s TaskScale) String() string

type TeachConfig

type TeachConfig struct {
	Enabled bool
	Depth   int // 1=what, 2=why, 3=how (default: 2)
}

TeachConfig controls explanation depth.

type Template added in v0.2.0

type Template struct {
	Name        string             `json:"name"`
	Description string             `json:"description"`
	Language    string             `json:"language"`
	Framework   string             `json:"framework"`
	Files       []TemplateFile     `json:"files"`
	Variables   []TemplateVariable `json:"variables"`
	PostCreate  []string           `json:"post_create"`
}

Template defines a project template for scaffolding.

type TemplateFile added in v0.2.0

type TemplateFile struct {
	Path      string      `json:"path"`
	Content   string      `json:"content"`
	Mode      os.FileMode `json:"mode"`
	Condition string      `json:"condition"`
}

TemplateFile defines a single file within a template.

type TemplateVariable added in v0.2.0

type TemplateVariable struct {
	Name        string   `json:"name"`
	Description string   `json:"description"`
	Default     string   `json:"default"`
	Required    bool     `json:"required"`
	Type        string   `json:"type"` // "string", "bool", "choice"
	Choices     []string `json:"choices,omitempty"`
}

TemplateVariable defines a variable used in template rendering.

type TestLoop added in v0.2.0

type TestLoop struct {
	// Enabled controls whether the test loop is active.
	Enabled bool

	// MaxRetries is the maximum number of test-fix retries per file.
	// Default is 3.
	MaxRetries int

	// Commands maps project type identifiers to test commands.
	// Auto-detected from project files if not explicitly set.
	Commands map[string]string

	// Timeout is the maximum duration allowed for a test run.
	// Default is 120s.
	Timeout time.Duration
	// contains filtered or unexported fields
}

TestLoop implements an auto-test loop similar to Aider's auto_test feature. After edits, it automatically runs the project's test suite and feeds failures back to the agent for self-correction.

func NewTestLoop added in v0.2.0

func NewTestLoop() *TestLoop

NewTestLoop creates a TestLoop with sensible defaults.

func (*TestLoop) RecordRetry added in v0.2.0

func (tl *TestLoop) RecordRetry(file string)

RecordRetry increments the retry counter for a file. Thread-safe.

func (*TestLoop) ResetFile added in v0.2.0

func (tl *TestLoop) ResetFile(file string)

ResetFile clears the retry count for a specific file.

func (*TestLoop) RetryCount added in v0.2.0

func (tl *TestLoop) RetryCount(file string) int

RetryCount returns the current retry count for a file. Thread-safe.

func (*TestLoop) RunTests added in v0.2.0

func (tl *TestLoop) RunTests(ctx context.Context, projectDir string) (*TestResult, error)

RunTests executes the detected or configured test command for the given project directory and returns a structured TestResult.

func (*TestLoop) ShouldRetry added in v0.2.0

func (tl *TestLoop) ShouldRetry(file string) bool

ShouldRetry returns true if the number of retries for the given file has not yet reached MaxRetries.

type TestResult added in v0.2.0

type TestResult struct {
	// Passed indicates whether all tests passed.
	Passed bool

	// Output is the combined stdout+stderr from the test command.
	Output string

	// FailedTests is a list of individual test names that failed.
	FailedTests []string

	// Duration is how long the test run took.
	Duration time.Duration

	// ExitCode is the process exit code (0 = pass).
	ExitCode int
}

TestResult holds the structured output from a test run.

type TestSelector added in v0.2.0

type TestSelector struct {
	ProjectDir string
	Language   string
	DepGraph   map[string][]string
	// contains filtered or unexported fields
}

TestSelector provides diff-aware test selection, identifying which tests need to run based on changed files and dependency relationships.

func NewTestSelector added in v0.2.0

func NewTestSelector(projectDir string) *TestSelector

NewTestSelector creates a TestSelector for the given project directory. It auto-detects the project language and builds a dependency graph.

func (*TestSelector) FindRelatedTests added in v0.2.0

func (ts *TestSelector) FindRelatedTests(file string) []string

FindRelatedTests finds test files related to the given source file.

func (*TestSelector) SelectFromDiff added in v0.2.0

func (ts *TestSelector) SelectFromDiff(diff string) (*SelectedTests, error)

SelectFromDiff parses a unified diff string, extracts changed file paths, and selects the related tests.

func (*TestSelector) SelectFromFiles added in v0.2.0

func (ts *TestSelector) SelectFromFiles(changedFiles []string) (*SelectedTests, error)

SelectFromFiles determines which tests to run given a list of changed files. Strategy depends on the detected language.

type ThinkingPhase added in v0.2.0

type ThinkingPhase string

ThinkingPhase represents a phase in the agent's reasoning process.

const (
	PhaseUnderstand ThinkingPhase = "understand"
	PhasePlan       ThinkingPhase = "plan"
	PhaseExecute    ThinkingPhase = "execute"
	PhaseVerify     ThinkingPhase = "verify"
	PhaseReflect    ThinkingPhase = "reflect"
)

type ThinkingProtocol added in v0.2.0

type ThinkingProtocol struct {
	Enabled      bool
	Visible      bool
	Steps        []ThinkingStep
	CurrentPhase ThinkingPhase
	// contains filtered or unexported fields
}

ThinkingProtocol structures the agent's reasoning process, making it explicit when the agent is planning vs executing.

func NewThinkingProtocol added in v0.2.0

func NewThinkingProtocol() *ThinkingProtocol

NewThinkingProtocol creates a new ThinkingProtocol with defaults.

func (*ThinkingProtocol) AddAlternative added in v0.2.0

func (tp *ThinkingProtocol) AddAlternative(thought, alternative string)

AddAlternative records an alternative approach considered for a thought.

func (*ThinkingProtocol) AddThought added in v0.2.0

func (tp *ThinkingProtocol) AddThought(content string, confidence float64)

AddThought records a thinking step in the current phase.

func (*ThinkingProtocol) BuildThinkingPrompt added in v0.2.0

func (tp *ThinkingProtocol) BuildThinkingPrompt(task string) string

BuildThinkingPrompt generates a structured thinking prompt for a task.

func (*ThinkingProtocol) FormatThinking added in v0.2.0

func (tp *ThinkingProtocol) FormatThinking(steps []ThinkingStep) string

FormatThinking formats thinking steps for display to the user.

func (*ThinkingProtocol) GetPhaseHistory added in v0.2.0

func (tp *ThinkingProtocol) GetPhaseHistory() map[ThinkingPhase][]ThinkingStep

GetPhaseHistory returns all thinking steps grouped by phase.

func (*ThinkingProtocol) ParseThinking added in v0.2.0

func (tp *ThinkingProtocol) ParseThinking(response string) []ThinkingStep

ParseThinking extracts thinking steps from an LLM response. It looks for phase markers like "Understanding:", "Plan:", "Risks:", etc. It also handles <thinking> tags if the model supports them.

func (*ThinkingProtocol) ResetForNewTask added in v0.2.0

func (tp *ThinkingProtocol) ResetForNewTask()

ResetForNewTask clears all thinking state for a new task.

func (*ThinkingProtocol) ShouldThinkFirst added in v0.2.0

func (tp *ThinkingProtocol) ShouldThinkFirst(task string) bool

ShouldThinkFirst applies heuristics to determine if a task needs structured thinking before execution.

func (*ThinkingProtocol) StartPhase added in v0.2.0

func (tp *ThinkingProtocol) StartPhase(phase ThinkingPhase)

StartPhase transitions to a new thinking phase.

func (*ThinkingProtocol) SummarizeThinking added in v0.2.0

func (tp *ThinkingProtocol) SummarizeThinking() string

SummarizeThinking provides a one-line summary of the thinking process.

type ThinkingStep added in v0.2.0

type ThinkingStep struct {
	Phase        ThinkingPhase
	Content      string
	Confidence   float64
	Alternatives []string
	Duration     time.Duration
	Timestamp    time.Time
}

ThinkingStep represents a single step in the thinking process.

type Timeline added in v0.2.0

type Timeline struct {
	Events    []TimelineEvent `json:"events"`
	SessionID string          `json:"session_id"`
	StartTime time.Time       `json:"start_time"`
	// contains filtered or unexported fields
}

Timeline tracks a chronological sequence of events during a session.

func NewTimeline added in v0.2.0

func NewTimeline(sessionID string) *Timeline

NewTimeline creates a new Timeline for the given session ID.

func (*Timeline) AddAction added in v0.2.0

func (t *Timeline) AddAction(tool, target string, duration time.Duration)

AddAction records a tool action with its target and duration.

func (*Timeline) AddDecision added in v0.2.0

func (t *Timeline) AddDecision(decision, reason string)

AddDecision records a decision with its reasoning.

func (*Timeline) AddError added in v0.2.0

func (t *Timeline) AddError(err string)

AddError records an error that occurred during the session.

func (*Timeline) AddEvent added in v0.2.0

func (t *Timeline) AddEvent(eventType, content string, metadata map[string]string)

AddEvent records a generic event with the given type, content, and metadata.

func (*Timeline) AddFileChange added in v0.2.0

func (t *Timeline) AddFileChange(path, action string)

AddFileChange records a file system change (create, modify, or delete).

func (*Timeline) AddMilestone added in v0.2.0

func (t *Timeline) AddMilestone(description string)

AddMilestone records a significant milestone in the session.

func (*Timeline) Duration added in v0.2.0

func (t *Timeline) Duration() time.Duration

Duration returns the total elapsed time since the timeline started.

func (*Timeline) GetBetween added in v0.2.0

func (t *Timeline) GetBetween(start, end time.Time) []TimelineEvent

GetBetween returns all events between start and end times (inclusive).

func (*Timeline) GetByType added in v0.2.0

func (t *Timeline) GetByType(eventType string) []TimelineEvent

GetByType returns all events matching the given type.

func (*Timeline) GetMilestones added in v0.2.0

func (t *Timeline) GetMilestones() []TimelineEvent

GetMilestones returns all milestone events.

func (*Timeline) RenderTimeline added in v0.2.0

func (t *Timeline) RenderTimeline(maxWidth int) string

RenderTimeline produces a human-readable chronological view of the session.

func (*Timeline) Summarize added in v0.2.0

func (t *Timeline) Summarize() string

Summarize returns a one-paragraph summary of the session.

type TimelineEvent added in v0.2.0

type TimelineEvent struct {
	ID        string            `json:"id"`
	Timestamp time.Time         `json:"timestamp"`
	Type      string            `json:"type"` // "action", "decision", "milestone", "error", "user_input", "file_change"
	Content   string            `json:"content"`
	Duration  time.Duration     `json:"duration,omitempty"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

TimelineEvent represents a single event in a session timeline.

type TimeoutConfig

type TimeoutConfig struct {
	Total     time.Duration // total time for the entire operation
	PerTurn   time.Duration // max time per LLM turn (default: 60s)
	PerTool   time.Duration // max time per tool execution (default: 120s)
	Countdown bool          // show remaining time in output
}

TimeoutConfig controls operation time budgets.

func DefaultTimeoutConfig

func DefaultTimeoutConfig() TimeoutConfig

DefaultTimeoutConfig returns a TimeoutConfig with sensible per-turn and per-tool defaults. Total is left at zero (no overall deadline) so the caller can set it.

type Timer added in v0.2.0

type Timer struct {
	Name    string
	Samples []time.Duration
	// contains filtered or unexported fields
}

Timer tracks duration samples for a named operation.

type TokenEntry added in v0.2.0

type TokenEntry struct {
	Timestamp    time.Time
	InputTokens  int
	OutputTokens int
	Model        string
	ToolName     string
	CostUSD      float64
	Cumulative   int
}

TokenEntry records a single token usage event.

type TokenPredictor added in v0.2.0

type TokenPredictor struct {
	History      []PredictionRecord
	ModelFactors map[string]float64
	// contains filtered or unexported fields
}

TokenPredictor estimates how many tokens a task will consume before execution. It maintains a history of predictions vs actuals to calibrate future estimates.

func NewTokenPredictor added in v0.2.0

func NewTokenPredictor() *TokenPredictor

NewTokenPredictor creates a TokenPredictor with default model factors.

func (*TokenPredictor) Calibrate added in v0.2.0

func (tp *TokenPredictor) Calibrate()

Calibrate adjusts ModelFactors based on prediction accuracy history. If predictions consistently under-predict for a model, increase its factor. If predictions consistently over-predict, decrease its factor.

func (*TokenPredictor) EstimateCost added in v0.2.0

func (tp *TokenPredictor) EstimateCost(tokens int, model string) float64

EstimateCost calculates the USD cost for a given token count and model. It splits tokens roughly 60/40 input/output for a blended rate.

func (*TokenPredictor) GetAccuracy added in v0.2.0

func (tp *TokenPredictor) GetAccuracy(model string) float64

GetAccuracy returns the mean absolute percentage error (MAPE) for predictions of the given model. Lower is better. Returns 0 if no history exists.

func (*TokenPredictor) Predict added in v0.2.0

func (tp *TokenPredictor) Predict(task string, contextSize int, model string) *Prediction

Predict estimates token usage for a task given its description, context size, and model.

func (*TokenPredictor) RecordActual added in v0.2.0

func (tp *TokenPredictor) RecordActual(taskType string, predicted, actual int, model string)

RecordActual records the actual token usage after task completion for calibration.

type TokenReporter added in v0.2.0

type TokenReporter struct {
	Entries       []TokenEntry
	SessionBudget int
	SessionSpent  int
	Alerts        []BudgetAlert
	// contains filtered or unexported fields
}

TokenReporter provides real-time visibility into token spending and projections throughout a session.

func NewTokenReporter added in v0.2.0

func NewTokenReporter(sessionBudget int) *TokenReporter

NewTokenReporter creates a TokenReporter with the given session budget.

func (*TokenReporter) CheckBudget added in v0.2.0

func (tr *TokenReporter) CheckBudget() *BudgetAlert

CheckBudget evaluates current spending against the session budget and returns an alert if a threshold has been newly crossed.

func (*TokenReporter) FormatAlert added in v0.2.0

func (tr *TokenReporter) FormatAlert(alert *BudgetAlert) string

FormatAlert returns a formatted string representation of a BudgetAlert.

func (*TokenReporter) GetHistory added in v0.2.0

func (tr *TokenReporter) GetHistory(last int) []TokenEntry

GetHistory returns the last n token entries. If last exceeds the number of entries, all entries are returned.

func (*TokenReporter) GetRemaining added in v0.2.0

func (tr *TokenReporter) GetRemaining() int

GetRemaining returns the number of tokens remaining in the session budget.

func (*TokenReporter) GetUsageRate added in v0.2.0

func (tr *TokenReporter) GetUsageRate() float64

GetUsageRate returns the token usage rate in tokens per minute over the session duration.

func (*TokenReporter) ProjectCompletion added in v0.2.0

func (tr *TokenReporter) ProjectCompletion() time.Duration

ProjectCompletion estimates the remaining time until the budget is exhausted at the current usage rate.

func (*TokenReporter) Record added in v0.2.0

func (tr *TokenReporter) Record(input, output int, model, tool string, cost float64)

Record logs a token usage event, updates cumulative totals, and checks budget thresholds.

func (*TokenReporter) RenderBreakdown added in v0.2.0

func (tr *TokenReporter) RenderBreakdown() string

RenderBreakdown returns a detailed breakdown of token usage by input/output, model, and tool.

func (*TokenReporter) RenderLive added in v0.2.0

func (tr *TokenReporter) RenderLive() string

RenderLive returns a compact single-block status display showing current token usage, rate, ETA, and last tool usage.

func (*TokenReporter) Reset added in v0.2.0

func (tr *TokenReporter) Reset()

Reset clears all recorded entries, spent tokens, and alerts, keeping the session budget intact.

type ToolConfirmationRouter added in v0.2.0

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 solo devs who want fast iteration without constant y/n prompts for safe operations.

func NewToolConfirmationRouter added in v0.2.0

func NewToolConfirmationRouter() *ToolConfirmationRouter

NewToolConfirmationRouter creates a router with sensible defaults for coding.

func (*ToolConfirmationRouter) Classify added in v0.2.0

func (r *ToolConfirmationRouter) Classify(toolName string, args map[string]interface{}) ToolRisk

Classify determines the risk level of a tool call.

func (*ToolConfirmationRouter) NeedsConfirmation added in v0.2.0

func (r *ToolConfirmationRouter) NeedsConfirmation(toolName string, args map[string]interface{}) bool

NeedsConfirmation returns true if the tool call should prompt the user.

type ToolInfo added in v0.2.0

type ToolInfo struct {
	Name     string
	Category string // "file", "search", "exec", "web", "agent", "system"
	Cost     string // "free", "cheap", "expensive"
	ReadOnly bool
}

ToolInfo describes a single tool available to the LLM.

type ToolInspector added in v0.2.0

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 added in v0.2.0

func NewToolInspector() *ToolInspector

NewToolInspector creates an inspector backed by the confirmation router.

func (*ToolInspector) Inspect added in v0.2.0

func (ti *ToolInspector) Inspect(toolName string, args map[string]interface{}) InspectionResult

Inspect analyzes a tool call and returns a decision with confidence.

type ToolRisk added in v0.2.0

type ToolRisk int

ToolRisk classifies the risk level of a tool invocation.

const (
	RiskNone   ToolRisk = iota // auto-approve silently
	RiskLow                    // auto-approve with notification
	RiskMedium                 // ask user (default for unknown)
	RiskHigh                   // always ask, show warning
)

type ToolSelection added in v0.2.0

type ToolSelection struct {
	Recommended []string
	Excluded    []string
	Reason      string
	Confidence  float64
}

ToolSelection holds the result of selecting tools for a task.

type ToolSelector added in v0.2.0

type ToolSelector struct {
	AllTools     []ToolInfo
	UsageHistory map[string]int
	TaskPatterns map[string][]string
	// contains filtered or unexported fields
}

ToolSelector recommends which tools to send to the LLM based on the task.

func NewToolSelector added in v0.2.0

func NewToolSelector(tools []ToolInfo) *ToolSelector

NewToolSelector creates a ToolSelector with the given tools.

func (*ToolSelector) Adapt added in v0.2.0

func (ts *ToolSelector) Adapt(feedback string)

Adapt processes feedback to adjust tool patterns for future selections. Feedback format example: "needed WebSearch but it wasn't available"

func (*ToolSelector) FilterExpensive added in v0.2.0

func (ts *ToolSelector) FilterExpensive(tools []string) []string

FilterExpensive removes tools marked as "expensive" from the provided list.

func (*ToolSelector) GetRecommendedForIntent added in v0.2.0

func (ts *ToolSelector) GetRecommendedForIntent(intent string) []string

GetRecommendedForIntent returns the tools mapped to a given intent category.

func (*ToolSelector) RecordUsage added in v0.2.0

func (ts *ToolSelector) RecordUsage(tool string, task string)

RecordUsage tracks which tools are used for which tasks.

func (*ToolSelector) Select added in v0.2.0

func (ts *ToolSelector) Select(task string, maxTools int) *ToolSelection

Select analyzes the task and returns a ToolSelection with at most maxTools recommended.

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 added in v0.2.0

type TrajectoryEvent struct {
	Index     int               `json:"index"`
	Type      string            `json:"type"` // "thought", "action", "observation", "error", "decision"
	Content   string            `json:"content"`
	ToolName  string            `json:"tool_name,omitempty"`
	Duration  time.Duration     `json:"duration"`
	Tokens    int               `json:"tokens"`
	Timestamp time.Time         `json:"timestamp"`
	Metadata  map[string]string `json:"metadata,omitempty"`
}

TrajectoryEvent represents a single event in an agent's trajectory.

type TrajectoryInspector added in v0.2.0

type TrajectoryInspector struct {
	Events    []TrajectoryEvent `json:"events"`
	SessionID string            `json:"session_id"`
	StartTime time.Time         `json:"start_time"`
	// contains filtered or unexported fields
}

TrajectoryInspector records and visualizes agent action sequences for debugging and analysis. Inspired by SWE-agent's trajectory inspector.

func NewTrajectoryInspector added in v0.2.0

func NewTrajectoryInspector(sessionID string) *TrajectoryInspector

NewTrajectoryInspector creates a new inspector for the given session.

func (*TrajectoryInspector) ExportJSON added in v0.2.0

func (ti *TrajectoryInspector) ExportJSON() (string, error)

ExportJSON serializes the trajectory inspector state to JSON.

func (*TrajectoryInspector) FindPatterns added in v0.2.0

func (ti *TrajectoryInspector) FindPatterns() []string

FindPatterns analyzes the trajectory for common patterns and returns descriptions.

func (*TrajectoryInspector) GetByType added in v0.2.0

func (ti *TrajectoryInspector) GetByType(eventType string) []TrajectoryEvent

GetByType returns all events matching the given type.

func (*TrajectoryInspector) GetToolUsage added in v0.2.0

func (ti *TrajectoryInspector) GetToolUsage() map[string]int

GetToolUsage returns a map of tool names to their usage counts.

func (*TrajectoryInspector) Record added in v0.2.0

func (ti *TrajectoryInspector) Record(eventType, content string, toolName string, duration time.Duration, tokens int)

Record adds a new event to the trajectory.

func (*TrajectoryInspector) RenderStats added in v0.2.0

func (ti *TrajectoryInspector) RenderStats() string

RenderStats returns a formatted summary of trajectory statistics.

func (*TrajectoryInspector) RenderTimeline added in v0.2.0

func (ti *TrajectoryInspector) RenderTimeline() string

RenderTimeline returns a formatted timeline of all events in the trajectory.

func (*TrajectoryInspector) Replay added in v0.2.0

func (ti *TrajectoryInspector) Replay(speed float64) <-chan TrajectoryEvent

Replay returns a channel that emits events at the given speed multiplier. A speed of 1.0 replays in real-time, 2.0 at double speed, etc.

func (*TrajectoryInspector) Summarize added in v0.2.0

func (ti *TrajectoryInspector) Summarize() string

Summarize returns a one-paragraph summary of what happened in the trajectory.

type TrajectoryRun

type TrajectoryRun struct {
	ID       int
	Messages []client.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(_ []client.EyrieMessage, tokenCount, threshold int) bool

type TypeDoc added in v0.2.0

type TypeDoc struct {
	Name        string
	Kind        string // "struct", "interface", "type"
	Fields      []FieldDoc
	Methods     []FunctionDoc
	Description string
}

TypeDoc represents documentation for a type.

type URLScraper added in v0.2.0

type URLScraper struct {
	Enabled   bool
	MaxSize   int64
	Timeout   time.Duration
	UserAgent string
	Cache     map[string]*ScrapeResult
	// contains filtered or unexported fields
}

URLScraper detects URLs in conversation text and fetches/extracts their content.

func NewURLScraper added in v0.2.0

func NewURLScraper() *URLScraper

NewURLScraper creates a URLScraper with default settings.

func (*URLScraper) CacheGet added in v0.2.0

func (s *URLScraper) CacheGet(rawURL string) *ScrapeResult

CacheGet retrieves a cached ScrapeResult for the given URL.

func (*URLScraper) CacheSet added in v0.2.0

func (s *URLScraper) CacheSet(rawURL string, result *ScrapeResult)

CacheSet stores a ScrapeResult in the cache.

func (*URLScraper) DetectURLs added in v0.2.0

func (s *URLScraper) DetectURLs(text string) []string

DetectURLs finds all URLs in text, deduplicates them, and filters out binary URLs.

func (*URLScraper) Fetch added in v0.2.0

func (s *URLScraper) Fetch(ctx context.Context, rawURL string) (*ScrapeResult, error)

Fetch retrieves the URL content, respecting timeout and size limits.

func (*URLScraper) FormatForContext added in v0.2.0

func (s *URLScraper) FormatForContext(result *ScrapeResult, maxTokens int) string

FormatForContext formats a ScrapeResult for injection into agent context.

func (*URLScraper) ShouldAutoFetch added in v0.2.0

func (s *URLScraper) ShouldAutoFetch(rawURL string) bool

ShouldAutoFetch determines whether a URL should be automatically fetched.

type UndoEntry added in v0.2.0

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 added in v0.2.0

type UndoManager struct {
	Stack      []UndoEntry
	MaxEntries int
	// contains filtered or unexported fields
}

UndoManager tracks file modifications and allows granular rollback of changes.

func NewUndoManager added in v0.2.0

func NewUndoManager() *UndoManager

NewUndoManager creates a new UndoManager with a default capacity of 100 entries.

func (*UndoManager) BeforeModify added in v0.2.0

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) Clear added in v0.2.0

func (um *UndoManager) Clear()

Clear empties the undo stack entirely.

func (*UndoManager) DiffEntry added in v0.2.0

func (um *UndoManager) DiffEntry(entry *UndoEntry) string

DiffEntry shows what changed in the entry using a unified diff-like format.

func (*UndoManager) FormatHistory added in v0.2.0

func (um *UndoManager) FormatHistory(entries []UndoEntry) string

FormatHistory formats undo entries for terminal display with relative timestamps and change statistics.

func (*UndoManager) History added in v0.2.0

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 added in v0.2.0

func (um *UndoManager) Peek() *UndoEntry

Peek returns the last entry without removing it, or nil if the stack is empty.

func (*UndoManager) RecordChange added in v0.2.0

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 added in v0.2.0

func (um *UndoManager) Size() int

Size returns the number of entries currently on the stack.

func (*UndoManager) Undo added in v0.2.0

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.

func (*UndoManager) UndoN added in v0.2.0

func (um *UndoManager) UndoN(n int) ([]*UndoEntry, error)

UndoN undoes the last n changes, returning the undone entries in order from most recent to oldest.

func (*UndoManager) UndoTo added in v0.2.0

func (um *UndoManager) UndoTo(entryID string) ([]*UndoEntry, error)

UndoTo undoes everything back to (and including) the entry with the specified ID. Returns all undone entries from most recent to the target.

type UpdatePlan added in v0.2.0

type UpdatePlan struct {
	Dependencies      []Dependency
	RiskLevel         string // "low", "medium", "high"
	TestCommand       string
	RollbackCommand   string
	EstimatedBreaking int
}

UpdatePlan represents a structured plan for updating dependencies.

type ValidationError

type ValidationError struct {
	File    string
	Line    int
	Column  int
	Message string
}

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 Violation added in v0.2.0

type Violation struct {
	Convention string
	File       string
	Line       int
	Code       string
	Expected   string
	Got        string
}

Violation records a single convention violation in generated code.

type VizContextItem added in v0.2.0

type VizContextItem struct {
	Label     string
	Tokens    int
	Role      string
	Truncated bool
}

VizContextItem represents a single piece of content within a section.

type WatcherConfig added in v0.2.0

type WatcherConfig struct {
	Patterns       []string
	IgnorePatterns []string
	Debounce       time.Duration
	BatchWindow    time.Duration
	PollInterval   time.Duration
}

WatcherConfig holds configuration for a FileWatcher.

type WindowMessage added in v0.2.0

type WindowMessage struct {
	Role         string
	Content      string
	Tokens       int
	Index        int
	IsToolResult bool
}

WindowMessage represents a single message in the context window.

func PreserveToolPairs added in v0.2.0

func PreserveToolPairs(messages []WindowMessage, head, tail int) ([]WindowMessage, int)

PreserveToolPairs ensures tool_use and tool_result messages stay together by adjusting window boundaries so pairs are not split. Returns the adjusted messages and number of extra messages included to preserve pairs.

type WindowResult added in v0.2.0

type WindowResult struct {
	Head        []WindowMessage
	Tail        []WindowMessage
	Dropped     int
	Summary     string
	TotalTokens int
}

WindowResult holds the result of applying the head-tail window strategy.

type Workflow added in v0.2.0

type Workflow struct {
	Name        string            `json:"name"`
	Description string            `json:"description"`
	Steps       []WorkflowStep    `json:"steps"`
	Variables   map[string]string `json:"variables"`
	OnFailure   string            `json:"on_failure"` // "abort", "continue", "retry"
	MaxDuration time.Duration     `json:"max_duration"`
	CreatedAt   time.Time         `json:"created_at"`
}

Workflow represents a multi-step automated workflow definition.

type WorkflowEngine added in v0.2.0

type WorkflowEngine struct {
	Workflows map[string]*Workflow
	ExecuteFn func(ctx context.Context, action, input string) (string, error)
	// contains filtered or unexported fields
}

WorkflowEngine manages and executes workflows.

func NewWorkflowEngine added in v0.2.0

func NewWorkflowEngine(executeFn func(context.Context, string, string) (string, error)) *WorkflowEngine

NewWorkflowEngine creates a new WorkflowEngine with the given execution function.

func (*WorkflowEngine) Execute added in v0.2.0

func (we *WorkflowEngine) Execute(ctx context.Context, workflow *Workflow) (*WorkflowResult, error)

Execute runs a workflow to completion, resolving dependencies and executing steps.

func (*WorkflowEngine) LoadWorkflow added in v0.2.0

func (we *WorkflowEngine) LoadWorkflow(path string) (*Workflow, error)

LoadWorkflow parses a JSON workflow file and validates the step dependencies form a DAG.

type WorkflowResult added in v0.2.0

type WorkflowResult struct {
	Status    string            `json:"status"` // "success", "failed", "aborted"
	Steps     []StepResult      `json:"steps"`
	Duration  time.Duration     `json:"duration"`
	Variables map[string]string `json:"variables"`
}

WorkflowResult holds the result of a workflow execution.

type WorkflowStep added in v0.2.0

type WorkflowStep struct {
	Name       string        `json:"name"`
	Action     string        `json:"action"` // "prompt", "bash", "edit", "read", "condition", "loop"
	Input      string        `json:"input"`  // template with {{.Variable}} substitution
	Output     string        `json:"output"` // variable name to store result
	Condition  string        `json:"condition"`
	MaxRetries int           `json:"max_retries"`
	Timeout    time.Duration `json:"timeout"`
	DependsOn  []string      `json:"depends_on"`
}

WorkflowStep represents a single step in a workflow.

type WorkspaceDiffReport added in v0.2.0

type WorkspaceDiffReport struct {
	Files           []FileDiffReport
	TotalAdditions  int
	TotalDeletions  int
	FilesAdded      int
	FilesModified   int
	FilesDeleted    int
	SessionDuration time.Duration
	GeneratedAt     time.Time
}

WorkspaceDiffReport contains the full report of all workspace changes made during a session.

type WorkspaceState added in v0.2.0

type WorkspaceState struct {
	OpenFiles     map[string]*FileState
	ModifiedFiles map[string]time.Time
	StagedFiles   []string
	ProjectDir    string
	LastScan      time.Time
	// contains filtered or unexported fields
}

WorkspaceState maintains awareness of the current project state including which files are open, modified, and staged. It provides workspace context to the agent for informed decision-making.

func NewWorkspaceState added in v0.2.0

func NewWorkspaceState(projectDir string) *WorkspaceState

NewWorkspaceState creates a new WorkspaceState for the given project directory.

func (*WorkspaceState) BuildContextForAgent added in v0.2.0

func (ws *WorkspaceState) BuildContextForAgent() string

BuildContextForAgent formats workspace awareness for inclusion in a system prompt.

func (*WorkspaceState) DetectExternalChanges added in v0.2.0

func (ws *WorkspaceState) DetectExternalChanges() []string

DetectExternalChanges returns files that changed outside of hawk's modifications.

func (*WorkspaceState) GetModified added in v0.2.0

func (ws *WorkspaceState) GetModified() []string

GetModified returns all files modified in this session.

func (*WorkspaceState) GetOpened added in v0.2.0

func (ws *WorkspaceState) GetOpened() []string

GetOpened returns all files the agent has read.

func (*WorkspaceState) HasChanged added in v0.2.0

func (ws *WorkspaceState) HasChanged(path string) bool

HasChanged returns true if the file has changed on disk since it was last read.

func (*WorkspaceState) MarkModified added in v0.2.0

func (ws *WorkspaceState) MarkModified(path string)

MarkModified tracks that the agent has modified this file.

func (*WorkspaceState) MarkOpened added in v0.2.0

func (ws *WorkspaceState) MarkOpened(path string)

MarkOpened tracks that the agent has read this file.

func (*WorkspaceState) MarkStaged added in v0.2.0

func (ws *WorkspaceState) MarkStaged(path string)

MarkStaged tracks that a file is staged for commit.

func (*WorkspaceState) Reset added in v0.2.0

func (ws *WorkspaceState) Reset()

Reset clears all tracking state.

func (*WorkspaceState) Scan added in v0.2.0

func (ws *WorkspaceState) Scan() error

Scan walks the project directory and updates file states, detecting changes since the last scan.

func (*WorkspaceState) Summary added in v0.2.0

func (ws *WorkspaceState) Summary() string

Summary returns a human-readable summary of the workspace state.

Source Files

Directories

Path Synopsis
Package agent is the Stage-1 namespace for sub-agent orchestration types.
Package agent is the Stage-1 namespace for sub-agent orchestration types.
Package branching is the Stage-1 namespace for branching strategies, cascade, council, shadow, snowball.
Package branching is the Stage-1 namespace for branching strategies, cascade, council, shadow, snowball.
Package code is the Stage-1 namespace for code-aware features (context extraction, lenses, actions, explainer).
Package code is the Stage-1 namespace for code-aware features (context extraction, lenses, actions, explainer).
Package compact is the Stage-1 namespace for the engine package's compaction-related types and functions.
Package compact is the Stage-1 namespace for the engine package's compaction-related types and functions.
Package control is the Stage-1 namespace for engine control-flow safety types — loop detection, stall detection, backtracking.
Package control is the Stage-1 namespace for engine control-flow safety types — loop detection, stall detection, backtracking.
Package cost is the Stage-1 namespace for cost-tracking types and functions in package engine.
Package cost is the Stage-1 namespace for cost-tracking types and functions in package engine.
Package ctxmgr is the Stage-1 namespace for context budget, decay, packing, providers, visualisation, and read-only context.
Package ctxmgr is the Stage-1 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 is the Stage-1 namespace for documentation generation, external docs fetching, and doc updating.
Package docs is the Stage-1 namespace for documentation generation, external docs fetching, and doc updating.
Package errs is the Stage-1 namespace for error context enrichment, grouping, learning, patterns, and recovery.
Package errs is the Stage-1 namespace for error context enrichment, grouping, learning, patterns, and recovery.
Package git is the Stage-1 namespace for git-related types and functions in package engine.
Package git is the Stage-1 namespace for git-related types and functions in package engine.
Package history is the Stage-1 namespace for command history, conversation summarisation, distillation, head/tail, annotations.
Package history is the Stage-1 namespace for command history, conversation summarisation, distillation, head/tail, annotations.
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 is the Stage-1 namespace for clipboard, AI watcher, file watcher, and cron scheduler types.
Package io is the Stage-1 namespace for 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 is the Stage-1 namespace for knowledge, experience, and memory consolidation types.
Package memory is the Stage-1 namespace for 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 is the Stage-1 namespace for prompt-construction and prompt-optimisation types in package engine.
Package prompt is the Stage-1 namespace for prompt-construction and prompt-optimisation types in package engine.
Package retry is the Stage-1 namespace for retry-queue types in package engine.
Package retry is the Stage-1 namespace for retry-queue types in package engine.
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 safety is the Stage-1 namespace for hallucination guard, output redaction, permissions, risk assessment.
Package safety is the Stage-1 namespace for hallucination guard, output redaction, permissions, risk assessment.
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 is the Stage-1 namespace for URL scraping, issue search, and research agent types.
Package search is the Stage-1 namespace for 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.

Jump to

Keyboard shortcuts

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