tool

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const BinaryIndicator = "[binary file — not displaying]"

BinaryIndicator is the message returned instead of binary content.

Variables

This section is empty.

Functions

func Apply

func Apply(patch *FilePatch) error

Apply applies a single FilePatch to disk.

func AutoCommit

func AutoCommit(ctx context.Context, path, toolName, description string) error

func AutoFix

func AutoFix(report *ValidationReport) []string

AutoFix attempts to automatically fix issues found in the validation report. It returns a list of descriptions of fixes that were applied or suggested.

func BackupFile

func BackupFile(path string) (string, error)

BackupFile creates a backup of a file before modification. Returns the backup path, or empty string if backup wasn't needed.

func DecodeFileContent

func DecodeFileContent(data []byte) (string, error)

DecodeFileContent reads file bytes and returns clean UTF-8 string. Strips BOM, detects binary (null bytes in first 8KB), handles common encodings.

func DetectCommitType

func DetectCommitType(diff string, files []string) string

DetectCommitType analyzes the diff and file list to determine the commit type.

func DetectCredentials

func DetectCredentials(content string) string

DetectCredentials returns a non-empty description of the first credential pattern found in content, or "" if none match.

func DetectScope

func DetectScope(files []string) string

DetectScope determines the scope from file paths.

func FormatAuditSummary

func FormatAuditSummary() string

FormatAuditSummary produces a human-readable summary of today's modifications.

func FormatComplianceResult

func FormatComplianceResult(result *ComplianceResult) string

FormatComplianceResult formats a ComplianceResult into a human-readable report.

func FormatConflicts

func FormatConflicts(cf *ConflictFile) string

FormatConflicts produces a human-readable summary of conflicts and their resolution status.

func FormatForGitHub

func FormatForGitHub(pr *PRDescription) string

FormatForGitHub formats the PRDescription into a string ready for gh pr create.

func FormatLintResult

func FormatLintResult(result *LintResult) string

FormatLintResult produces a human-readable lint report.

func FormatRefactoringResult

func FormatRefactoringResult(result *RefactoringResult) string

FormatRefactoringResult renders a RefactoringResult as a human-readable string.

func FormatReport

func FormatReport(report *ValidationReport) string

FormatReport produces a human-readable formatted report of validation results.

func FormatResult

func FormatResult(path string, result *ReadResult) string

FormatResult formats a ReadResult for display.

func FormatResults

func FormatResults(results []*BackgroundResult) string

FormatResults returns a human-readable summary of background results suitable for injection into the conversation.

func GenerateBody

func GenerateBody(commitCtx CommitContext) string

GenerateBody creates a commit body with file change descriptions.

func GeneratePRBody

func GeneratePRBody(commits []CommitSummary, diffStat string, files []string) string

GeneratePRBody creates a detailed PR body with sections.

func GenerateRuleBased

func GenerateRuleBased(commitCtx CommitContext) string

GenerateRuleBased produces a conventional commit message using heuristics.

func GenerateSubject

func GenerateSubject(commitType string, files []string, diff string) string

GenerateSubject creates a commit subject line based on the type, files, and diff.

func GenerateTestPlan

func GenerateTestPlan(commits []CommitSummary, files []string) string

GenerateTestPlan creates a test plan based on the commits and files changed.

func GenerateTitle

func GenerateTitle(commits []CommitSummary) string

GenerateTitle creates a PR title from the commit summaries.

func IsBinaryContent

func IsBinaryContent(data []byte) bool

IsBinaryContent returns true when data appears to be binary, detected by: - Null bytes in the first binaryProbeSize bytes (classic binary indicator) - High ratio of non-text bytes (control characters other than \n, \r, \t)

func IsBinaryData

func IsBinaryData(data []byte) bool

IsBinaryData checks for null bytes in the first 8KB.

func IsDestructiveCommand

func IsDestructiveCommand(command string) bool

IsDestructiveCommand returns true when the command contains a pattern that is considered destructive. This is a superset intended for pre-execution gating — it catches broader patterns than bash.go's dangerousSubstrings (e.g. "rm -rf ." is already caught; this also catches bare "rm -rf").

func IsGitRepo

func IsGitRepo() bool

IsGitRepo checks if the current directory is inside a git repository.

func IsPlanMode

func IsPlanMode() bool

IsPlanMode returns whether plan mode is active.

func IsPowerShellAvailable

func IsPowerShellAvailable() bool

IsPowerShellAvailable returns whether a PowerShell runtime is available.

func IsSafeGitCommit

func IsSafeGitCommit(command string) bool

IsSafeGitCommit checks if a git commit command is safe. Git commits with simple quoted messages are considered safe.

func IsSensitivePath

func IsSensitivePath(path string) string

IsSensitivePath returns a non-empty reason when path points to a file that should be blocked for security. The path is cleaned and, when possible, resolved through symlinks before checking.

func IsSuspicious

func IsSuspicious(command string) bool

IsSuspicious returns true if the command needs a permission prompt. This is fail-closed: anything we can't confidently classify as safe gets flagged.

func LanguageForFile

func LanguageForFile(path string) string

LanguageForFile returns the tree-sitter language name for a file extension.

func LastAutoCommitHash

func LastAutoCommitHash() string

func ListBackups

func ListBackups(path string) []string

ListBackups returns all backups for a file.

func LoadDescription

func LoadDescription(toolName, fallback string) string

LoadDescription loads a tool description from embedded markdown. Falls back to the provided default if no file exists.

func RecordFileDelete

func RecordFileDelete(toolName, path string)

RecordFileDelete logs a file deletion.

func RecordFileEdit

func RecordFileEdit(toolName, path string, linesChanged int)

RecordFileEdit logs a file edit operation.

func RecordFileWrite

func RecordFileWrite(toolName, path string, bytes int)

RecordFileWrite logs a file write/create operation.

func ResolveAdditive

func ResolveAdditive(ours, theirs, base string) string

ResolveAdditive resolves conflicts where both sides add new lines relative to base.

func ResolveImports

func ResolveImports(ours, theirs string) string

ResolveImports merges import blocks, deduplicates, and sorts.

func ResolvePath

func ResolvePath(path string) (string, error)

ResolvePath returns the absolute, symlink-resolved path. If resolution fails it falls back to filepath.Abs.

func ResolveTrivial

func ResolveTrivial(ours, theirs string) (string, bool)

ResolveTrivial handles trivial conflict cases. Returns the resolution and true if resolved, empty string and false otherwise.

func RestoreFromBackup

func RestoreFromBackup(path string) error

RestoreFromBackup restores the most recent backup of a file.

func RevertLastAutoCommit

func RevertLastAutoCommit() error

func SegmentCommand

func SegmentCommand(cmd string) []string

SegmentCommand splits a command string on &&, ||, ;, and | (respecting quotes and heredocs) into individual segments for independent analysis.

func ShouldBlock

func ShouldBlock(report *ValidationReport) bool

ShouldBlock returns true if the validation report indicates the commit should not proceed due to required check failures.

func StripBOM

func StripBOM(data []byte) []byte

StripBOM removes Byte Order Mark from file content if present.

func SuggestLabels

func SuggestLabels(commits []CommitSummary) []string

SuggestLabels suggests PR labels based on commit types.

func SuggestReviewers

func SuggestReviewers(files []string, gitBlame map[string]string) []string

SuggestReviewers suggests reviewers based on git blame data for changed files.

func ToolTimeout

func ToolTimeout(toolName string) time.Duration

ToolTimeout returns the default timeout for a given tool name. Callers may still override with an explicit per-invocation value.

func TruncateOutput

func TruncateOutput(s string) string

TruncateOutput trims output to maxOutputBytes and appends an indicator.

func UndoLatest

func UndoLatest() (string, error)

UndoLatest finds the most recent backup across all files and restores it. Returns the restored file path for display, or an error if no backups exist.

func ValidateMessage

func ValidateMessage(msg string) []string

ValidateMessage checks a commit message for conventional commit compliance and returns a list of warnings.

func ValidateToolInput

func ValidateToolInput(toolName string, input json.RawMessage) error

ValidateToolInput checks that required parameters are present and have correct types. It inspects the tool's Parameters() schema for "required" fields and verifies they exist in the provided input JSON.

func WithContainerExecutor

func WithContainerExecutor(ctx context.Context, ce ContainerExecutor) context.Context

WithContainerExecutor injects a container executor into the context. When present, BashTool routes all commands through it instead of local shell.

func WithSSRFSkip

func WithSSRFSkip(ctx context.Context) context.Context

WithSSRFSkip returns a context that skips SSRF URL validation.

func WithToolContext

func WithToolContext(ctx context.Context, tc *ToolContext) context.Context

WithToolContext attaches a ToolContext to a context.

Types

type APICompatTool

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

APICompatTool implements the Tool interface for API compatibility checking.

func NewAPICompatTool

func NewAPICompatTool() *APICompatTool

NewAPICompatTool creates a new APICompatTool.

func (*APICompatTool) Description

func (t *APICompatTool) Description() string

func (*APICompatTool) Execute

