Documentation
¶
Overview ¶
Package agent handles agent-assisted review via LLM providers.
Index ¶
- Constants
- func ArchitectPhaseNames() []string
- func ArchitectPhasePrompts() []string
- func AutoDetectEnvVars() []string
- func ConservativeModels() []string
- func DefaultGroqModels() []string
- func DefaultLMStudioModels() []string
- func DefaultModels() map[string][]string
- func DefaultOllamaModels() []string
- func DefaultOpenAIModels() []string
- func DetectAPIKey() (key string, envVar string)
- func FormatDeepObservations(result ReviewResult) []string
- func FormatProviderSummary(providers []DetectedProvider) string
- func FormatReviewForRecord(result ReviewResult) string
- func FormatWorkspaceForLLM(snap *WorkspaceArchSnapshot, maxTokensHint int) string
- func GroqModels() []string
- func HasAnyProvider() bool
- func IsDeepReview(result ReviewResult) bool
- func LMStudioModels() []string
- func OllamaModels() []string
- func OpenAIModels() []string
- func ProviderNames(providers []DetectedProvider) []string
- func WorkspacePhaseNames() []string
- func WorkspacePhasePrompts() []string
- type APIError
- type ArchConcern
- type ArchCoverageGap
- type ArchDataFlow
- type ArchDelta
- type ArchFinding
- type ArchLayer
- type ArchPhase1Result
- type ArchPhase2Result
- type ArchPhase3Result
- type ArchPhase4Result
- type ArchPhase5Result
- type ArchPhase6Result
- type ArchRecommendation
- type ArchRisk
- type ArchRoadItem
- type ArchSnapshot
- type ArchitectResult
- type ArchitectReviewer
- type ChatRequest
- type ChatResponse
- type Choice
- type CircuitBreaker
- type CodeMetricsAggregates
- type Coordinator
- type CoordinatorConfig
- type CouplingPair
- type CoverageAggregates
- type CrossDepEdge
- type DecisionResponse
- type DeepAnalysisAggregates
- type DeepReviewResponse
- type DepEdge
- type DetectedProvider
- type FallbackProvider
- type Message
- type ModelChain
- type ModelConfig
- type ModelInfo
- type OpenRouterProvider
- type PackageNode
- type Pipeline
- type PipelineConfig
- type PrescreenResponse
- type ProjectContext
- type PromptRegistry
- type PromptTemplate
- type Provider
- type RateLimiter
- type RemediationResponse
- type RemediationStep
- type RepoSummary
- type ResponseFormat
- type ReviewInput
- type ReviewResult
- type Reviewer
- type Router
- type ScanSuggestion
- type ScoringResponse
- type SnapshotMetrics
- type Stage
- type StageInput
- type StageResult
- type Strategy
- type StructuralAggregates
- type SubmoduleInfo
- type SubmoduleSnapshotEntry
- type TaskType
- type UnitSummary
- type Usage
- type WorkspaceArchSnapshot
- type WorkspaceMetrics
- type WorkspaceProjectContext
Constants ¶
const ( // ConservativeTokenBudget is the max tokens for auto-detected conservative mode. ConservativeTokenBudget = 10_000 // ConservativeCircuitThreshold is the circuit breaker threshold for conservative mode. ConservativeCircuitThreshold = 3 )
const SnapshotSchemaVersion = 3 // v1: PR #20 (structural only), v2: full alignment, v3: deep analysis
SnapshotSchemaVersion tracks the data contract between BuildSnapshot and FormatForLLM. Increment when adding/removing/renaming fields in SnapshotMetrics or its sub-structs.
Variables ¶
This section is empty.
Functions ¶
func ArchitectPhaseNames ¶ added in v0.6.0
func ArchitectPhaseNames() []string
ArchitectPhaseNames returns the phase names (exported for testing).
func ArchitectPhasePrompts ¶ added in v0.6.0
func ArchitectPhasePrompts() []string
ArchitectPhasePrompts returns the system prompts in order (exported for testing).
func AutoDetectEnvVars ¶
func AutoDetectEnvVars() []string
AutoDetectEnvVars returns environment variables checked for cloud API keys, in priority order.
func ConservativeModels ¶
func ConservativeModels() []string
ConservativeModels returns free-tier OpenRouter models in fallback order. These are default suggestions — users can choose any model via config or the extension.
func DefaultGroqModels ¶
func DefaultGroqModels() []string
DefaultGroqModels returns suggested models for Groq.
func DefaultLMStudioModels ¶
func DefaultLMStudioModels() []string
DefaultLMStudioModels returns models for LM Studio.
func DefaultModels ¶
DefaultModels returns the provider-to-models mapping.
func DefaultOllamaModels ¶
func DefaultOllamaModels() []string
DefaultOllamaModels returns common Ollama models.
func DefaultOpenAIModels ¶
func DefaultOpenAIModels() []string
DefaultOpenAIModels returns suggested models for OpenAI.
func DetectAPIKey ¶
DetectAPIKey checks environment variables for an API key (cloud providers). Returns the key and the env var name it was found in. Returns empty strings if no key is found.
func FormatDeepObservations ¶ added in v0.1.4
func FormatDeepObservations(result ReviewResult) []string
FormatDeepObservations creates formatted observation strings from a ReviewResult.
func FormatProviderSummary ¶
func FormatProviderSummary(providers []DetectedProvider) string
FormatProviderSummary returns a human-readable summary of detected providers.
func FormatReviewForRecord ¶ added in v0.1.4
func FormatReviewForRecord(result ReviewResult) string
FormatReviewForRecord creates a compact review summary suitable for record storage.
func FormatWorkspaceForLLM ¶ added in v0.10.0
func FormatWorkspaceForLLM(snap *WorkspaceArchSnapshot, maxTokensHint int) string
FormatWorkspaceForLLM serializes the workspace snapshot for LLM consumption.
func GroqModels ¶
func GroqModels() []string
Backward-compatible aliases (functions returning fresh slices).
func HasAnyProvider ¶
func HasAnyProvider() bool
HasAnyProvider returns true if any provider (cloud or local) is available.
func IsDeepReview ¶ added in v0.1.4
func IsDeepReview(result ReviewResult) bool
IsDeepReview returns true if the result came from a deep review (local model).
func LMStudioModels ¶
func LMStudioModels() []string
func OllamaModels ¶
func OllamaModels() []string
func OpenAIModels ¶
func OpenAIModels() []string
func ProviderNames ¶
func ProviderNames(providers []DetectedProvider) []string
ProviderNames returns the display names of detected providers.
func WorkspacePhaseNames ¶ added in v0.10.0
func WorkspacePhaseNames() []string
WorkspacePhaseNames returns phase names for workspace mode.
func WorkspacePhasePrompts ¶ added in v0.10.0
func WorkspacePhasePrompts() []string
WorkspacePhasePrompts returns the workspace-specific system prompts in order.
Types ¶
type ArchConcern ¶ added in v0.6.0
type ArchConcern struct {
Area string `json:"area"`
Description string `json:"description"`
AffectedPackages []string `json:"affected_packages"`
Metrics map[string]any `json:"metrics"`
}
ArchConcern describes a security or operational concern in the architecture.
type ArchCoverageGap ¶ added in v0.6.0
type ArchCoverageGap struct {
Package string `json:"package"`
CurrentScore float64 `json:"current_score"`
Issue string `json:"issue"`
}
ArchCoverageGap identifies a package with insufficient test coverage.
type ArchDataFlow ¶ added in v0.6.0
type ArchDataFlow struct {
From string `json:"from"`
To string `json:"to"`
Description string `json:"description"`
}
ArchDataFlow describes a data flow between two architectural components.
type ArchDelta ¶ added in v0.6.0
type ArchDelta struct {
Metric string `json:"metric"`
Current string `json:"current"`
Projected string `json:"projected"`
}
ArchDelta captures a before/after comparison for a specific metric.
type ArchFinding ¶ added in v0.6.0
type ArchFinding struct {
Package string `json:"package"`
Issue string `json:"issue"`
CurrentMetrics map[string]float64 `json:"current_metrics"`
Severity string `json:"severity"`
}
ArchFinding describes a code quality finding in a specific package.
type ArchLayer ¶ added in v0.6.0
type ArchLayer struct {
Name string `json:"name"`
Packages []string `json:"packages"`
Description string `json:"description"`
}
ArchLayer describes a logical architecture layer and its constituent packages.
type ArchPhase1Result ¶ added in v0.6.0
type ArchPhase1Result struct {
Layers []ArchLayer `json:"layers"`
DataFlows []ArchDataFlow `json:"data_flows"`
DependencyAssessment string `json:"dependency_assessment"`
}
ArchPhase1Result describes the as-is architecture.
type ArchPhase2Result ¶ added in v0.6.0
type ArchPhase2Result struct {
Findings []ArchFinding `json:"findings"`
}
ArchPhase2Result holds code quality findings.
type ArchPhase3Result ¶ added in v0.6.0
type ArchPhase3Result struct {
CoverageGaps []ArchCoverageGap `json:"coverage_gaps"`
StrategyAssessment string `json:"strategy_assessment"`
}
ArchPhase3Result holds test strategy assessment.
type ArchPhase4Result ¶ added in v0.6.0
type ArchPhase4Result struct {
Concerns []ArchConcern `json:"concerns"`
}
ArchPhase4Result holds security/ops concerns.
type ArchPhase5Result ¶ added in v0.6.0
type ArchPhase5Result struct {
Recommendations []ArchRecommendation `json:"recommendations"`
}
ArchPhase5Result holds comparative recommendations.
type ArchPhase6Result ¶ added in v0.6.0
type ArchPhase6Result struct {
ExecutiveSummary string `json:"executive_summary"`
RiskMatrix []ArchRisk `json:"risk_matrix"`
Roadmap []ArchRoadItem `json:"roadmap"`
}
ArchPhase6Result holds the final synthesis.
type ArchRecommendation ¶ added in v0.6.0
type ArchRecommendation struct {
Title string `json:"title"`
CurrentState string `json:"current_state"`
ProposedState string `json:"proposed_state"`
Deltas []ArchDelta `json:"deltas"`
AffectedUnits []string `json:"affected_units"`
Effort string `json:"effort"`
Justification string `json:"justification"`
}
ArchRecommendation describes a specific improvement with projected impact.
type ArchRisk ¶ added in v0.6.0
type ArchRisk struct {
Risk string `json:"risk"`
Severity string `json:"severity"`
Likelihood string `json:"likelihood"`
RecommendationRef string `json:"recommendation_ref"`
}
ArchRisk describes an architectural risk with severity and likelihood.
type ArchRoadItem ¶ added in v0.6.0
type ArchRoadItem struct {
Priority int `json:"priority"`
Title string `json:"title"`
Effort string `json:"effort"`
Impact string `json:"impact"`
RecommendationRef string `json:"recommendation_ref"`
DeltaSummary string `json:"delta_summary"`
}
ArchRoadItem represents a prioritized improvement item in the roadmap.
type ArchSnapshot ¶ added in v0.6.0
type ArchSnapshot struct {
SchemaVersion int `json:"schema_version"`
Packages []PackageNode // every package with metrics, sorted by path
DependencyEdges []DepEdge // package → package imports
Layers map[string]string // package → layer (cmd, internal, domain, external)
Hotspots []PackageNode // top 10 by risk score (units × (1 - avg_score))
CouplingPairs []CouplingPair // most cross-referenced package pairs
Metrics SnapshotMetrics // aggregate metrics
}
ArchSnapshot captures the current architecture as deterministic data. Computed from certification records — no LLM involved.
func BuildSnapshot ¶ added in v0.6.0
func BuildSnapshot(records []domain.CertificationRecord, root string) *ArchSnapshot
BuildSnapshot computes a deterministic architecture snapshot from certification records. The root parameter is used for Go import analysis (can be empty to skip).
type ArchitectResult ¶ added in v0.6.0
type ArchitectResult struct {
Snapshot *ArchSnapshot
Phase1 *ArchPhase1Result
Phase2 *ArchPhase2Result
Phase3 *ArchPhase3Result
Phase4 *ArchPhase4Result
Phase5 *ArchPhase5Result
Phase6 *ArchPhase6Result
RawOutputs []string // raw LLM responses per phase
Thinking []string // chain-of-thought reasoning per phase (from <think> tags)
TotalTokens int
Duration time.Duration
Model string
PhasesComplete int
Errors []string // errors per failed phase
}
ArchitectResult holds the output of a complete architectural review.
type ArchitectReviewer ¶ added in v0.6.0
type ArchitectReviewer struct {
Provider Provider
Model string
Verbose bool
OnPhaseStart func(phase int, name string)
OnPhaseDone func(phase int, name string, tokens int)
}
ArchitectReviewer orchestrates the 6-phase architectural review pipeline.
func (*ArchitectReviewer) Review ¶ added in v0.6.0
func (ar *ArchitectReviewer) Review(ctx context.Context, pc *ProjectContext, phases []int) (*ArchitectResult, error)
Review runs the 6-phase architectural review pipeline. Phases can be limited with the phases parameter (nil = all, else list of 1-indexed phase numbers).
func (*ArchitectReviewer) ReviewWorkspace ¶ added in v0.10.0
func (ar *ArchitectReviewer) ReviewWorkspace(ctx context.Context, wpc *WorkspaceProjectContext, phases []int) (*ArchitectResult, error)
ReviewWorkspace runs the 6-phase review with workspace-specific prompts and context.
type ChatRequest ¶
type ChatRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Temperature float64 `json:"temperature,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
// ResponseFormat can request structured JSON output
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
}
ChatRequest is an OpenAI-compatible chat completion request.
type ChatResponse ¶
type ChatResponse struct {
ID string `json:"id"`
Model string `json:"model"`
Choices []Choice `json:"choices"`
Usage Usage `json:"usage"`
}
ChatResponse is an OpenAI-compatible chat completion response.
func (ChatResponse) Content ¶
func (r ChatResponse) Content() string
Content returns the first choice's message content, or empty string.
type Choice ¶
type Choice struct {
Index int `json:"index"`
Message Message `json:"message"`
FinishReason string `json:"finish_reason"`
}
Choice represents a single completion choice.
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker wraps a Provider and stops calling it after consecutive failures.
func NewCircuitBreaker ¶
func NewCircuitBreaker(provider Provider, threshold int) *CircuitBreaker
NewCircuitBreaker wraps a provider with a circuit breaker. After `threshold` consecutive failures, the circuit opens and all calls return immediately with an error until a successful call closes it.
func (*CircuitBreaker) Chat ¶
func (cb *CircuitBreaker) Chat(ctx context.Context, req ChatRequest) (ChatResponse, error)
Chat delegates to the wrapped provider unless the circuit is open.
func (*CircuitBreaker) IsOpen ¶
func (cb *CircuitBreaker) IsOpen() bool
IsOpen returns true if the circuit is currently open.
func (*CircuitBreaker) Name ¶
func (cb *CircuitBreaker) Name() string
Name returns the wrapped provider's name.
type CodeMetricsAggregates ¶ added in v0.9.0
type CodeMetricsAggregates struct {
TotalCodeLines int `json:"total_code_lines"`
TotalCommentLines int `json:"total_comment_lines"`
TotalComplexity int `json:"total_complexity"`
MaxComplexity int `json:"max_complexity"`
AvgComplexity float64 `json:"avg_complexity"`
TotalTodos int `json:"total_todos"`
}
CodeMetricsAggregates holds aggregated code metrics across all units.
type Coordinator ¶
type Coordinator struct {
// contains filtered or unexported fields
}
Coordinator manages file-level dedup, token budgets, and pipeline execution.
func NewConservativeCoordinator ¶
func NewConservativeCoordinator(providers []DetectedProvider) *Coordinator
NewConservativeCoordinator builds a Coordinator from all detected providers. Uses StrategyQuick (prescreen only), conservative token budget, free-tier models. Cloud providers are tried first, then local providers as fallback.
func NewCoordinator ¶
func NewCoordinator(provider Provider, cfg CoordinatorConfig) *Coordinator
NewCoordinator creates a review coordinator.
func (*Coordinator) IsLocal ¶ added in v0.1.4
func (c *Coordinator) IsLocal() bool
IsLocal returns true if the coordinator is using a local strategy.
func (*Coordinator) ReviewUnit ¶
func (c *Coordinator) ReviewUnit(ctx context.Context, unit domain.Unit, source string, ev []domain.Evidence) ReviewResult
ReviewUnit returns the review result for a unit, deduplicating by file.
func (*Coordinator) Stats ¶
func (c *Coordinator) Stats() (filesReviewed, totalFiles, tokensSpent int)
Stats returns coordinator statistics.
type CoordinatorConfig ¶
type CoordinatorConfig struct {
Models domain.ModelAssignments
Strategy Strategy
TokenBudget int // max tokens to spend across all reviews (0=unlimited)
}
CoordinatorConfig configures the review coordinator.
type CouplingPair ¶ added in v0.6.0
type CouplingPair struct {
PkgA string `json:"pkg_a"`
PkgB string `json:"pkg_b"`
EdgeCount int `json:"edge_count"` // total edges both directions
}
CouplingPair represents two packages with high bidirectional coupling.
type CoverageAggregates ¶ added in v0.9.0
type CoverageAggregates struct {
UnitsWithCoverage int `json:"units_with_coverage"`
UnitsWithoutCoverage int `json:"units_without_coverage"`
AvgCoverage float64 `json:"avg_coverage"`
MinCoverage float64 `json:"min_coverage"`
MaxCoverage float64 `json:"max_coverage"`
}
CoverageAggregates holds aggregated test coverage data across all units.
type CrossDepEdge ¶ added in v0.10.0
type CrossDepEdge struct {
FromSubmodule string `json:"from_submodule"`
ToSubmodule string `json:"to_submodule"`
Evidence string `json:"evidence"`
Weight int `json:"weight"`
}
CrossDepEdge represents a dependency between two submodules.
type DecisionResponse ¶
type DecisionResponse struct {
Status string `json:"status"`
Reasoning string `json:"reasoning"`
Actions []string `json:"actions"`
}
DecisionResponse is the structured output from the decision step.
type DeepAnalysisAggregates ¶ added in v0.12.0
type DeepAnalysisAggregates struct {
AvgFanIn float64 `json:"avg_fan_in"`
MaxFanIn int `json:"max_fan_in"`
AvgFanOut float64 `json:"avg_fan_out"`
MaxFanOut int `json:"max_fan_out"`
DeadExportCount int `json:"dead_export_count"`
ConcreteDepsCount int `json:"concrete_deps_count"`
AvgCogComplexity float64 `json:"avg_cognitive_complexity"`
MaxCogComplexity int `json:"max_cognitive_complexity"`
ErrorsNotWrapped int `json:"errors_not_wrapped"`
UnsafeImportCount int `json:"unsafe_import_count"`
HardcodedSecrets int `json:"hardcoded_secrets"`
MaxDepDepth int `json:"max_dep_depth"`
AvgInstability float64 `json:"avg_instability"`
UnitsWithDeepData int `json:"units_with_deep_data"`
}
DeepAnalysisAggregates holds aggregated type-aware metrics from deep analysis.
type DeepReviewResponse ¶ added in v0.1.4
type DeepReviewResponse struct {
Summary string `json:"summary"`
Review string `json:"review"`
Risks []string `json:"risks"`
SystemImpact []string `json:"system_impact"`
Suggestions []string `json:"suggestions"`
Strengths []string `json:"strengths"`
}
DeepReviewResponse is the structured output from deep review.
type DepEdge ¶ added in v0.6.0
type DepEdge struct {
From string `json:"from"`
To string `json:"to"`
Weight int `json:"weight"` // number of import sites
}
DepEdge represents an import dependency between two packages.
type DetectedProvider ¶
type DetectedProvider struct {
Name string // "openrouter", "groq", "ollama", "lmstudio"
BaseURL string // API base URL
APIKey string // API key (empty for local providers)
Models []string // Preferred models for this provider
Local bool // True for local providers (no auth required)
}
DetectedProvider describes an auto-detected LLM provider.
func DetectProviders ¶
func DetectProviders() []DetectedProvider
DetectProviders checks for available LLM providers in priority order. Cloud providers (requiring API keys) come first, local providers last.
type FallbackProvider ¶
type FallbackProvider struct {
// contains filtered or unexported fields
}
FallbackProvider tries multiple providers in order until one succeeds. Only retryable errors (429, 5xx) trigger fallback; auth errors abort immediately.
func NewFallbackProvider ¶
func NewFallbackProvider(providers []Provider) *FallbackProvider
NewFallbackProvider creates a provider that falls back through a list.
func (*FallbackProvider) Chat ¶
func (f *FallbackProvider) Chat(ctx context.Context, req ChatRequest) (ChatResponse, error)
func (*FallbackProvider) Name ¶
func (f *FallbackProvider) Name() string
Name returns the provider identifier for the fallback provider.
type Message ¶
Message represents a chat message (OpenAI-compatible).
func AdaptiveMessages ¶
AdaptiveMessages builds a message list that works with or without system message support. When useSystem=true, sends separate system + user messages. When useSystem=false, combines system instruction into the user message.
type ModelChain ¶
type ModelChain struct {
// contains filtered or unexported fields
}
ModelChain creates a FallbackProvider with one OpenRouterProvider per model. Each provider is configured with longer backoff suitable for free-tier rate limits.
func NewModelChain ¶
func NewModelChain(baseURL, apiKey, referer, title string, models []string) *ModelChain
NewModelChain creates a chain of model-specific providers. When model A returns 429, automatically tries model B, etc.
func (*ModelChain) Chat ¶
func (mc *ModelChain) Chat(ctx context.Context, req ChatRequest) (ChatResponse, error)
func (*ModelChain) Name ¶
func (mc *ModelChain) Name() string
Name returns the provider identifier for the model chain.
type ModelConfig ¶
type ModelConfig struct {
ID string `json:"id"`
ContextWindow int `json:"context_window"`
MaxOutput int `json:"max_output"`
StructuredOutputs bool `json:"structured_outputs"`
ToolCalling bool `json:"tool_calling"`
Reasoning bool `json:"reasoning"`
}
ModelConfig describes a model's capabilities.
type ModelInfo ¶
type ModelInfo struct {
ID string `json:"id"`
OwnedBy string `json:"owned_by,omitempty"`
ContextWindow int `json:"context_window,omitempty"`
Created int64 `json:"created,omitempty"`
}
ModelInfo describes a model available from a provider.
type OpenRouterProvider ¶
type OpenRouterProvider struct {
// contains filtered or unexported fields
}
OpenRouterProvider implements Provider for the OpenRouter API. Also works with any OpenAI-compatible endpoint (Groq, Ollama, LM Studio).
func NewLocalProvider ¶
func NewLocalProvider(baseURL, name string) *OpenRouterProvider
NewLocalProvider creates a provider for local OpenAI-compatible servers (Ollama, LM Studio). No API key required, no auth headers sent.
func NewOpenRouterProvider ¶
func NewOpenRouterProvider(baseURL, apiKey, httpReferer, xTitle string) *OpenRouterProvider
NewOpenRouterProvider creates a new OpenRouter provider.
func (*OpenRouterProvider) Chat ¶
func (p *OpenRouterProvider) Chat(ctx context.Context, req ChatRequest) (ChatResponse, error)
Chat sends a chat completion request with retry logic.
func (*OpenRouterProvider) Name ¶
func (p *OpenRouterProvider) Name() string
Name returns the provider name.
func (*OpenRouterProvider) SetTimeout ¶ added in v0.6.0
func (p *OpenRouterProvider) SetTimeout(d time.Duration)
SetTimeout overrides the HTTP client timeout. Use for long-running requests like architectural reviews with local models.
type PackageNode ¶ added in v0.6.0
type PackageNode struct {
Path string `json:"path"`
Units int `json:"units"`
AvgScore float64 `json:"avg_score"`
Grade string `json:"grade"`
Observations int `json:"observations"`
TopIssues []string `json:"top_issues,omitempty"`
Imports []string `json:"imports,omitempty"`
ImportedBy []string `json:"imported_by,omitempty"`
ExportedAPI []string `json:"exported_api,omitempty"`
}
PackageNode holds metrics for a single package directory.
type Pipeline ¶
type Pipeline struct {
// contains filtered or unexported fields
}
Pipeline orchestrates review stages in sequence.
func NewPipeline ¶
func NewPipeline(provider Provider, cfg PipelineConfig) *Pipeline
NewPipeline builds a pipeline based on strategy and model assignments.
func (*Pipeline) Run ¶
func (p *Pipeline) Run(ctx context.Context, input StageInput) (ReviewResult, error)
Run executes the pipeline stages in order. Each stage can short-circuit (stop the pipeline). Errors cause graceful degradation, not failure.
type PipelineConfig ¶
type PipelineConfig struct {
Strategy Strategy
Models domain.ModelAssignments
}
PipelineConfig configures the review pipeline.
type PrescreenResponse ¶
type PrescreenResponse struct {
NeedsReview bool `json:"needs_review"`
Reason string `json:"reason"`
Confidence float64 `json:"confidence"`
Suggestions []string `json:"suggestions,omitempty"`
}
PrescreenResponse is the structured output from the prescreen step.
type ProjectContext ¶ added in v0.6.0
type ProjectContext struct {
RepoName string
CommitSHA string
Languages []string
Snapshot *ArchSnapshot
LowestUnits []UnitSummary // bottom 20 by score
Documentation map[string]string // filename → content (README, PRD, etc.)
FileTree string
PolicyRules []string
GitSummary string
}
ProjectContext aggregates everything the architect reviewer needs.
func GatherContext ¶ added in v0.6.0
func GatherContext(root, certDir string, records []domain.CertificationRecord) (*ProjectContext, error)
GatherContext assembles a ProjectContext from certification records and the filesystem.
func (*ProjectContext) FormatForLLM ¶ added in v0.6.0
func (pc *ProjectContext) FormatForLLM(maxTokensHint int) string
FormatForLLM serializes the project context into a structured text block for LLM consumption. maxTokensHint suggests a target size (~4 chars per token).
type PromptRegistry ¶
type PromptRegistry struct {
// contains filtered or unexported fields
}
PromptRegistry loads and caches prompt templates by task type.
func NewPromptRegistry ¶
func NewPromptRegistry(dir string) *PromptRegistry
NewPromptRegistry creates a registry that loads templates from a directory.
func (*PromptRegistry) Get ¶
func (r *PromptRegistry) Get(task TaskType) (*PromptTemplate, error)
Get returns the prompt template for a task type, loading and caching on first access.
type PromptTemplate ¶
type PromptTemplate struct {
// contains filtered or unexported fields
}
PromptTemplate is a loaded prompt template with variable substitution.
func LoadPrompt ¶
func LoadPrompt(path string) (*PromptTemplate, error)
LoadPrompt loads a prompt template from a file.
func (*PromptTemplate) Render ¶
func (p *PromptTemplate) Render(vars map[string]string) (string, error)
Render substitutes variables into the template. Variables are specified as {{.Key}} in the template.
func (*PromptTemplate) Version ¶
func (p *PromptTemplate) Version() string
Version extracts the version from the filename (e.g., "prescreen.v1.md" → "v1").
type Provider ¶
type Provider interface {
// Chat sends a chat completion request and returns the response.
Chat(ctx context.Context, req ChatRequest) (ChatResponse, error)
// Name returns the provider name.
Name() string
}
Provider is the interface for LLM API providers.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a simple token bucket rate limiter.
func NewRateLimiter ¶
func NewRateLimiter(maxRate int, interval time.Duration) *RateLimiter
NewRateLimiter creates a rate limiter that allows maxRate requests per interval.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow() bool
Allow checks if a request is allowed (non-blocking).
type RemediationResponse ¶
type RemediationResponse struct {
Steps []RemediationStep `json:"steps"`
}
RemediationResponse is the structured output from the remediation step.
type RemediationStep ¶
type RemediationStep struct {
Priority int `json:"priority"`
Dimension string `json:"dimension"`
Description string `json:"description"`
Effort string `json:"effort"` // low, medium, high
}
RemediationStep is a single remediation action.
type RepoSummary ¶
type RepoSummary struct {
Languages []string // Detected languages (e.g., "go", "typescript")
UnitCount int // Total code units discovered
FilePatterns []string // Top-level directories or patterns found
Policies []string // Currently configured policy pack names
}
RepoSummary holds repository metadata for generating AI suggestions.
type ResponseFormat ¶
type ResponseFormat struct {
Type string `json:"type"` // "json_object" or "json_schema"
Schema any `json:"json_schema,omitempty"`
}
ResponseFormat requests a specific output format.
type ReviewInput ¶
ReviewInput holds everything needed for an agent review.
type ReviewResult ¶
type ReviewResult struct {
Reviewed bool `json:"reviewed"`
Prescreened bool `json:"prescreened"`
ReviewOutput string `json:"review_output,omitempty"`
Scores map[string]float64 `json:"scores,omitempty"`
Status string `json:"status,omitempty"`
Actions []string `json:"actions,omitempty"`
Remediation []RemediationStep `json:"remediation,omitempty"`
Confidence float64 `json:"confidence"`
TokensUsed int `json:"tokens_used"`
ModelsUsed []string `json:"models_used,omitempty"`
PrescreenReason string `json:"prescreen_reason,omitempty"`
Suggestions []string `json:"suggestions,omitempty"`
}
ReviewResult holds the outcome of an agent review.
func (ReviewResult) ToDeepEvidence ¶ added in v0.1.4
func (r ReviewResult) ToDeepEvidence() domain.Evidence
ToDeepEvidence creates evidence from a deep review result.
func (ReviewResult) ToEvidence ¶
func (r ReviewResult) ToEvidence() domain.Evidence
ToEvidence converts the review result to a domain.Evidence. Model attribution is embedded in the Source field.
func (ReviewResult) ToPrescreenEvidence ¶ added in v0.1.3
func (r ReviewResult) ToPrescreenEvidence() domain.Evidence
ToPrescreenEvidence converts a prescreen-only result to evidence. Used when AI evaluated but determined no detailed review was needed.
type Reviewer ¶
type Reviewer struct {
// contains filtered or unexported fields
}
Reviewer orchestrates the 5-step agent review pipeline.
func NewReviewer ¶
NewReviewer creates a new agent reviewer.
func (*Reviewer) Review ¶
func (rv *Reviewer) Review(ctx context.Context, input ReviewInput) (ReviewResult, error)
Review runs the full agent review pipeline.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router maps task types to specific models with fallback.
func NewRouter ¶
func NewRouter(assignments domain.ModelAssignments) *Router
NewRouter creates a model router.
type ScanSuggestion ¶
type ScanSuggestion struct {
Suggestions string // Human-readable suggestion text
TokensUsed int // Tokens consumed by this call
Model string // Model that generated the suggestion
}
ScanSuggestion holds the result of an AI-powered scan suggestion.
func SuggestForRepo ¶
func SuggestForRepo(ctx context.Context, provider Provider, summary RepoSummary) ScanSuggestion
SuggestForRepo sends a single LLM call to generate policy/scope suggestions based on the repository summary. Returns empty ScanSuggestion on any failure (graceful degradation — never blocks, never errors).
type ScoringResponse ¶
type ScoringResponse struct {
Scores map[string]float64 `json:"scores"`
Confidence float64 `json:"confidence"`
Reasoning string `json:"reasoning"`
}
ScoringResponse is the structured output from the scoring step.
type SnapshotMetrics ¶ added in v0.6.0
type SnapshotMetrics struct {
TotalUnits int `json:"total_units"`
TotalPackages int `json:"total_packages"`
AvgScore float64 `json:"avg_score"`
GradeDistribution map[string]int `json:"grade_distribution"`
TopObservations map[string]int `json:"top_observations"`
PolicyViolations map[string]int `json:"policy_violations"`
Structural StructuralAggregates `json:"structural"`
DeepAnalysis DeepAnalysisAggregates `json:"deep_analysis"`
Coverage CoverageAggregates `json:"coverage"`
CodeMetrics CodeMetricsAggregates `json:"code_metrics"`
}
SnapshotMetrics holds aggregate metrics across all packages.
type Stage ¶
type Stage interface {
Execute(ctx context.Context, input StageInput) (StageResult, bool, error)
Name() string
}
Stage is a single step in the review pipeline. Returns (result, shouldContinue, error).
func NewDeepReviewStage ¶ added in v0.1.4
NewDeepReviewStage creates a comprehensive review stage for local models. Unlike the standard prescreen→review flow, this always performs a full analysis since local model tokens are free.
func NewPrescreenStage ¶
NewPrescreenStage creates the prescreen gate stage.
func NewReviewStage ¶
NewReviewStage creates the detailed code review stage.
func NewScoringStage ¶
NewScoringStage creates the dimension scoring stage.
type StageInput ¶
type StageInput struct {
Unit domain.Unit
SourceCode string
Evidence []domain.Evidence
EvidenceSummary string
ReviewOutput string // set by ReviewStage, read by ScoringStage
}
StageInput holds all data flowing through the pipeline.
type StageResult ¶
type StageResult struct {
Reviewed bool
ReviewOutput string
Scores map[string]float64
Status string
Actions []string
Remediation []RemediationStep
Confidence float64
TokensUsed int
ModelsUsed []string // attribution: which models contributed
PrescreenReason string // brief quality assessment from prescreen
Suggestions []string // actionable improvement suggestions
}
StageResult accumulates output from pipeline stages.
type Strategy ¶
type Strategy int
Strategy determines how many pipeline stages to execute.
const ( // StrategyQuick runs prescreen only — cheap gate. StrategyQuick Strategy = iota // StrategyStandard runs prescreen → review → scoring (3 stages). StrategyStandard // StrategyFull runs all 5 stages including decision and remediation. StrategyFull // StrategyLocal skips prescreen gate, runs deep review → scoring. // Designed for local models with zero token cost. StrategyLocal )
type StructuralAggregates ¶ added in v0.9.0
type StructuralAggregates struct {
PanicCalls int `json:"panic_calls"`
OsExitCalls int `json:"os_exit_calls"`
GlobalMutableCount int `json:"global_mutable_count"`
DeferInLoop int `json:"defer_in_loop"`
InitFuncCount int `json:"init_func_count"`
ContextNotFirst int `json:"context_not_first"`
ErrorsIgnored int `json:"errors_ignored"`
NakedReturns int `json:"naked_returns"`
RecursiveCalls int `json:"recursive_calls"`
MaxNestingDepth int `json:"max_nesting_depth"`
NestedLoopPairs int `json:"nested_loop_pairs"`
QuadraticPatterns int `json:"quadratic_patterns"`
TotalFuncLines int `json:"total_func_lines"`
TotalParams int `json:"total_params"`
TotalReturns int `json:"total_returns"`
TotalMethods int `json:"total_methods"`
}
StructuralAggregates holds summed structural metrics across all units. These are computed from Evidence.Metrics in certification records, providing the LLM with real data instead of requiring it to guess.
type SubmoduleInfo ¶ added in v0.10.0
type SubmoduleInfo struct {
Name string
Path string
Commit string
Records []domain.CertificationRecord
}
SubmoduleInfo holds the input data for building a workspace snapshot. This is populated by the CLI from workspace.Submodule + loaded records.
type SubmoduleSnapshotEntry ¶ added in v0.10.0
type SubmoduleSnapshotEntry struct {
Name string `json:"name"`
Path string `json:"path"`
Commit string `json:"commit"`
Snapshot *ArchSnapshot `json:"snapshot"`
Role string `json:"role"` // "service", "library", "tool", "infrastructure"
}
SubmoduleSnapshotEntry holds a per-submodule architecture snapshot.
type UnitSummary ¶ added in v0.6.0
UnitSummary is a lightweight unit representation for LLM context.
type Usage ¶
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
Usage reports token consumption.
type WorkspaceArchSnapshot ¶ added in v0.10.0
type WorkspaceArchSnapshot struct {
SchemaVersion int `json:"schema_version"`
SubmoduleSnapshots []SubmoduleSnapshotEntry `json:"submodule_snapshots"`
CrossDependencies []CrossDepEdge `json:"cross_dependencies"`
InfraFiles []string `json:"infra_files"`
AggregateMetrics WorkspaceMetrics `json:"aggregate_metrics"`
}
WorkspaceArchSnapshot extends the architecture snapshot with cross-submodule data.
func BuildWorkspaceSnapshot ¶ added in v0.10.0
func BuildWorkspaceSnapshot(root string, subs []SubmoduleInfo) *WorkspaceArchSnapshot
BuildWorkspaceSnapshot builds a workspace-level architecture snapshot from submodule info. Each submodule gets its own ArchSnapshot built from its certification records.
type WorkspaceMetrics ¶ added in v0.10.0
type WorkspaceMetrics struct {
TotalSubmodules int `json:"total_submodules"`
ConfiguredSubmodules int `json:"configured_submodules"`
TotalUnitsAcrossAll int `json:"total_units_across_all"`
WeightedAvgScore float64 `json:"weighted_avg_score"`
WorstSubmodule string `json:"worst_submodule"`
BestSubmodule string `json:"best_submodule"`
}
WorkspaceMetrics holds aggregate metrics across all submodules.
type WorkspaceProjectContext ¶ added in v0.10.0
type WorkspaceProjectContext struct {
RepoName string
CommitSHA string
Snapshot *WorkspaceArchSnapshot
Documentation map[string]string // workspace-level docs
}
WorkspaceProjectContext holds everything needed for a workspace-level architect review.
func GatherWorkspaceContext ¶ added in v0.10.0
func GatherWorkspaceContext(root string, subs []SubmoduleInfo) *WorkspaceProjectContext
GatherWorkspaceContext assembles a WorkspaceProjectContext for architect review.