func (t *APICompatTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (*APICompatTool) Name

func (t *APICompatTool) Name() string

func (*APICompatTool) Parameters

func (t *APICompatTool) Parameters() map[string]interface{}

type APISnapshot

type APISnapshot struct {
	Package     string         `json:"package"`
	Functions   []FuncSig      `json:"functions"`
	Types       []TypeSig      `json:"types"`
	Interfaces  []InterfaceSig `json:"interfaces"`
	Constants   []ConstSig     `json:"constants"`
	Variables   []VarSig       `json:"variables"`
	GeneratedAt time.Time      `json:"generated_at"`
}

APISnapshot captures the full public API surface of a Go package.

type AgentTool

type AgentTool struct{}

func (AgentTool) Aliases

func (AgentTool) Aliases() []string

func (AgentTool) Description

func (AgentTool) Description() string

func (AgentTool) Execute

func (AgentTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (AgentTool) Name

func (AgentTool) Name() string

func (AgentTool) Parameters

func (AgentTool) Parameters() map[string]interface{}

func (AgentTool) RiskLevel

func (AgentTool) RiskLevel() string

type AgenticFetchTool

type AgenticFetchTool struct{}

AgenticFetchTool spawns a sub-agent to fetch, process, and summarize web content.

func (AgenticFetchTool) Aliases

func (AgenticFetchTool) Aliases() []string

func (AgenticFetchTool) Description

func (AgenticFetchTool) Description() string

func (AgenticFetchTool) Execute

func (AgenticFetchTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (AgenticFetchTool) Name

func (AgenticFetchTool) Name() string

func (AgenticFetchTool) Parameters

func (AgenticFetchTool) Parameters() map[string]interface{}

func (AgenticFetchTool) RiskLevel

func (AgenticFetchTool) RiskLevel() string

type AliasedTool

type AliasedTool interface {
	Aliases() []string
}

AliasedTool can be implemented by tools that need backward-compatible wire names.

type AskUserQuestionTool

type AskUserQuestionTool struct{}

func (AskUserQuestionTool) Aliases

func (AskUserQuestionTool) Aliases() []string

func (AskUserQuestionTool) Description

func (AskUserQuestionTool) Description() string

func (AskUserQuestionTool) Execute

func (AskUserQuestionTool) Name

func (AskUserQuestionTool) Name() string

func (AskUserQuestionTool) Parameters

func (AskUserQuestionTool) Parameters() map[string]interface{}

type AuditEntry

type AuditEntry struct {
	Timestamp    time.Time `json:"timestamp"`
	Tool         string    `json:"tool"`
	Action       string    `json:"action"` // "create", "edit", "write", "delete"
	Path         string    `json:"path"`
	BackupRef    string    `json:"backup_ref,omitempty"`
	LinesChanged int       `json:"lines_changed,omitempty"`
	BytesWritten int       `json:"bytes_written,omitempty"`
}

AuditEntry records a file modification event.

func TodayEntries

func TodayEntries() ([]AuditEntry, error)

TodayEntries reads today's audit entries.

type AuditLog

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

AuditLog tracks all file modifications for accountability.

func GetAuditLog

func GetAuditLog() *AuditLog

GetAuditLog returns the global audit log instance.

func (*AuditLog) Close

func (a *AuditLog) Close()

Close closes the audit log.

func (*AuditLog) Record

func (a *AuditLog) Record(entry AuditEntry)

Record logs a file modification event.

type AutoImportTool

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

AutoImportTool resolves and adds missing imports in Go source files.

func NewAutoImportTool

func NewAutoImportTool() *AutoImportTool

NewAutoImportTool creates an AutoImportTool with a pre-configured AutoImporter.

func (AutoImportTool) Description

func (AutoImportTool) Description() string

func (AutoImportTool) Execute

func (t AutoImportTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (AutoImportTool) Name

func (AutoImportTool) Name() string

func (AutoImportTool) Parameters

func (AutoImportTool) Parameters() map[string]interface{}

type AutoImporter

type AutoImporter struct {
	KnownPackages map[string]string // symbol (package name) → import path
	// contains filtered or unexported fields
}

AutoImporter resolves missing imports in Go source code by matching package-qualified symbols against a database of known packages.

func NewAutoImporter

func NewAutoImporter() *AutoImporter

NewAutoImporter creates a new AutoImporter pre-loaded with 200+ common Go packages.

func (*AutoImporter) ApplyFixes

func (ai *AutoImporter) ApplyFixes(code string, fixes []ImportFix) string

ApplyFixes adds missing imports to the code, creating or extending the import block as needed. Imports are grouped: stdlib, external, internal.

func (*AutoImporter) DetectMissing

func (ai *AutoImporter) DetectMissing(code string) []string

DetectMissing finds package-qualified calls in code that don't have a corresponding import statement (e.g., fmt.Println without "fmt" imported).

func (*AutoImporter) FormatFixes

func (ai *AutoImporter) FormatFixes(fixes []ImportFix) string

FormatFixes renders a human-readable summary of the import fixes.

func (*AutoImporter) RegisterPackage

func (ai *AutoImporter) RegisterPackage(symbol, importPath string)

RegisterPackage adds a new symbol-to-import-path mapping.

func (*AutoImporter) Resolve

func (ai *AutoImporter) Resolve(code string) []ImportFix

Resolve finds undefined symbols in the given code and returns the import fixes needed to resolve them.

func (*AutoImporter) SuggestImport

func (ai *AutoImporter) SuggestImport(symbol string) []string

SuggestImport returns possible import paths for a given symbol (package name).

type BackgroundAgent

type BackgroundAgent struct {
	ID      string
	Prompt  string
	Started time.Time
}

BackgroundAgent represents a running background sub-agent.

type BackgroundAgentManager

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

BackgroundAgentManager tracks background sub-agent goroutines so the engine can wait for them and collect their results after the main LLM turn completes.

func NewBackgroundAgentManager

func NewBackgroundAgentManager() *BackgroundAgentManager

NewBackgroundAgentManager creates a new manager.

func (*BackgroundAgentManager) CollectResults

func (m *BackgroundAgentManager) CollectResults() []*BackgroundResult

CollectResults returns and clears all completed results.

func (*BackgroundAgentManager) Elapsed

func (m *BackgroundAgentManager) Elapsed(id string) time.Duration

Elapsed returns the elapsed time for a running agent.

func (*BackgroundAgentManager) GetResult

func (m *BackgroundAgentManager) GetResult(id string) (*BackgroundResult, bool)

GetResult returns the result for a specific agent ID, if completed.

func (*BackgroundAgentManager) HasPending

func (m *BackgroundAgentManager) HasPending() bool

HasPending returns true if any background agents are still running.

func (*BackgroundAgentManager) IsRunning

func (m *BackgroundAgentManager) IsRunning(id string) bool

IsRunning returns true if the agent with the given ID is still running.

func (*BackgroundAgentManager) Spawn

func (m *BackgroundAgentManager) Spawn(ctx context.Context, id, prompt string, spawnFn func(ctx context.Context, prompt string) (string, error))

Spawn starts a background sub-agent goroutine. The agent runs the spawnFn asynchronously and stores the result when complete.

func (*BackgroundAgentManager) WaitForResults

func (m *BackgroundAgentManager) WaitForResults(timeout time.Duration) []*BackgroundResult

WaitForResults blocks until all pending agents complete or the timeout is reached. Returns all collected results (including any that completed before this call).

type BackgroundResult

type BackgroundResult struct {
	ID     string
	Prompt string
	Output string
	Err    error
	Done   time.Time
}

BackgroundResult holds the outcome of a completed background sub-agent.

type BashTool

type BashTool struct{}

func (BashTool) Aliases

func (BashTool) Aliases() []string

func (BashTool) Description

func (BashTool) Description() string

func (BashTool) Execute

func (BashTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (BashTool) Name

func (BashTool) Name() string

func (BashTool) Parameters

func (BashTool) Parameters() map[string]interface{}

func (BashTool) RiskLevel

func (BashTool) RiskLevel() string

type BreakingChange

type BreakingChange struct {
	Type     string `json:"type"` // "removed", "signature_changed", "type_changed", "field_removed", "method_added"
	Symbol   string `json:"symbol"`
	Old      string `json:"old"`
	New      string `json:"new"`
	Severity string `json:"severity"` // "breaking", "deprecated", "compatible"
}

BreakingChange describes a single incompatible change between two API snapshots.

type BriefTool

type BriefTool struct{}

BriefTool (SendUserMessage) sends a message the user will read. Text outside this tool is visible in the detail view; the answer lives here.

func (BriefTool) Aliases

func (BriefTool) Aliases() []string

func (BriefTool) Description

func (BriefTool) Description() string

func (BriefTool) Execute

func (BriefTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (BriefTool) Name

func (BriefTool) Name() string

func (BriefTool) Parameters

func (BriefTool) Parameters() map[string]interface{}

type ChangeValidator

type ChangeValidator struct {
	Checks      []ValidationCheck
	StopOnFirst bool
	// contains filtered or unexported fields
}

ChangeValidator runs a battery of validation checks before allowing changes to be committed. It supports parallel execution and configurable check sets.

func NewChangeValidator

func NewChangeValidator() *ChangeValidator

NewChangeValidator creates a ChangeValidator with built-in checks covering syntax, format, lint, test, security, and size categories.

func (*ChangeValidator) AddCheck

func (cv *ChangeValidator) AddCheck(check ValidationCheck)

AddCheck registers a new validation check to the validator.

func (*ChangeValidator) Validate

func (cv *ChangeValidator) Validate(changedFiles []string) *ValidationReport

Validate runs all configured checks against the given changed files, executing independent checks in parallel where possible. Returns a full validation report.

func (*ChangeValidator) ValidateQuick

func (cv *ChangeValidator) ValidateQuick(changedFiles []string) *ValidationReport

ValidateQuick runs only fast checks (syntax and format) for rapid feedback.

type CheckResult

type CheckResult struct {
	Passed    bool
	CheckName string
	Message   string
	Details   []string
	Duration  time.Duration
	Severity  string // "error", "warning", "info"
}

CheckResult holds the outcome of a single validation check.

type CodeGenTool

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

CodeGenTool implements the Tool interface for code generation.

func NewCodeGenTool

func NewCodeGenTool() *CodeGenTool

NewCodeGenTool creates a new CodeGenTool.

func (*CodeGenTool) Description

func (t *CodeGenTool) Description() string

func (*CodeGenTool) Execute

func (t *CodeGenTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (*CodeGenTool) Generator

func (t *CodeGenTool) Generator() *CodeGenerator

Generator returns the underlying CodeGenerator for direct use.

func (*CodeGenTool) Name

func (t *CodeGenTool) Name() string

func (*CodeGenTool) Parameters

func (t *CodeGenTool) Parameters() map[string]interface{}

type CodeGenerator

type CodeGenerator struct {
	Templates map[string]*CodeTemplate
	Language  string
	// contains filtered or unexported fields
}

CodeGenerator manages code generation templates and renders them on demand.

func NewCodeGenerator

func NewCodeGenerator() *CodeGenerator

NewCodeGenerator creates a CodeGenerator pre-loaded with built-in templates.

func (*CodeGenerator) Generate

func (cg *CodeGenerator) Generate(templateName string, vars map[string]string) (string, error)

Generate renders a template with the given variables.

func (*CodeGenerator) ListTemplates

func (cg *CodeGenerator) ListTemplates(language string) []*CodeTemplate

ListTemplates returns templates filtered by language. If language is empty, all templates are returned.

func (*CodeGenerator) Preview

func (cg *CodeGenerator) Preview(templateName string, vars map[string]string) string

Preview shows what would be generated without performing full rendering. It shows the template with variable placeholders highlighted.

func (*CodeGenerator) Register

func (cg *CodeGenerator) Register(template *CodeTemplate)

Register adds a custom template to the generator.

func (*CodeGenerator) SuggestTemplate

func (cg *CodeGenerator) SuggestTemplate(description string) string

SuggestTemplate suggests the best template given a natural language description.

type CodeSearchResult

type CodeSearchResult struct {
	Path      string
	StartLine int
	EndLine   int
	Content   string
	Symbol    string
	Language  string
	Score     float64
}

CodeSearchResult is returned by CodeSearchFn.

type CodeSearchTool

type CodeSearchTool struct{}

CodeSearchTool searches the codebase semantically.

func (CodeSearchTool) Aliases

func (CodeSearchTool) Aliases() []string

func (CodeSearchTool) Description

func (CodeSearchTool) Description() string

func (CodeSearchTool) Execute

func (CodeSearchTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (CodeSearchTool) Name

func (CodeSearchTool) Name() string

func (CodeSearchTool) Parameters

func (CodeSearchTool) Parameters() map[string]interface{}

func (CodeSearchTool) RiskLevel

func (CodeSearchTool) RiskLevel() string

type CodeTemplate

type CodeTemplate struct {
	Name        string
	Description string
	Language    string
	Template    string
	Variables   []TemplateVar
	Output      string
}

CodeTemplate defines a single code generation template.

type CommitContext

type CommitContext struct {
	// Diff is the git diff content.
	Diff string

	// FilesChanged lists the paths of files that changed.
	FilesChanged []string

	// ConversationGoal describes what the user asked for.
	ConversationGoal string

	// PreviousCommits holds the last 3 commit messages for style matching.
	PreviousCommits []string
}

CommitContext holds all the information needed to generate a commit message.

type CommitLinter

type CommitLinter struct {
	Rules []CommitRule
	// contains filtered or unexported fields
}

CommitLinter validates commit messages against configurable rules following the commitlint specification.

func NewCommitLinter

func NewCommitLinter() *CommitLinter

NewCommitLinter creates a CommitLinter with default conventional commit rules.

func (*CommitLinter) FixMessage

func (cl *CommitLinter) FixMessage(message string) string

FixMessage auto-fixes common issues in a commit message.

func (*CommitLinter) Lint

func (cl *CommitLinter) Lint(message string) *LintResult

Lint validates a commit message against the configured rules.

func (*CommitLinter) LoadFromProject

func (cl *CommitLinter) LoadFromProject(projectDir string) error

LoadFromProject reads commitlint configuration from a project directory. It looks for commitlint.config.js, .commitlintrc.json, and .commitlintrc.yml.

type CommitMessageGenerator

type CommitMessageGenerator struct {
	// ChatFn calls the LLM with a prompt and returns the response.
	ChatFn func(ctx context.Context, prompt string) (string, error)

	// FallbackToConventional uses rule-based generation if LLM fails.
	FallbackToConventional bool

	// MaxLength is the maximum subject line length (default 72).
	MaxLength int

	// IncludeBody controls whether a body is appended (default true).
	IncludeBody bool

	// Style is one of "conventional", "descriptive", "concise".
	Style string
}

CommitMessageGenerator produces high-quality commit messages using an LLM with a rule-based fallback.

func (*CommitMessageGenerator) GenerateMessage

func (g *CommitMessageGenerator) GenerateMessage(ctx context.Context, commitCtx CommitContext) (string, error)

GenerateMessage uses the LLM to produce a commit message, falling back to rule-based generation if the LLM is unavailable or fails.

type CommitRule

type CommitRule struct {
	Name       string
	Level      string      // "error", "warning", "disabled"
	Applicable string      // "always", "never"
	Value      interface{} // rule-specific value (int, string, []string, etc.)
}

CommitRule represents a single linting rule.

type CommitSummary

type CommitSummary struct {
	Hash    string
	Message string
	Type    string
	Scope   string
	Files   []string
	Author  string
}

CommitSummary represents a parsed commit from git log output.

func ParseCommits

func ParseCommits(gitLog string) []CommitSummary

ParseCommits parses git log output into CommitSummary slices. Expected format per line: hash|author|message

type CompatChecker

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

CompatChecker performs API compatibility analysis between snapshots.

func NewCompatChecker

func NewCompatChecker() *CompatChecker

NewCompatChecker creates a new CompatChecker instance.

func (*CompatChecker) Compare

func (c *CompatChecker) Compare(old, new *APISnapshot) []BreakingChange

Compare detects breaking changes between two API snapshots.

func (*CompatChecker) FormatChanges

func (c *CompatChecker) FormatChanges(changes []BreakingChange) string

FormatChanges produces a human-readable report of breaking changes.

func (*CompatChecker) IsBackwardCompatible

func (c *CompatChecker) IsBackwardCompatible(old, new *APISnapshot) bool

IsBackwardCompatible returns true if no breaking changes exist between old and new.

func (*CompatChecker) LoadSnapshot

func (c *CompatChecker) LoadSnapshot(path string) (*APISnapshot, error)

LoadSnapshot deserializes an APISnapshot from a JSON file.

func (*CompatChecker) SaveSnapshot

func (c *CompatChecker) SaveSnapshot(snapshot *APISnapshot, path string) error

SaveSnapshot serializes an APISnapshot to a JSON file.

func (*CompatChecker) Snapshot

func (c *CompatChecker) Snapshot(path string) (*APISnapshot, error)

Snapshot parses the Go package at the given directory path and extracts the public API.

type ComplianceResult

type ComplianceResult struct {
	Ticket      *Ticket
	Satisfied   []string
	Unsatisfied []string
	Score       float64
	Suggestions []string
}

ComplianceResult holds the outcome of checking a PR against a ticket.

type ConfigTool

type ConfigTool struct{}

ConfigTool reads/writes hawk settings.

func (ConfigTool) Aliases

func (ConfigTool) Aliases() []string

func (ConfigTool) Description

func (ConfigTool) Description() string

func (ConfigTool) Execute

func (ConfigTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (ConfigTool) Name

func (ConfigTool) Name() string

func (ConfigTool) Parameters

func (ConfigTool) Parameters() map[string]interface{}

type Conflict

type Conflict struct {
	File          string
	StartLine     int
	EndLine       int
	OursContent   string
	TheirsContent string
	BaseContent   string
	Resolved      bool
	Resolution    string
}

Conflict represents a single conflict region within a file.

type ConflictFile

type ConflictFile struct {
	Path        string
	Conflicts   []Conflict
	FullContent string
}

ConflictFile represents a file containing one or more merge conflicts.

type ConflictResolver

type ConflictResolver struct {
	Strategy string // "ours", "theirs", "smart"
	// contains filtered or unexported fields
}

ConflictResolver provides intelligent git merge conflict resolution.

func NewConflictResolver

func NewConflictResolver() *ConflictResolver

NewConflictResolver creates a ConflictResolver with the "smart" strategy.

func (*ConflictResolver) ApplyResolution

func (cr *ConflictResolver) ApplyResolution(cf *ConflictFile) error

ApplyResolution writes the resolved content back to the file.

func (*ConflictResolver) AutoResolve

func (cr *ConflictResolver) AutoResolve(cf *ConflictFile) (string, error)

AutoResolve attempts to automatically resolve all conflicts in a ConflictFile.

func (*ConflictResolver) ParseConflicts

func (cr *ConflictResolver) ParseConflicts(path string) (*ConflictFile, error)

ParseConflicts reads a file and extracts all conflict regions.

type ConflictResolverTool

type ConflictResolverTool struct{}

ConflictResolverTool resolves git merge conflicts in files.

func (ConflictResolverTool) Description

func (ConflictResolverTool) Description() string

func (ConflictResolverTool) Execute

func (ConflictResolverTool) Name

func (ConflictResolverTool) Parameters

func (ConflictResolverTool) Parameters() map[string]interface{}

type ConstSig

type ConstSig struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Exported bool   `json:"exported"`
}

ConstSig represents a constant declaration.

type ContainerExecutor

type ContainerExecutor interface {
	Exec(ctx context.Context, command string, timeout time.Duration) (string, error)
	Running() bool
}

ContainerExecutor allows BashTool to route commands through a container instead of local execution. When set via context, all commands run inside the container (Docker-first mode).

func ContainerExecutorFromContext

func ContainerExecutorFromContext(ctx context.Context) ContainerExecutor

ContainerExecutorFromContext extracts the container executor, if any.

type CoreMemoryAppendTool

type CoreMemoryAppendTool struct{}

CoreMemoryAppendTool appends content to a memory block identified by label.

func (CoreMemoryAppendTool) Description

func (CoreMemoryAppendTool) Description() string

func (CoreMemoryAppendTool) Execute

func (CoreMemoryAppendTool) Name

func (CoreMemoryAppendTool) Parameters

func (CoreMemoryAppendTool) Parameters() map[string]interface{}

type CoreMemoryReplaceTool

type CoreMemoryReplaceTool struct{}

CoreMemoryReplaceTool finds and replaces content within a memory block.

func (CoreMemoryReplaceTool) Description

func (CoreMemoryReplaceTool) Description() string

func (CoreMemoryReplaceTool) Execute

func (CoreMemoryReplaceTool) Name

func (CoreMemoryReplaceTool) Parameters

func (CoreMemoryReplaceTool) Parameters() map[string]interface{}

type CoreMemoryRethinkTool

type CoreMemoryRethinkTool struct{}

CoreMemoryRethinkTool completely rewrites a memory block.

func (CoreMemoryRethinkTool) Description

func (CoreMemoryRethinkTool) Description() string

func (CoreMemoryRethinkTool) Execute

func (CoreMemoryRethinkTool) Name

func (CoreMemoryRethinkTool) Parameters

func (CoreMemoryRethinkTool) Parameters() map[string]interface{}

type CronCreateTool

type CronCreateTool struct{}

CronCreateTool schedules a prompt to run on a cron schedule.

func (CronCreateTool) Aliases

func (CronCreateTool) Aliases() []string

func (CronCreateTool) Description

func (CronCreateTool) Description() string

func (CronCreateTool) Execute

func (CronCreateTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (CronCreateTool) Name

func (CronCreateTool) Name() string

func (CronCreateTool) Parameters

func (CronCreateTool) Parameters() map[string]interface{}

type CronDeleteTool

type CronDeleteTool struct{}

CronDeleteTool removes a scheduled job.

func (CronDeleteTool) Aliases

func (CronDeleteTool) Aliases() []string

func (CronDeleteTool) Description

func (CronDeleteTool) Description() string

func (CronDeleteTool) Execute

func (CronDeleteTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (CronDeleteTool) Name

func (CronDeleteTool) Name() string

func (CronDeleteTool) Parameters

func (CronDeleteTool) Parameters() map[string]interface{}

type CronJob

type CronJob struct {
	ID        string    `json:"id"`
	Schedule  string    `json:"schedule"`
	Prompt    string    `json:"prompt"`
	Recurring bool      `json:"recurring"`
	Durable   bool      `json:"durable"`
	CreatedAt time.Time `json:"createdAt"`
	LastRun   time.Time `json:"lastRun,omitempty"`
	NextRun   time.Time `json:"nextRun"`
	Runs      int       `json:"runs"`
	// contains filtered or unexported fields
}

CronJob represents a scheduled recurring or one-shot task.

type CronListTool

type CronListTool struct{}

CronListTool lists all scheduled jobs.

func (CronListTool) Aliases

func (CronListTool) Aliases() []string

func (CronListTool) Description

func (CronListTool) Description() string

func (CronListTool) Execute

func (CronListTool) Name

func (CronListTool) Name() string

func (CronListTool) Parameters

func (CronListTool) Parameters() map[string]interface{}

type CronScheduler

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

CronScheduler manages scheduled tasks.

func GetCronScheduler

func GetCronScheduler() *CronScheduler

func (*CronScheduler) Create

func (s *CronScheduler) Create(schedule, prompt string, recurring, durable bool) (*CronJob, error)

func (*CronScheduler) Delete

func (s *CronScheduler) Delete(id string) bool

func (*CronScheduler) Get

func (s *CronScheduler) Get(id string) (*CronJob, bool)

func (*CronScheduler) List

func (s *CronScheduler) List() []*CronJob

type DebuggerTool

type DebuggerTool struct{}

DebuggerTool provides debugging capabilities via language-specific debuggers (Delve for Go, pdb for Python, node --inspect for Node).

func (DebuggerTool) Aliases

func (DebuggerTool) Aliases() []string

func (DebuggerTool) Description

func (DebuggerTool) Description() string

func (DebuggerTool) Execute

func (DebuggerTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (DebuggerTool) Name

func (DebuggerTool) Name() string

func (DebuggerTool) Parameters

func (DebuggerTool) Parameters() map[string]interface{}

type DevEnvTool

type DevEnvTool struct {
	// Manager is the DevEnvManager used for building and caching images.
	// If nil, the build action will return an error.
	Manager *sandbox.DevEnvManager
}

DevEnvTool allows the agent to read, write, and build Docker environments dynamically. When the agent needs a tool that isn't installed, it can modify the Dockerfile and rebuild the container on-the-fly.

func (DevEnvTool) Aliases

func (DevEnvTool) Aliases() []string

func (DevEnvTool) Description

func (DevEnvTool) Description() string

func (DevEnvTool) Execute

func (t DevEnvTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (DevEnvTool) Name

func (DevEnvTool) Name() string

func (DevEnvTool) Parameters

func (DevEnvTool) Parameters() map[string]interface{}

func (DevEnvTool) RiskLevel

func (DevEnvTool) RiskLevel() string

type DiagnosticsTool

type DiagnosticsTool struct{}

DiagnosticsTool runs lint/type/compile diagnostics for a file or project.

func (DiagnosticsTool) Aliases

func (DiagnosticsTool) Aliases() []string

func (DiagnosticsTool) Description

func (DiagnosticsTool) Description() string

func (DiagnosticsTool) Execute

func (DiagnosticsTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (DiagnosticsTool) Name

func (DiagnosticsTool) Name() string

func (DiagnosticsTool) Parameters

func (DiagnosticsTool) Parameters() map[string]interface{}

type DownloadTool

type DownloadTool struct{}

DownloadTool downloads a file from a URL to a local path.

func (DownloadTool) Aliases

func (DownloadTool) Aliases() []string

func (DownloadTool) Description

func (DownloadTool) Description() string

func (DownloadTool) Execute

func (DownloadTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (DownloadTool) Name

func (DownloadTool) Name() string

func (DownloadTool) Parameters

func (DownloadTool) Parameters() map[string]interface{}

func (DownloadTool) RiskLevel

func (DownloadTool) RiskLevel() string

type EnterPlanModeTool

type EnterPlanModeTool struct{}

func (EnterPlanModeTool) Aliases

func (EnterPlanModeTool) Aliases() []string

func (EnterPlanModeTool) Description

func (EnterPlanModeTool) Description() string

func (EnterPlanModeTool) Execute

func (EnterPlanModeTool) Name

func (EnterPlanModeTool) Name() string

func (EnterPlanModeTool) Parameters

func (EnterPlanModeTool) Parameters() map[string]interface{}

type EnterWorktreeTool

type EnterWorktreeTool struct{}

EnterWorktreeTool switches to a git worktree.

func (EnterWorktreeTool) Aliases

func (EnterWorktreeTool) Aliases() []string

func (EnterWorktreeTool) Description

func (EnterWorktreeTool) Description() string

func (EnterWorktreeTool) Execute

func (EnterWorktreeTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (EnterWorktreeTool) Name

func (EnterWorktreeTool) Name() string

func (EnterWorktreeTool) Parameters

func (EnterWorktreeTool) Parameters() map[string]interface{}

type ExitPlanModeTool

type ExitPlanModeTool struct{}

func (ExitPlanModeTool) Aliases

func (ExitPlanModeTool) Aliases() []string

func (ExitPlanModeTool) Description

func (ExitPlanModeTool) Description() string

func (ExitPlanModeTool) Execute

func (ExitPlanModeTool) Name

func (ExitPlanModeTool) Name() string

func (ExitPlanModeTool) Parameters

func (ExitPlanModeTool) Parameters() map[string]interface{}

type ExitWorktreeTool

type ExitWorktreeTool struct{}

ExitWorktreeTool returns to the main repository from a worktree.

func (ExitWorktreeTool) Aliases

func (ExitWorktreeTool) Aliases() []string

func (ExitWorktreeTool) Description

func (ExitWorktreeTool) Description() string

func (ExitWorktreeTool) Execute

func (ExitWorktreeTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (ExitWorktreeTool) Name

func (ExitWorktreeTool) Name() string

func (ExitWorktreeTool) Parameters

func (ExitWorktreeTool) Parameters() map[string]interface{}

type FieldSig

type FieldSig struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Tag      string `json:"tag"`
	Exported bool   `json:"exported"`
}

FieldSig represents a struct field.

type FileEditTool

type FileEditTool struct{}

func (FileEditTool) Aliases

func (FileEditTool) Aliases() []string

func (FileEditTool) Description

func (FileEditTool) Description() string

func (FileEditTool) Execute

func (FileEditTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (FileEditTool) Name

func (FileEditTool) Name() string

func (FileEditTool) Parameters

func (FileEditTool) Parameters() map[string]interface{}

func (FileEditTool) RiskLevel

func (FileEditTool) RiskLevel() string

type FileOperation

type FileOperation struct {
	Type       string      // "create", "modify", "delete", "rename"
	Path       string      // target path
	OldPath    string      // source path for rename operations
	Content    []byte      // new content (for create/modify)
	OldContent []byte      // original content (captured before modification)
	Mode       os.FileMode // file permissions
}

FileOperation represents a single file operation within a transaction.

type FilePatch

type FilePatch struct {
	Path     string
	Hunks    []Hunk
	IsNew    bool // true if creating a new file
	IsDelete bool // true if deleting file
}

FilePatch represents modifications to a single file.

type FileReadTool

type FileReadTool struct{}

func (FileReadTool) Aliases

func (FileReadTool) Aliases() []string

func (FileReadTool) Description

func (FileReadTool) Description() string

func (FileReadTool) Execute

func (FileReadTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (FileReadTool) Name

func (FileReadTool) Name() string

func (FileReadTool) Parameters

func (FileReadTool) Parameters() map[string]interface{}

func (FileReadTool) RiskLevel

func (FileReadTool) RiskLevel() string

type FileTemplate

type FileTemplate struct {
	Extension           string
	Language            string
	Template            string
	RequiresPackageName bool
}

FileTemplate describes the boilerplate template for a given file type.

type FileWriteTool

type FileWriteTool struct{}

func (FileWriteTool) Aliases

func (FileWriteTool) Aliases() []string

func (FileWriteTool) Description

func (FileWriteTool) Description() string

func (FileWriteTool) Execute

func (FileWriteTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (FileWriteTool) Name

func (FileWriteTool) Name() string

func (FileWriteTool) Parameters

func (FileWriteTool) Parameters() map[string]interface{}

func (FileWriteTool) RiskLevel

func (FileWriteTool) RiskLevel() string

type Fixture

type Fixture struct {
	TypeName string
	Fields   map[string]interface{}
	Variants []FixtureVariant
}

Fixture represents generated test data for a type.

type FixtureGenerator

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

FixtureGenerator generates test fixtures from type definitions.

func NewFixtureGenerator

func NewFixtureGenerator() *FixtureGenerator

NewFixtureGenerator creates a new FixtureGenerator.

func (*FixtureGenerator) FormatFixture

func (fg *FixtureGenerator) FormatFixture(fixture *Fixture) string

FormatFixture formats a fixture into a human-readable string representation.

func (*FixtureGenerator) GenerateEdgeCases

func (fg *FixtureGenerator) GenerateEdgeCases(typeDef string) []FixtureVariant

GenerateEdgeCases generates edge case fixture variants for a type definition.

func (*FixtureGenerator) GenerateForType

func (fg *FixtureGenerator) GenerateForType(typeDef string) *Fixture

GenerateForType parses a type definition and generates a Fixture with default values and variants.

func (*FixtureGenerator) GenerateGoCode

func (fg *FixtureGenerator) GenerateGoCode(fixture *Fixture) string

GenerateGoCode produces Go code that creates the fixture as a function.

func (*FixtureGenerator) GenerateTableTestData

func (fg *FixtureGenerator) GenerateTableTestData(funcSignature string) string

GenerateTableTestData generates a table-driven test structure for a function signature.

type FixtureGeneratorTool

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

FixtureGeneratorTool implements the Tool interface for test fixture generation.

func NewFixtureGeneratorTool

func NewFixtureGeneratorTool() *FixtureGeneratorTool

NewFixtureGeneratorTool creates a new FixtureGeneratorTool.

func (*FixtureGeneratorTool) Description

func (t *FixtureGeneratorTool) Description() string

func (*FixtureGeneratorTool) Execute

func (t *FixtureGeneratorTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (*FixtureGeneratorTool) Generator

func (t *FixtureGeneratorTool) Generator() *FixtureGenerator

Generator returns the underlying FixtureGenerator for direct use.

func (*FixtureGeneratorTool) Name

func (t *FixtureGeneratorTool) Name() string

func (*FixtureGeneratorTool) Parameters

func (t *FixtureGeneratorTool) Parameters() map[string]interface{}

type FixtureVariant

type FixtureVariant struct {
	Name        string
	Values      map[string]interface{}
	Description string
}

FixtureVariant represents a named variant of a fixture with specific values.

type FuncSig

type FuncSig struct {
	Name     string   `json:"name"`
	Receiver string   `json:"receiver"`
	Params   []string `json:"params"`
	Returns  []string `json:"returns"`
	Exported bool     `json:"exported"`
}

FuncSig represents a function or method signature.

type GitConfig

type GitConfig map[string]map[string]string

GitConfig represents a parsed .git/config file. Keys are stored as "section.key" or "section.subsection.key".

func ParseGitConfig

func ParseGitConfig(path string) (GitConfig, error)

ParseGitConfig reads and parses a git config file without spawning git. It handles: [section], [section "subsection"], key = value, and comments.

type GitHookInstaller

type GitHookInstaller struct {
	HooksDir  string
	Installed map[string]bool
	// contains filtered or unexported fields
}

GitHookInstaller manages installation and lifecycle of git hooks for hawk agent integration.

func NewGitHookInstaller

func NewGitHookInstaller(projectDir string) *GitHookInstaller

NewGitHookInstaller creates a new installer rooted at the given project directory. It resolves .git/hooks relative to projectDir and probes which hooks are already installed.

func (*GitHookInstaller) BackupExisting

func (g *GitHookInstaller) BackupExisting(hookName string) error

BackupExisting saves the existing hook as .bak before overwriting.

func (*GitHookInstaller) FormatStatus

func (g *GitHookInstaller) FormatStatus() string

FormatStatus returns a human-readable summary of installed/missing hooks.

func (*GitHookInstaller) GeneratePostCommit

func (g *GitHookInstaller) GeneratePostCommit() string

GeneratePostCommit returns a shell script that notifies the hawk trace system for session capture after a commit.

func (*GitHookInstaller) GeneratePreCommit

func (g *GitHookInstaller) GeneratePreCommit() string

GeneratePreCommit returns a shell script that runs format check, lint, and secret scan before allowing a commit.

func (*GitHookInstaller) GeneratePrePush

func (g *GitHookInstaller) GeneratePrePush() string

GeneratePrePush returns a shell script that runs the test suite before allowing a push.

func (*GitHookInstaller) GeneratePrepareCommitMsg

func (g *GitHookInstaller) GeneratePrepareCommitMsg() string

GeneratePrepareCommitMsg returns a shell script that invokes hawk to generate an AI-powered commit message.

func (*GitHookInstaller) Install

func (g *GitHookInstaller) Install(hook HookConfig) error

Install writes a hook script to .git/hooks/, makes it executable, and preserves any existing hook by chaining it.

func (*GitHookInstaller) InstallAll

func (g *GitHookInstaller) InstallAll() error

InstallAll installs the default set of hawk hooks for agent integration.

func (*GitHookInstaller) IsInstalled

func (g *GitHookInstaller) IsInstalled(hookName string) bool

IsInstalled reports whether a hawk-managed hook is installed for the given name.

func (*GitHookInstaller) ListInstalled

func (g *GitHookInstaller) ListInstalled() []string

ListInstalled returns the names of all currently installed hawk-managed hooks.

func (*GitHookInstaller) Uninstall

func (g *GitHookInstaller) Uninstall(hookName string) error

Uninstall removes a hawk-managed hook. If a backup exists it is restored.

type GitState

type GitState struct {
	Branch   string
	Commit   string
	IsDirty  bool
	Worktree bool
}

GitState holds parsed git repository state read directly from the filesystem without spawning a git subprocess.

func ReadGitState

func ReadGitState(dir string) (*GitState, error)

ReadGitState reads .git/HEAD and refs to determine the current branch and commit hash without spawning a git subprocess.

type GitTool

type GitTool struct {
	// WorkDir is the git repository working directory. If empty, uses CWD.
	WorkDir string
}

GitTool executes structured git commands.

func (GitTool) Aliases

func (GitTool) Aliases() []string

func (GitTool) Description

func (GitTool) Description() string

func (GitTool) Execute

func (t GitTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (GitTool) Name

func (GitTool) Name() string

func (GitTool) Parameters

func (GitTool) Parameters() map[string]interface{}

func (GitTool) RequiresApproval

func (t GitTool) RequiresApproval(input json.RawMessage) bool

func (GitTool) RiskLevel

func (GitTool) RiskLevel() string

type GlobTool

type GlobTool struct{}

func (GlobTool) Aliases

func (GlobTool) Aliases() []string

func (GlobTool) Description

func (GlobTool) Description() string

func (GlobTool) Execute

func (GlobTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (GlobTool) Name

func (GlobTool) Name() string

func (GlobTool) Parameters

func (GlobTool) Parameters() map[string]interface{}

func (GlobTool) RiskLevel

func (GlobTool) RiskLevel() string

type GrepTool

type GrepTool struct{}

func (GrepTool) Aliases

func (GrepTool) Aliases() []string

func (GrepTool) Description

func (GrepTool) Description() string

func (GrepTool) Execute

func (GrepTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (GrepTool) Name

func (GrepTool) Name() string

func (GrepTool) Parameters

func (GrepTool) Parameters() map[string]interface{}

func (GrepTool) RiskLevel

func (GrepTool) RiskLevel() string

type HookConfig

type HookConfig struct {
	Name     string // "pre-commit", "post-commit", "prepare-commit-msg", "pre-push"
	Script   string
	Enabled  bool
	Priority int
}

HookConfig describes a single git hook to install.

type Hunk

type Hunk struct {
	ContextBefore string   // line(s) before the change for anchoring
	ContextAfter  string   // line(s) after the change for anchoring
	OldLines      []string // lines to remove (without the leading "- ")
	NewLines      []string // lines to add (without the leading "+ ")
}

Hunk represents a single change within a file, anchored by context lines.

type ImportEntry

type ImportEntry struct {
	Path  string
	Alias string
	Used  bool
}

ImportEntry represents a single import statement.

type ImportFix

type ImportFix struct {
	File    string // file path where the fix applies
	Package string // package name (e.g., "fmt")
	Path    string // import path (e.g., "fmt" or "encoding/json")
	Symbol  string // the full qualified symbol reference (e.g., "fmt.Println")
	Line    int    // approximate line number where the symbol is used
}

ImportFix describes a single missing import that should be added.

type ImportGroup

type ImportGroup struct {
	Name    string
	Imports []ImportEntry
	Comment string
}

ImportGroup represents a logical grouping of imports.

type ImportOrganizer

type ImportOrganizer struct {
	Language   string
	GroupOrder []string
}

ImportOrganizer organizes and manages imports for Go and TypeScript files.

func NewImportOrganizer

func NewImportOrganizer(language string) *ImportOrganizer

NewImportOrganizer creates a new ImportOrganizer for the given language.

func (*ImportOrganizer) AddMissingImport

func (o *ImportOrganizer) AddMissingImport(content, importPath string) (string, error)

AddMissingImport adds an import to the correct group in the content.

func (*ImportOrganizer) DetectUnusedGo

func (o *ImportOrganizer) DetectUnusedGo(content string, imports []ImportEntry) []ImportEntry

DetectUnusedGo checks each import against the file body to find unused ones.

func (*ImportOrganizer) DetectUnusedTS

func (o *ImportOrganizer) DetectUnusedTS(content string, imports []ImportEntry) []ImportEntry

DetectUnusedTS checks each TypeScript import for usage in the file.

func (*ImportOrganizer) FormatImportBlock

func (o *ImportOrganizer) FormatImportBlock(groups []ImportGroup, language string) string

FormatImportBlock renders properly formatted import block for the language.

func (*ImportOrganizer) OrganizeGo

func (o *ImportOrganizer) OrganizeGo(content string) (string, error)

OrganizeGo parses and reorganizes imports in Go source code.

func (*ImportOrganizer) OrganizeTypeScript

func (o *ImportOrganizer) OrganizeTypeScript(content string) (string, error)

OrganizeTypeScript parses and reorganizes imports in TypeScript source code.

func (*ImportOrganizer) RemoveImport

func (o *ImportOrganizer) RemoveImport(content, importPath string) (string, error)

RemoveImport removes a specific import from the content.

type ImportOrganizerTool

type ImportOrganizerTool struct{}

ImportOrganizerTool organizes imports in Go and TypeScript files.

func (ImportOrganizerTool) Description

func (ImportOrganizerTool) Description() string

func (ImportOrganizerTool) Execute

func (ImportOrganizerTool) Name

func (ImportOrganizerTool) Name() string

func (ImportOrganizerTool) Parameters

func (ImportOrganizerTool) Parameters() map[string]interface{}

type InterfaceSig

type InterfaceSig struct {
	Name     string    `json:"name"`
	Methods  []FuncSig `json:"methods"`
	Exported bool      `json:"exported"`
}

InterfaceSig represents an interface declaration.

type LSPTool

type LSPTool struct{}

func (LSPTool) Aliases

func (LSPTool) Aliases() []string

func (LSPTool) Description

func (LSPTool) Description() string

func (LSPTool) Execute

func (LSPTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (LSPTool) Name

func (LSPTool) Name() string

func (LSPTool) Parameters

func (LSPTool) Parameters() map[string]interface{}

type LSTool

type LSTool struct{}

func (LSTool) Aliases

func (LSTool) Aliases() []string

func (LSTool) Description

func (LSTool) Description() string

func (LSTool) Execute

func (LSTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (LSTool) Name

func (LSTool) Name() string

func (LSTool) Parameters

func (LSTool) Parameters() map[string]interface{}

func (LSTool) RiskLevel

func (LSTool) RiskLevel() string

type LintResult

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

LintResult contains the outcome of linting a commit message.

type ListMcpResourcesTool

type ListMcpResourcesTool struct{}

func (ListMcpResourcesTool) Aliases

func (ListMcpResourcesTool) Aliases() []string

func (ListMcpResourcesTool) Description

func (ListMcpResourcesTool) Description() string

func (ListMcpResourcesTool) Execute

func (ListMcpResourcesTool) Name

func (ListMcpResourcesTool) Parameters

func (ListMcpResourcesTool) Parameters() map[string]interface{}

type MCPAuthManager

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

MCPAuthManager handles OAuth flows for MCP servers.

func GetMCPAuthManager

func GetMCPAuthManager() *MCPAuthManager

func (*MCPAuthManager) GetState

func (m *MCPAuthManager) GetState(serverName string) (*MCPAuthState, bool)

func (*MCPAuthManager) SetAuthenticated

func (m *MCPAuthManager) SetAuthenticated(serverName string)

func (*MCPAuthManager) StartAuth

func (m *MCPAuthManager) StartAuth(serverName, serverURL string) (*MCPAuthState, error)

type MCPAuthState

type MCPAuthState struct {
	ServerName string `json:"serverName"`
	AuthURL    string `json:"authUrl,omitempty"`
	Status     string `json:"status"` // "pending", "authenticated", "error"
	Error      string `json:"error,omitempty"`
}

MCPAuthState tracks OAuth state for an MCP server.

type MCPTool

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

MCPTool wraps an MCP server tool as a hawk tool.

func NewMCPTool

func NewMCPTool(server *mcp.Server, t mcp.Tool) *MCPTool

func (*MCPTool) Aliases

func (m *MCPTool) Aliases() []string

func (*MCPTool) Description

func (m *MCPTool) Description() string

func (*MCPTool) Execute

func (m *MCPTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (*MCPTool) Name

func (m *MCPTool) Name() string

func (*MCPTool) Parameters

func (m *MCPTool) Parameters() map[string]interface{}

type McpAuthTool

type McpAuthTool struct{}

McpAuthTool initiates OAuth authentication for an MCP server.

func (McpAuthTool) Aliases

func (McpAuthTool) Aliases() []string

func (McpAuthTool) Description

func (McpAuthTool) Description() string

func (McpAuthTool) Execute

func (McpAuthTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (McpAuthTool) Name

func (McpAuthTool) Name() string

func (McpAuthTool) Parameters

func (McpAuthTool) Parameters() map[string]interface{}

type MultiAgentTool

type MultiAgentTool struct{}

MultiAgentTool spawns multiple sub-agents in parallel.

func (MultiAgentTool) Aliases

func (MultiAgentTool) Aliases() []string

func (MultiAgentTool) Description

func (MultiAgentTool) Description() string

func (MultiAgentTool) Execute

func (MultiAgentTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (MultiAgentTool) Name

func (MultiAgentTool) Name() string

func (MultiAgentTool) Parameters

func (MultiAgentTool) Parameters() map[string]interface{}

type MultiEditTool

type MultiEditTool struct{}

MultiEditTool applies multiple edits to a single file in one call.

func (MultiEditTool) Aliases

func (MultiEditTool) Aliases() []string

func (MultiEditTool) Description

func (MultiEditTool) Description() string

func (MultiEditTool) Execute

func (MultiEditTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (MultiEditTool) Name

func (MultiEditTool) Name() string

func (MultiEditTool) Parameters

func (MultiEditTool) Parameters() map[string]interface{}

func (MultiEditTool) RiskLevel

func (MultiEditTool) RiskLevel() string

type NotebookEditTool

type NotebookEditTool struct{}

NotebookEditTool edits Jupyter notebook cells.

func (NotebookEditTool) Aliases

func (NotebookEditTool) Aliases() []string

func (NotebookEditTool) Description

func (NotebookEditTool) Description() string

func (NotebookEditTool) Execute

func (NotebookEditTool) Name

func (NotebookEditTool) Name() string

func (NotebookEditTool) Parameters

func (NotebookEditTool) Parameters() map[string]interface{}

type OutlineTool

type OutlineTool struct{}

OutlineTool extracts function/type/class signatures from files without reading the full content. Returns a compact outline with line numbers.

func (OutlineTool) Aliases

func (OutlineTool) Aliases() []string

func (OutlineTool) Description

func (OutlineTool) Description() string

func (OutlineTool) Execute

func (OutlineTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (OutlineTool) Name

func (OutlineTool) Name() string

func (OutlineTool) Parameters

func (OutlineTool) Parameters() map[string]interface{}

func (OutlineTool) RiskLevel

func (OutlineTool) RiskLevel() string

type PRDescription

type PRDescription struct {
	Title     string
	Body      string
	Labels    []string
	Reviewers []string
	Type      string // "feat", "fix", "refactor", "docs", "chore"
	Breaking  bool
	TestPlan  string
}

PRDescription holds all the components of a generated pull request description.

type PRGenerator

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

PRGenerator generates pull request descriptions from commit history and diffs.

func NewPRGenerator

func NewPRGenerator(projectDir string) *PRGenerator

NewPRGenerator creates a new PRGenerator for the given project directory.

func (*PRGenerator) Generate

func (g *PRGenerator) Generate(baseBranch string) (*PRDescription, error)

Generate produces a PRDescription by analyzing commits since baseBranch.

type PRGeneratorTool

type PRGeneratorTool struct {
	ProjectDir string
}

PRGeneratorTool implements the Tool interface for PR description generation.

func (*PRGeneratorTool) Description

func (t *PRGeneratorTool) Description() string

Description returns the tool description.

func (*PRGeneratorTool) Execute

func (t *PRGeneratorTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

Execute runs the PR generator tool.

func (*PRGeneratorTool) Name

func (t *PRGeneratorTool) Name() string

Name returns the tool name.

func (*PRGeneratorTool) Parameters

func (t *PRGeneratorTool) Parameters() map[string]interface{}

Parameters returns the JSON schema for the tool's input.

type ParsedCommit

type ParsedCommit struct {
	Type     string
	Scope    string
	Subject  string
	Body     string
	Footer   string
	Breaking bool
}

ParsedCommit holds the parsed components of a conventional commit message.

func ParseCommitMessage

func ParseCommitMessage(msg string) *ParsedCommit

ParseCommitMessage parses a commit message into its constituent parts.

type PatchParser

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

PatchParser holds parsed file patches from a structured patch input.

func ParsePatch

func ParsePatch(input string) (*PatchParser, error)

ParsePatch parses a structured patch in the *** Begin Patch format.

func (*PatchParser) ApplyAll

func (p *PatchParser) ApplyAll() ([]string, error)

ApplyAll applies all patches and returns the list of modified file paths.

func (*PatchParser) Patches

func (p *PatchParser) Patches() []FilePatch

Patches returns the parsed file patches.

type PatchTool

type PatchTool struct{}

PatchTool implements the Tool interface for applying structured patches.

func (PatchTool) Description

func (PatchTool) Description() string

func (PatchTool) Execute

func (PatchTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (PatchTool) Name

func (PatchTool) Name() string

func (PatchTool) Parameters

func (PatchTool) Parameters() map[string]interface{}

type PathProtector

type PathProtector interface {
	IsProtected(path string) bool
}

PathProtector checks whether a file path is protected (read-only). engine.ProtectedPaths implements this interface.

type PathResolver

type PathResolver struct {
	ProjectDir string
	FileCache  map[string]bool
	LastScan   time.Time
	// contains filtered or unexported fields
}

PathResolver helps the agent find the correct file paths even when given partial or ambiguous paths.

func NewPathResolver

func NewPathResolver(projectDir string) *PathResolver

NewPathResolver creates a new PathResolver for the given project directory.

func (*PathResolver) FindByName

func (pr *PathResolver) FindByName(filename string) []string

FindByName finds all files with this exact name anywhere in the project.

func (*PathResolver) FindByPattern

func (pr *PathResolver) FindByPattern(glob string) []string

FindByPattern finds files matching a glob pattern across the project.

func (*PathResolver) FindSimilar

func (pr *PathResolver) FindSimilar(path string, limit int) []string

FindSimilar returns paths similar to the input based on Levenshtein distance.

func (*PathResolver) FormatResult

func (pr *PathResolver) FormatResult(result *ResolveResult) string

FormatResult formats a ResolveResult for display.

func (*PathResolver) IsValidPath

func (pr *PathResolver) IsValidPath(path string) bool

IsValidPath checks whether the given path points to an existing file.

func (*PathResolver) NormalizePath

func (pr *PathResolver) NormalizePath(path string) string

NormalizePath cleans a path, resolves .., and handles ~ expansion.

func (*PathResolver) Resolve

func (pr *PathResolver) Resolve(path string) *ResolveResult

Resolve attempts to find the correct file path given an exact, partial, or ambiguous input path. It tries multiple strategies in order of confidence.

func (*PathResolver) ScanProject

func (pr *PathResolver) ScanProject() error

ScanProject builds the file cache for fast lookups.

func (*PathResolver) SuggestCorrection

func (pr *PathResolver) SuggestCorrection(wrongPath string) string

SuggestCorrection returns the best single correction suggestion for a wrong path.

type PowerShellTool

type PowerShellTool struct{}

PowerShellTool executes PowerShell commands (Windows/cross-platform pwsh).

func (PowerShellTool) Aliases

func (PowerShellTool) Aliases() []string

func (PowerShellTool) Description

func (PowerShellTool) Description() string

func (PowerShellTool) Execute

func (PowerShellTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (PowerShellTool) Name

func (PowerShellTool) Name() string

func (PowerShellTool) Parameters

func (PowerShellTool) Parameters() map[string]interface{}

func (PowerShellTool) RiskLevel

func (PowerShellTool) RiskLevel() string

type ReadMcpResourceTool

type ReadMcpResourceTool struct{}

func (ReadMcpResourceTool) Aliases

func (ReadMcpResourceTool) Aliases() []string

func (ReadMcpResourceTool) Description

func (ReadMcpResourceTool) Description() string

func (ReadMcpResourceTool) Execute

func (ReadMcpResourceTool) Name

func (ReadMcpResourceTool) Name() string

func (ReadMcpResourceTool) Parameters

func (ReadMcpResourceTool) Parameters() map[string]interface{}

type ReadResult

type ReadResult struct {
	Content    string
	Tokens     int
	Truncated  bool
	Strategy   string
	Sections   []ReadSection
	TotalLines int
	ShownLines int
}

ReadResult contains the result of a smart file read.

type ReadSection

type ReadSection struct {
	StartLine int
	EndLine   int
	Content   string
	Reason    string // "head", "tail", "function", "relevant", "import"
}

ReadSection represents a contiguous section of a file that was read.

type RefactorTool

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

RefactorTool exposes refactoring operations as a hawk tool.

func NewRefactorTool

func NewRefactorTool() *RefactorTool

NewRefactorTool creates a RefactorTool with its own Refactorer instance.

func (RefactorTool) Description

func (RefactorTool) Description() string

func (RefactorTool) Execute

func (rt RefactorTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (RefactorTool) Name

func (RefactorTool) Name() string

func (RefactorTool) Parameters

func (RefactorTool) Parameters() map[string]interface{}

type Refactorer

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

Refactorer applies common refactoring patterns using pure AST-based transformations without requiring LLM calls.

func NewRefactorer

func NewRefactorer() *Refactorer

NewRefactorer creates a new Refactorer.

func (*Refactorer) AddErrorCheck

func (r *Refactorer) AddErrorCheck(file string, line int) (*RefactoringResult, error)

AddErrorCheck inserts an `if err != nil { return err }` block after the given line, which should be a function call that returns an error.

func (*Refactorer) ConvertToTableTest

func (r *Refactorer) ConvertToTableTest(file, testFunc string) (*RefactoringResult, error)

ConvertToTableTest converts a simple test function into table-driven test format.

func (*Refactorer) ExtractFunction

func (r *Refactorer) ExtractFunction(file string, startLine, endLine int, newName string) (*RefactoringResult, error)

ExtractFunction extracts lines startLine..endLine (1-based, inclusive) from file into a new function named newName, replacing the original lines with a call. It detects needed parameters from variables used but not declared in the extracted block.

func (*Refactorer) ExtractVariable

func (r *Refactorer) ExtractVariable(file string, line int, expr, varName string) (*RefactoringResult, error)

ExtractVariable replaces an expression on the given line with a named variable, inserting the variable declaration before that line.

func (*Refactorer) InlineVariable

func (r *Refactorer) InlineVariable(file string, line int) (*RefactoringResult, error)

InlineVariable replaces a variable declaration on the given line with its value at all use sites within the file.

func (*Refactorer) RemoveUnusedParams

func (r *Refactorer) RemoveUnusedParams(file, funcName string) (*RefactoringResult, error)

RemoveUnusedParams detects and removes parameters not used in the specified function body.

func (*Refactorer) RenameSymbol

func (r *Refactorer) RenameSymbol(file, oldName, newName string) (*RefactoringResult, error)

RenameSymbol renames all occurrences of oldName to newName within the file, respecting word boundaries.

func (*Refactorer) SortImports

func (r *Refactorer) SortImports(file string) (*RefactoringResult, error)

SortImports groups and sorts imports in a Go file (stdlib, external, internal).

func (*Refactorer) WrapWithContext

func (r *Refactorer) WrapWithContext(file string, line int, context string) (*RefactoringResult, error)

WrapWithContext wraps a `return err` statement on the given line with `return fmt.Errorf("%s: %%w", context, err)`.

type RefactoringResult

type RefactoringResult struct {
	File        string
	Changes     int
	Before      string
	After       string
	Type        string
	Description string
}

RefactoringResult describes the outcome of a single refactoring operation.

type Registry

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

Registry holds all registered tools.

func NewRegistry

func NewRegistry(tools ...Tool) *Registry

NewRegistry creates a registry with the given tools.

func (*Registry) Execute

func (r *Registry) Execute(ctx context.Context, name string, input json.RawMessage) (string, error)

Execute runs a tool by name with the given JSON input.

func (*Registry) EyrieTools

func (r *Registry) EyrieTools() []client.EyrieTool

EyrieTools converts all tools to eyrie tool definitions for the API.

func (*Registry) Filter

func (r *Registry) Filter(allow []string) *Registry

Filter returns a new Registry containing only tools whose names are in the allowlist.

func (*Registry) Get

func (r *Registry) Get(name string) (Tool, bool)

Get returns a tool by name.

func (*Registry) PrimaryTools

func (r *Registry) PrimaryTools() []Tool

PrimaryTools returns the model-visible tools registered in this registry.

type ResolveResult

type ResolveResult struct {
	Found        bool
	Path         string
	Alternatives []string
	Confidence   float64
}

ResolveResult contains the outcome of a path resolution attempt.

type RiskLevelProvider

type RiskLevelProvider interface {
	RiskLevel() string // "low", "medium", "high"
}

RiskLevelProvider can be implemented by tools to declare their risk level. Tools that don't implement it default to "medium".

type SkillTool

type SkillTool struct{}

func (SkillTool) Aliases

func (SkillTool) Aliases() []string

func (SkillTool) Description

func (SkillTool) Description() string

func (SkillTool) Execute

func (SkillTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (SkillTool) Name

func (SkillTool) Name() string

func (SkillTool) Parameters

func (SkillTool) Parameters() map[string]interface{}

type SleepTool

type SleepTool struct{}

SleepTool pauses execution for a specified duration.

func (SleepTool) Aliases

func (SleepTool) Aliases() []string

func (SleepTool) Description

func (SleepTool) Description() string

func (SleepTool) Execute

func (SleepTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (SleepTool) Name

func (SleepTool) Name() string

func (SleepTool) Parameters

func (SleepTool) Parameters() map[string]interface{}

type SmartCreateTool

type SmartCreateTool struct {
	Creator *SmartCreator
}

SmartCreateTool implements the Tool interface for smart file creation.

func (*SmartCreateTool) Description

func (t *SmartCreateTool) Description() string

func (*SmartCreateTool) Execute

func (t *SmartCreateTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (*SmartCreateTool) Name

func (t *SmartCreateTool) Name() string

func (*SmartCreateTool) Parameters

func (t *SmartCreateTool) Parameters() map[string]interface{}

type SmartCreator

type SmartCreator struct {
	ProjectDir  string
	Conventions map[string]string
}

SmartCreator generates boilerplate content when creating new files based on project conventions and file type.

func NewSmartCreator

func NewSmartCreator(projectDir string) *SmartCreator

NewSmartCreator creates a SmartCreator rooted at the given project directory.

func (*SmartCreator) DetectCopyright

func (sc *SmartCreator) DetectCopyright(projectDir string) string

DetectCopyright scans existing source files in the project for a copyright header and returns it if found.

func (*SmartCreator) DetectImportStyle

func (sc *SmartCreator) DetectImportStyle(projectDir string, language string) string

DetectImportStyle looks at existing files to determine import conventions for the given language.

func (*SmartCreator) GenerateBoilerplate

func (sc *SmartCreator) GenerateBoilerplate(path string) string

GenerateBoilerplate produces starter content for a new file based on its extension and path within the project.

func (*SmartCreator) GenerateInterface

func (sc *SmartCreator) GenerateInterface(functions []string) string

GenerateInterface produces a Go interface definition from function signatures.

func (*SmartCreator) GenerateTestFile

func (sc *SmartCreator) GenerateTestFile(sourcePath string) string

GenerateTestFile creates a test file corresponding to the given source file.

func (*SmartCreator) InferPackageName

func (sc *SmartCreator) InferPackageName(filePath string) string

InferPackageName determines the Go package name from a file path.

type SmartReader

type SmartReader struct {
	MaxTokens int
	Strategy  string // "full", "head_tail", "symbols", "relevant"
	// contains filtered or unexported fields
}

SmartReader reads files within a token budget using adaptive strategies.

func NewSmartReader

func NewSmartReader(maxTokens int) *SmartReader

NewSmartReader creates a SmartReader with the given token budget.

func (*SmartReader) EstimateFileTokens

func (sr *SmartReader) EstimateFileTokens(path string) (int, error)

EstimateFileTokens quickly estimates the token count without reading the full file. Uses file size / 4 as approximation.

func (*SmartReader) ReadFile

func (sr *SmartReader) ReadFile(path string, query string) (*ReadResult, error)

ReadFile reads a file intelligently within the token budget. If the file fits in budget, the full content is returned. Otherwise the configured strategy is applied.

func (*SmartReader) ReadRange

func (sr *SmartReader) ReadRange(path string, startLine, endLine int) (*ReadResult, error)

ReadRange reads a specific line range from a file.

func (*SmartReader) ReadRelevant

func (sr *SmartReader) ReadRelevant(path, query string, budget int) (*ReadResult, error)

ReadRelevant reads lines containing query keywords with surrounding context.

func (*SmartReader) ReadSymbolsOnly

func (sr *SmartReader) ReadSymbolsOnly(path string) (*ReadResult, error)

ReadSymbolsOnly extracts function signatures, type definitions, and exports.

func (*SmartReader) ReadWithBudget

func (sr *SmartReader) ReadWithBudget(path string, budget int) (*ReadResult, error)

ReadWithBudget reads a file within an exact token budget using adaptive strategy.

type SmartReaderTool

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

SmartReaderTool exposes SmartReader as a hawk tool.

func NewSmartReaderTool

func NewSmartReaderTool() *SmartReaderTool

func (SmartReaderTool) Aliases

func (SmartReaderTool) Aliases() []string

func (SmartReaderTool) Description

func (SmartReaderTool) Description() string

func (*SmartReaderTool) Execute

func (t *SmartReaderTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (SmartReaderTool) Name

func (SmartReaderTool) Name() string

func (SmartReaderTool) Parameters

func (SmartReaderTool) Parameters() map[string]interface{}

func (SmartReaderTool) RiskLevel

func (SmartReaderTool) RiskLevel() string

type StructuredEditTool

type StructuredEditTool struct{}

StructuredEditTool applies search-and-replace blocks (structured diffs) to files. This is more precise and token-efficient than whole-file writes. Inspired by Aider's search/replace edit format.

func (StructuredEditTool) Aliases

func (StructuredEditTool) Aliases() []string

func (StructuredEditTool) Description

func (StructuredEditTool) Description() string

func (StructuredEditTool) Execute

func (s StructuredEditTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (StructuredEditTool) Name

func (StructuredEditTool) Name() string

func (StructuredEditTool) Parameters

func (StructuredEditTool) Parameters() map[string]interface{}

func (StructuredEditTool) RiskLevel

func (StructuredEditTool) RiskLevel() string

type Task

type Task struct {
	ID           string           `json:"id"`
	ParentID     string           `json:"parentId,omitempty"`
	Subject      string           `json:"subject"`
	Description  string           `json:"description"`
	ActiveForm   string           `json:"activeForm,omitempty"`
	Status       TaskStatus       `json:"status"`
	Owner        string           `json:"owner,omitempty"`
	Dependencies []TaskDependency `json:"dependencies"`
	Metadata     map[string]any   `json:"metadata,omitempty"`
	CreatedAt    time.Time        `json:"createdAt"`
	UpdatedAt    time.Time        `json:"updatedAt"`
}

Task represents a structured task in the task list.

type TaskCreateTool

type TaskCreateTool struct{}

TaskCreateTool creates a new task in the task list.

func (TaskCreateTool) Aliases

func (TaskCreateTool) Aliases() []string

func (TaskCreateTool) Description

func (TaskCreateTool) Description() string

func (TaskCreateTool) Execute

func (TaskCreateTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (TaskCreateTool) Name

func (TaskCreateTool) Name() string

func (TaskCreateTool) Parameters

func (TaskCreateTool) Parameters() map[string]interface{}

type TaskDependency

type TaskDependency struct {
	TargetID string `json:"targetId"`
	Type     string `json:"type"` // "blocks", "related", "parent-child"
}

TaskDependency represents a typed dependency between tasks.

type TaskGetTool

type TaskGetTool struct{}

TaskGetTool retrieves a task by ID.

func (TaskGetTool) Aliases

func (TaskGetTool) Aliases() []string

func (TaskGetTool) Description

func (TaskGetTool) Description() string

func (TaskGetTool) Execute

func (TaskGetTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (TaskGetTool) Name

func (TaskGetTool) Name() string

func (TaskGetTool) Parameters

func (TaskGetTool) Parameters() map[string]interface{}

type TaskListTool

type TaskListTool struct{}

TaskListTool lists all tasks.

func (TaskListTool) Aliases

func (TaskListTool) Aliases() []string

func (TaskListTool) Description

func (TaskListTool) Description() string

func (TaskListTool) Execute

func (TaskListTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (TaskListTool) Name

func (TaskListTool) Name() string

func (TaskListTool) Parameters

func (TaskListTool) Parameters() map[string]interface{}

type TaskOutputTool

type TaskOutputTool struct{}

func (TaskOutputTool) Aliases

func (TaskOutputTool) Aliases() []string

func (TaskOutputTool) Description

func (TaskOutputTool) Description() string

func (TaskOutputTool) Execute

func (TaskOutputTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (TaskOutputTool) Name

func (TaskOutputTool) Name() string

func (TaskOutputTool) Parameters

func (TaskOutputTool) Parameters() map[string]interface{}

type TaskStatus

type TaskStatus string

TaskStatus represents the state of a task.

const (
	TaskStatusPending    TaskStatus = "pending"
	TaskStatusInProgress TaskStatus = "in_progress"
	TaskStatusCompleted  TaskStatus = "completed"
)

type TaskStopTool

type TaskStopTool struct{}

func (TaskStopTool) Aliases

func (TaskStopTool) Aliases() []string

func (TaskStopTool) Description

func (TaskStopTool) Description() string

func (TaskStopTool) Execute

func (TaskStopTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (TaskStopTool) Name

func (TaskStopTool) Name() string

func (TaskStopTool) Parameters

func (TaskStopTool) Parameters() map[string]interface{}

type TaskStore

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

TaskStore is a thread-safe in-memory store for tasks.

func GetTaskStore

func GetTaskStore() *TaskStore

GetTaskStore returns the global task store.

func (*TaskStore) CompactCompleted

func (s *TaskStore) CompactCompleted() string

CompactCompleted removes completed tasks and returns a summary.

func (*TaskStore) Create

func (s *TaskStore) Create(subject, description, activeForm string, metadata map[string]any) *Task

func (*TaskStore) CreateWithParent

func (s *TaskStore) CreateWithParent(subject, description, activeForm string, metadata map[string]any, parentID string) *Task

func (*TaskStore) Delete

func (s *TaskStore) Delete(id string) bool

func (*TaskStore) Get

func (s *TaskStore) Get(id string) (*Task, bool)

func (*TaskStore) GetReadyWork

func (s *TaskStore) GetReadyWork() []*Task

GetReadyWork returns pending tasks with no open blocking dependencies.

func (*TaskStore) List

func (s *TaskStore) List() []*Task

func (*TaskStore) Reset

func (s *TaskStore) Reset()

func (*TaskStore) Update

func (s *TaskStore) Update(id string, fn func(*Task)) bool

type TaskUpdateTool

type TaskUpdateTool struct{}

TaskUpdateTool updates task fields.

func (TaskUpdateTool) Aliases

func (TaskUpdateTool) Aliases() []string

func (TaskUpdateTool) Description

func (TaskUpdateTool) Description() string

func (TaskUpdateTool) Execute

func (TaskUpdateTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (TaskUpdateTool) Name

func (TaskUpdateTool) Name() string

func (TaskUpdateTool) Parameters

func (TaskUpdateTool) Parameters() map[string]interface{}

type TemplateVar

type TemplateVar struct {
	Name        string
	Description string
	Required    bool
	Default     string
}

TemplateVar describes a variable used in a template.

type Ticket

type Ticket struct {
	ID                 string
	Title              string
	Description        string
	AcceptanceCriteria []string
	Labels             []string
	Source             string // "github", "jira", "linear"
}

Ticket represents a linked issue/ticket from any tracking system.

type TicketCompliance

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

TicketCompliance verifies that PR changes satisfy linked issue requirements.

func NewTicketCompliance

func NewTicketCompliance() *TicketCompliance

NewTicketCompliance creates a new TicketCompliance checker.

func (*TicketCompliance) CheckCompliance

func (tc *TicketCompliance) CheckCompliance(ticket *Ticket, diff, commitMessages string) *ComplianceResult

CheckCompliance verifies whether the diff and commit messages satisfy ticket criteria. For each acceptance criterion, it checks if the diff or commits address it using keyword matching.

func (*TicketCompliance) ExtractTicketRef

func (tc *TicketCompliance) ExtractTicketRef(branchName, prDescription string) []string

ExtractTicketRef parses ticket references from branch names and PR descriptions. It recognizes patterns like: #123, PROJ-456, fixes #789, closes #101, feature/PROJ-123-description, "Fixes #42", "Resolves HAWK-99".

func (*TicketCompliance) ParseTicket

func (tc *TicketCompliance) ParseTicket(content string) *Ticket

ParseTicket extracts ticket information from raw content. It parses title, description, and acceptance criteria from issue body text. Acceptance criteria are extracted from:

  • Checkboxes: "- [ ] criterion"
  • Numbered lists: "1. criterion"
  • "should" statements: "The system should ..."

type TicketComplianceTool

type TicketComplianceTool struct{}

TicketComplianceTool implements the Tool interface for ticket compliance checking.

func (*TicketComplianceTool) Description

func (t *TicketComplianceTool) Description() string

Description returns the tool description.

func (*TicketComplianceTool) Execute

func (t *TicketComplianceTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

Execute runs the ticket compliance tool.

func (*TicketComplianceTool) Name

func (t *TicketComplianceTool) Name() string

Name returns the tool name.

func (*TicketComplianceTool) Parameters

func (t *TicketComplianceTool) Parameters() map[string]interface{}

Parameters returns the JSON schema for the tool's input.

type TodoWriteTool

type TodoWriteTool struct{}

func (TodoWriteTool) Aliases

func (TodoWriteTool) Aliases() []string

func (TodoWriteTool) Description

func (TodoWriteTool) Description() string

func (TodoWriteTool) Execute

func (TodoWriteTool) Execute(_ context.Context, input json.RawMessage) (string, error)

func (TodoWriteTool) Name

func (TodoWriteTool) Name() string

func (TodoWriteTool) Parameters

func (TodoWriteTool) Parameters() map[string]interface{}

type Tool

type Tool interface {
	Name() string
	Description() string
	Parameters() map[string]interface{}
	Execute(ctx context.Context, input json.RawMessage) (string, error)
}

Tool is the interface every hawk tool implements.

func LoadMCPTools

func LoadMCPTools(ctx context.Context, name, command string, args ...string) ([]Tool, error)

LoadMCPTools connects to an MCP server and returns hawk tools for all its tools.

type ToolContext

type ToolContext struct {
	AgentSpawnFn       func(ctx context.Context, prompt string) (string, error)
	AskUserFn          func(question string) (string, error)
	CodeSearchFn       func(ctx context.Context, query string, limit int) ([]CodeSearchResult, error)
	RefreshCodeIndexFn func(ctx context.Context) error
	AvailableTools     []Tool
	AllowedDirectories []string
	SandboxMode        sandbox.Mode
	AutoCommit         bool
	Protected          PathProtector
	YaadBridge         *memory.YaadBridge
	Attribution        *types.Attribution
	SettingsGet        func(key string) (string, bool)
	SettingsSet        func(key, value string) error
	// BackgroundManager tracks background sub-agents. If nil, background
	// mode is not available.
	BackgroundManager *BackgroundAgentManager
}

ToolContext carries session-level functions for tools that need them.

func GetToolContext

func GetToolContext(ctx context.Context) *ToolContext

GetToolContext retrieves the ToolContext from a context.

type ToolSearchTool

type ToolSearchTool struct{}

func (ToolSearchTool) Aliases

func (ToolSearchTool) Aliases() []string

func (ToolSearchTool) Description

func (ToolSearchTool) Description() string

func (ToolSearchTool) Execute

func (ToolSearchTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (ToolSearchTool) Name

func (ToolSearchTool) Name() string

func (ToolSearchTool) Parameters

func (ToolSearchTool) Parameters() map[string]interface{}

func (ToolSearchTool) RiskLevel

func (ToolSearchTool) RiskLevel() string

type Transaction

type Transaction struct {
	ID          string
	Operations  []FileOperation
	Status      string // "pending", "committed", "rolled_back"
	CreatedAt   time.Time
	CommittedAt *time.Time
	// contains filtered or unexported fields
}

Transaction groups multiple file operations into an atomic unit. Either all operations succeed or all are rolled back.

func NewTransaction

func NewTransaction() *Transaction

NewTransaction creates a new pending transaction with a unique ID.

func (*Transaction) Add

func (tx *Transaction) Add(op FileOperation) error

Add adds a file operation to the transaction after validating it and capturing the current file state for potential rollback.

func (*Transaction) AddCreate

func (tx *Transaction) AddCreate(path string, content []byte, mode os.FileMode) error

AddCreate adds a file creation operation to the transaction.

func (*Transaction) AddDelete

func (tx *Transaction) AddDelete(path string) error

AddDelete adds a file deletion operation to the transaction. It reads and stores the original content for potential rollback.

func (*Transaction) AddModify

func (tx *Transaction) AddModify(path string, newContent []byte) error

AddModify adds a file modification operation to the transaction. It reads and stores the original content for potential rollback.

func (*Transaction) AddRename

func (tx *Transaction) AddRename(oldPath, newPath string) error

AddRename adds a file rename operation to the transaction.

func (*Transaction) Commit

func (tx *Transaction) Commit() error

Commit applies all operations in order. If any operation fails, all previously applied operations are automatically rolled back.

func (*Transaction) DryRun

func (tx *Transaction) DryRun() []string

DryRun returns descriptions of what each operation would do without applying them.

func (*Transaction) FilesDiff

func (tx *Transaction) FilesDiff() string

FilesDiff returns a unified diff representation of all modifications in the transaction.

func (*Transaction) Rollback

func (tx *Transaction) Rollback() error

Rollback reverses all applied operations, restoring original file states.

func (*Transaction) Summary

func (tx *Transaction) Summary() string

Summary returns a human-readable transaction summary.

func (*Transaction) Validate

func (tx *Transaction) Validate() []string

Validate pre-checks all operations for potential issues without applying them. Returns a list of warnings or an empty slice if everything looks good.

type TransactionTool

type TransactionTool struct{}

TransactionTool implements the Tool interface for atomic multi-file edits.

func (TransactionTool) Aliases

func (TransactionTool) Aliases() []string

func (TransactionTool) Description

func (TransactionTool) Description() string

func (TransactionTool) Execute

func (TransactionTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (TransactionTool) Name

func (TransactionTool) Name() string

func (TransactionTool) Parameters

func (TransactionTool) Parameters() map[string]interface{}

func (TransactionTool) RiskLevel

func (TransactionTool) RiskLevel() string

type TreeSitter

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

TreeSitter provides AST-aware code analysis using tree-sitter WASM grammars. It enables precise code editing by finding exact AST node locations.

func NewTreeSitter

func NewTreeSitter(grammarDir string) *TreeSitter

NewTreeSitter creates a TreeSitter instance that loads grammars from the given directory.

func (*TreeSitter) FindNode

func (ts *TreeSitter) FindNode(ctx context.Context, source, searchText string) (start, end int, err error)

FindNode uses tree-sitter to find a syntax node matching the given search text. Returns the exact byte range in the source for precise editing.

type TypeSig

type TypeSig struct {
	Name     string     `json:"name"`
	Kind     string     `json:"kind"`
	Fields   []FieldSig `json:"fields"`
	Exported bool       `json:"exported"`
}

TypeSig represents a type declaration.

type ValidationCheck

type ValidationCheck struct {
	Name     string
	Category string // "syntax", "lint", "test", "security", "style", "size"
	RunFn    func(files []string) *CheckResult
	Required bool
}

ValidationCheck represents a single validation step in the pre-commit pipeline.

type ValidationReport

type ValidationReport struct {
	Checks           []CheckResult
	AllPassed        bool
	Duration         time.Duration
	BlockingFailures int
	Warnings         int
}

ValidationReport aggregates the results of all checks in a validation run.

type VarSig

type VarSig struct {
	Name     string `json:"name"`
	Type     string `json:"type"`
	Exported bool   `json:"exported"`
}

VarSig represents a variable declaration.

type VerifyPlanExecutionTool

type VerifyPlanExecutionTool struct{}

VerifyPlanExecutionTool checks whether a plan's steps have been executed correctly.

func (VerifyPlanExecutionTool) Aliases

func (VerifyPlanExecutionTool) Aliases() []string

func (VerifyPlanExecutionTool) Description

func (VerifyPlanExecutionTool) Description() string

func (VerifyPlanExecutionTool) Execute

func (VerifyPlanExecutionTool) Name

func (VerifyPlanExecutionTool) Parameters

func (VerifyPlanExecutionTool) Parameters() map[string]interface{}

type WebFetchTool

type WebFetchTool struct{}

func (WebFetchTool) Aliases

func (WebFetchTool) Aliases() []string

func (WebFetchTool) Description

func (WebFetchTool) Description() string

func (WebFetchTool) Execute

func (WebFetchTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (WebFetchTool) Name

func (WebFetchTool) Name() string

func (WebFetchTool) Parameters

func (WebFetchTool) Parameters() map[string]interface{}

type WebSearchTool

type WebSearchTool struct{}

func (WebSearchTool) Aliases

func (WebSearchTool) Aliases() []string

func (WebSearchTool) Description

func (WebSearchTool) Description() string

func (WebSearchTool) Execute

func (WebSearchTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (WebSearchTool) Name

func (WebSearchTool) Name() string

func (WebSearchTool) Parameters

func (WebSearchTool) Parameters() map[string]interface{}

func (WebSearchTool) RiskLevel

func (WebSearchTool) RiskLevel() string

type WorkflowDef

type WorkflowDef struct {
	Name        string         `yaml:"name" json:"name"`
	Description string         `yaml:"description" json:"description"`
	Steps       []WorkflowStep `yaml:"steps" json:"steps"`
}

WorkflowDef defines a scripted workflow loaded from .hawk/workflows/.

func ListWorkflows

func ListWorkflows() []WorkflowDef

ListWorkflows discovers available workflows.

type WorkflowStep

type WorkflowStep struct {
	Name    string `yaml:"name" json:"name"`
	Prompt  string `yaml:"prompt" json:"prompt"`
	Tool    string `yaml:"tool" json:"tool"`
	Input   string `yaml:"input" json:"input"`
	OnError string `yaml:"on_error" json:"on_error"`
}

WorkflowStep is a single step in a workflow.

type WorkflowTool

type WorkflowTool struct{}

WorkflowTool executes scripted workflows from .hawk/workflows/.

func (WorkflowTool) Aliases

func (WorkflowTool) Aliases() []string

func (WorkflowTool) Description

func (WorkflowTool) Description() string

func (WorkflowTool) Execute

func (WorkflowTool) Execute(ctx context.Context, input json.RawMessage) (string, error)

func (WorkflowTool) Name

func (WorkflowTool) Name() string

func (WorkflowTool) Parameters

func (WorkflowTool) Parameters() map[string]interface{}

Jump to

Keyboard shortcuts

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