core

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MaxIterationsPerFile is the recommended number of ReAct loop iterations to
	// allocate per changed file in the diff.
	MaxIterationsPerFile = 5
	// AbsoluteMaxIter is the hard upper bound for the ReAct loop to prevent
	// infinite recursion or excessive token spend.
	AbsoluteMaxIter = 25
	// MaxToolConcurrency is the maximum number of tools allowed to run
	// in parallel in a single turn.
	MaxToolConcurrency = 8
	// MaxToolResultBytes is the hard upper bound for any individual tool result
	// to prevent context window overflow on large outputs.
	MaxToolResultBytes = 50000
)

Variables

View Source
var (
	// ErrSessionNotFound is returned when the session directory or messages file does not exist.
	ErrSessionNotFound = errors.New("session not found")
	// ErrSessionEmpty is returned when the session messages file contains no valid messages.
	ErrSessionEmpty = errors.New("session is empty")
)
View Source
var StructuredReviewSchema = map[string]any{
	"type": "object",
	"properties": map[string]any{
		"approval": map[string]any{
			"type": "object",
			"properties": map[string]any{
				"approved": map[string]any{
					"type":        "boolean",
					"description": "Whether the changes are approved for merging.",
				},
				"rationale": map[string]any{
					"type":        "string",
					"description": "The high-level reasoning for the approval or rejection.",
				},
				"action": map[string]any{
					"type":        "string",
					"description": "The GitHub review action: 'APPROVE' if approved, 'REQUEST_CHANGES' if there are issues, or 'COMMENT' for neutral feedback.",
					"enum":        []string{"APPROVE", "REQUEST_CHANGES", "COMMENT"},
				},
			},
			"required": []string{"approved", "rationale", "action"},
		},
		"non_specific_review": map[string]any{
			"type":        "string",
			"description": "General review notes that are not tied to specific files or line ranges.",
		},
		"files_review": map[string]any{
			"type": "array",
			"items": map[string]any{
				"type": "object",
				"properties": map[string]any{
					"path": map[string]any{
						"type":        "string",
						"description": "The relative path to the file being reviewed.",
					},
					"lines": map[string]any{
						"type":        "string",
						"description": "The specific line number (e.g., '42') or range (e.g., '10-25') this review applies to.",
					},
					"review": map[string]any{
						"type":        "string",
						"description": "The detailed feedback for this specific chunk of code.",
					},
				},
				"required": []string{"path", "review"},
			},
		},
	},
	"required": []string{"approval", "files_review"},
}

StructuredReviewSchema is the JSON Schema representation of StructuredReview. This is used by LLM providers to enforce the output format. Note: raw_free_text is excluded from the schema to save tokens; it is populated manually by the caller.

Functions

func CalculateMaxIterations

func CalculateMaxIterations(changedFiles int) int

CalculateMaxIterations returns a sensible iteration cap based on the number of changed files, bounded by AbsoluteMaxIter.

func WithTestREPLStreams added in v0.6.0

func WithTestREPLStreams(ctx context.Context, in io.Reader, err io.Writer) context.Context

WithTestREPLStreams wraps a context to override standard input/stderr of the interactive REPL.

Types

type ACPOption added in v0.8.0

type ACPOption func(*acpReporter)

ACPOption configures an acpReporter.

func WithACPSessionID added in v0.8.0

func WithACPSessionID(id acp.SessionId) ACPOption

WithACPSessionID sets an initial session ID on the acpReporter.

func WithACPSessionStore added in v0.8.0

func WithACPSessionStore(store SessionStore) ACPOption

WithACPSessionStore sets a SessionStore on the acpReporter for session persistence and loading.

type Agent

type Agent struct {
	Stage string
	// contains filtered or unexported fields
}

Agent orchestrates the ReAct (Reason + Act) loop between the LLM and the tool registry.

func NewAgent

func NewAgent(model llm.Model, registry ToolDispatcher, opts ...AgentOption) *Agent

NewAgent creates an Agent. Diagnostic / progress output goes to os.Stderr by default; override with WithStderr or WithReporter. The final review is returned as a string (caller routes it to stdout).

func (*Agent) ExtractStructuredReview

func (a *Agent) ExtractStructuredReview(ctx context.Context, extractionSystemPrompt, rawReview string, config llm.StructuredConfig) (*StructuredReview, error)

ExtractStructuredReview takes a raw markdown review and converts it into a machine-readable StructuredReview using a second LLM pass. Hard LLM errors are returned immediately (the underlying RetryingModel has already exhausted its own retry budget for them). Only soft application-level failures — empty content and malformed JSON — are retried here, up to extractionMaxAttempts times total, to overcome non-determinism in LLM output.

func (*Agent) GetMetrics added in v0.4.0

func (a *Agent) GetMetrics() SessionMetrics

GetMetrics returns the collected usage and execution metrics for the session.

func (*Agent) History added in v0.8.0

func (a *Agent) History() []llm.Message

History returns a copy of the Agent's conversation history.

func (*Agent) Reporter added in v0.5.0

func (a *Agent) Reporter() Reporter

Reporter returns the Agent's reporter.

func (*Agent) ResetMetrics added in v0.7.0

func (a *Agent) ResetMetrics()

ResetMetrics clears all collected metrics (usage, tool calls, iterations) on the Agent.

func (*Agent) RunChatFlight added in v0.6.0

func (a *Agent) RunChatFlight(ctx context.Context, userText string, maxIterations, maxTokens int) (reply string, err error)

RunChatFlight executes the conversational ReAct loop for a single chat turn in the REPL. If the turn fails or is canceled before completion, any messages appended to a.history during the turn are rolled back so history role alternation stays valid.

func (*Agent) RunReview

func (a *Agent) RunReview(ctx context.Context, stableSystem, dynamicSystem, requestText string, maxIterations, maxTokens int) (string, error)

RunReview executes the ReAct loop. stableSystem is the stable prompt prefix (Zones 1+2); dynamicSystem is the per-PR dynamic suffix (Zone 3, e.g. AGENTS.md / REVIEWERS.md content). When dynamicSystem is non-empty, providers that support prompt caching (e.g. Anthropic) will cache the stable prefix. Pass an empty string for dynamicSystem when there is no per-PR dynamic content. maxIterations controls how many tool-call rounds are permitted before the loop is forcibly terminated. Pass 0 to use the default cap. maxTokens limits the length of the LLM response.

func (*Agent) SetHistory added in v0.8.0

func (a *Agent) SetHistory(msgs []llm.Message)

SetHistory replaces the Agent's conversation history.

func (*Agent) SetSession added in v0.8.0

func (a *Agent) SetSession(store SessionStore, sessionID string)

SetSession sets or updates the SessionStore and session ID on the Agent.

type AgentOption

type AgentOption func(*Agent)

AgentOption configures an Agent.

func WithEmptyResponseRetryDelay added in v0.9.0

func WithEmptyResponseRetryDelay(d time.Duration) AgentOption

WithEmptyResponseRetryDelay configures the delay between retries when an LLM returns empty content.

func WithReporter

func WithReporter(r Reporter) AgentOption

WithReporter sets a custom reporter for the Agent.

func WithSessionStore added in v0.8.0

func WithSessionStore(store SessionStore, sessionID string) AgentOption

WithSessionStore configures the Agent to persist conversation messages to the given SessionStore.

func WithStderr

func WithStderr(w io.Writer) AgentOption

WithStderr redirects diagnostic/progress output to w instead of os.Stderr. Useful in tests to suppress noise (pass io.Discard).

type Approval

type Approval struct {
	Approved  bool   `json:"approved"`
	Rationale string `json:"rationale"`
	Action    string `json:"action,omitempty"` // The GitHub review action: "APPROVE", "REQUEST_CHANGES", "COMMENT".
}

Approval represents the overall decision on the code changes.

type ConcreteSessionStore added in v0.8.0

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

ConcreteSessionStore persists session conversation history as JSONL under configFolder/sessions/<session-id>/messages.jsonl.

func NewConcreteSessionStore added in v0.8.0

func NewConcreteSessionStore(baseDir string) *ConcreteSessionStore

NewConcreteSessionStore creates a ConcreteSessionStore rooted at baseDir.

func (*ConcreteSessionStore) AppendMessages added in v0.8.0

func (s *ConcreteSessionStore) AppendMessages(ctx context.Context, sessionID string, msgs ...llm.Message) error

func (*ConcreteSessionStore) LoadSession added in v0.8.0

func (s *ConcreteSessionStore) LoadSession(ctx context.Context, sessionID string) ([]llm.Message, error)

func (*ConcreteSessionStore) SessionExists added in v0.8.0

func (s *ConcreteSessionStore) SessionExists(sessionID string) bool

type ConsoleFormatter added in v0.6.0

type ConsoleFormatter interface {
	NotifyUser() string
	FormatToolCalls(tcs []llm.ToolCall) string
	FormatReviewHeader(files int, guidelines, model string) string
	FormatConfig(cfg *config.Config, targetDir string) string
	FormatReview(result string) string
	StyleStderr(plain, styled string, color string, bold bool) string
	FormatPostReviewReply(message string) string
	FormatPostReviewUserQuery(query string, width int) string
}

ConsoleFormatter abstracts formatting and styling for console output.

type FileReview

type FileReview struct {
	Path   string `json:"path"`
	Lines  string `json:"lines,omitempty"` // A single line ("42") or a single range ("10-25").
	Review string `json:"review"`
}

FileReview represents feedback for a specific part of a file.

func (*FileReview) ParseLines

func (fr *FileReview) ParseLines() (int, int, error)

ParseLines parses the 'lines' string into individual line numbers. Returns startLine and endLine. For single lines, startLine == endLine.

type NoopSessionStore added in v0.8.0

type NoopSessionStore struct{}

NoopSessionStore is a no-op SessionStore used when configFolder is unset.

func NewNoopSessionStore added in v0.8.0

func NewNoopSessionStore() *NoopSessionStore

func (*NoopSessionStore) AppendMessages added in v0.8.0

func (s *NoopSessionStore) AppendMessages(_ context.Context, _ string, _ ...llm.Message) error

func (*NoopSessionStore) LoadSession added in v0.8.0

func (s *NoopSessionStore) LoadSession(_ context.Context, sessionID string) ([]llm.Message, error)

func (*NoopSessionStore) SessionExists added in v0.8.0

func (s *NoopSessionStore) SessionExists(_ string) bool

type PRComment

type PRComment struct {
	ID         int64     `json:"id"`
	Author     string    `json:"author"`
	Body       string    `json:"body"`
	IsSelf     bool      `json:"is_self"`
	Date       time.Time `json:"date"`
	Path       string    `json:"path,omitempty"`
	Line       int       `json:"line,omitempty"`
	StartLine  int       `json:"start_line,omitempty"`
	IsOutdated bool      `json:"is_outdated"`
}

PRComment represents a single comment on a pull request.

type PRMetadata

type PRMetadata struct {
	RepoFullName  string        `json:"repo_full_name"`
	PRNumber      int           `json:"pr_number"`
	Title         string        `json:"title"`
	Description   string        `json:"description"`
	Author        string        `json:"author"`
	CreatedAt     time.Time     `json:"created_at"`
	Comments      []PRComment   `json:"comments"`
	IdentifiedTag string        `json:"identified_tag,omitempty"`
	Branch        string        `json:"branch,omitempty"`
	Base          string        `json:"base,omitempty"`
	Head          string        `json:"head,omitempty"`
	Stack         []PRStackItem `json:"stack,omitempty"`
}

PRMetadata represents the context of a pull request.

type PRStackItem added in v0.8.0

type PRStackItem = tools.PRStackItem

PRStackItem represents a single pull request in a PR stack.

type PhaseMetrics added in v0.7.0

type PhaseMetrics struct {
	Phase   string         `json:"phase"`
	Metrics SessionMetrics `json:"metrics"`
}

PhaseMetrics captures the metrics for a specific review phase.

type PostReviewServer added in v0.8.0

type PostReviewServer interface {
	WaitForFirstMessage(ctx context.Context) (string, error)
	ServePostReview(ctx context.Context, handler func(ctx context.Context, query string) error) error
	SignalReviewFailed(err error) error
}

PostReviewServer is an optional interface implemented by reporters (such as ACP) that handle interactive post-review conversations asynchronously.

type Reporter

type Reporter interface {
	ReportIteration(iter int)
	ReportStageIteration(stage string, iter int)
	ReportToolCalls(tcs []llm.ToolCall)
	ReportUsage(usage llm.Usage)
	ReportUsageSummary(usage llm.Usage)
	ReportFinalReview()
	ReportStageFinalReview(stage string)
	ReportExtraction()
	ReportExtractionRetry(attempt int)
	ReportEmptyResponseRetry(attempt int)
	ReportCapReached(maxIterations int)
	ReportTruncated(maxTokens int)
	ReportMCPStatus(name string, status string, err error)
	ReportToolStatus(tc llm.ToolCall, status string, err error)
	ReportReviewHeader(files int, guidelines string, model string)

	// Additional lifecycle methods
	ReportConfig(cfg *config.Config, targetDir string)
	ReportFetchingDiff()
	ReportFetchingCommits()
	ReportNoChanges()
	ReportReview(result string) error
	ReportStageReview(stage, result string) error
	ReportReviewWritten(file string)
	ReportStructuredReviewWritten(file string)
	ReportMetricsWritten(file string)
	ReportWarning(msg string, err error)
	ReportError(err error)
	NotifyUser()
	ReportPostReviewReply(message string)
	ReportPostReviewUserQuery(query string)
}

Reporter defines how the Agent reports progress and diagnostics.

func NewACPReporter added in v0.8.0

func NewACPReporter(ctx context.Context, stdout io.Writer, stdin io.Reader, stderr io.Writer, cancelSession context.CancelFunc, opts ...ACPOption) Reporter

NewACPReporter creates a Reporter backed by an ACP AgentSideConnection over stdout and stdin. All diagnostic warnings and internal connection logs are routed to stderr so stdout remains reserved exclusively for JSON-RPC frames.

func NewDefaultReporter added in v0.5.0

func NewDefaultReporter(w io.Writer) Reporter

NewDefaultReporter creates a raw reporter for backward compatibility.

func NewMarkdownReporter added in v0.6.0

func NewMarkdownReporter(stdout, stderr io.Writer) Reporter

NewMarkdownReporter creates a reporter that renders markdown via glamour.

func NewRawReporter added in v0.6.0

func NewRawReporter(stdout, stderr io.Writer) Reporter

NewRawReporter creates a reporter that prints raw text.

func NewTuiReporter added in v0.6.0

func NewTuiReporter(stdout, stderr io.Writer, cancel context.CancelFunc) Reporter

NewTuiReporter constructs a TUI reporter.

type ReviewMetrics added in v0.7.0

type ReviewMetrics struct {
	Phases []PhaseMetrics `json:"metrics"`
}

ReviewMetrics captures the list of phase-specific metrics.

type ReviewVerdict added in v0.8.0

type ReviewVerdict string

ReviewVerdict represents the high-level outcome of a code review.

const (
	VerdictApproved ReviewVerdict = "approved"
	VerdictRejected ReviewVerdict = "rejected"
	VerdictComment  ReviewVerdict = "comment"
	VerdictElse     ReviewVerdict = VerdictComment
)

func DetermineVerdict added in v0.8.0

func DetermineVerdict(reviewText string) ReviewVerdict

DetermineVerdict extracts the ReviewVerdict from a review's markdown text. It inspects lines from the bottom of the review upwards to find the concluding verdict.

type Reviewer added in v0.5.0

type Reviewer struct {
	Agent                    *Agent
	Config                   *config.Config
	RootDir                  string
	StablePrompt             string
	Guidelines               string
	SupplementalGuidelines   []string
	ApprovalEvaluationPrompt string

	PreReviewMetrics  *SessionMetrics
	CodeReviewMetrics *SessionMetrics
	DiscussionMetrics *SessionMetrics
	// contains filtered or unexported fields
}

Reviewer encapsulates an initialized Agent and its environment.

func NewReviewer added in v0.5.0

func NewReviewer(ctx context.Context, cfg *config.Config, targetDir string, reporter Reporter) (r *Reviewer, err error)

NewReviewer instantiates a Reviewer based on the provided configuration. targetDir is the directory where local tools (like grep) will operate.

func (*Reviewer) Close added in v0.5.0

func (r *Reviewer) Close() error

Close releases resources (like MCP server connections).

func (*Reviewer) GetMetrics added in v0.7.0

func (r *Reviewer) GetMetrics() ReviewMetrics

GetMetrics returns the captured metrics for both phases.

func (*Reviewer) GetVerdict added in v0.8.0

func (r *Reviewer) GetVerdict() ReviewVerdict

GetVerdict returns the current review verdict in a thread-safe manner.

func (*Reviewer) Run added in v0.5.0

func (r *Reviewer) Run(ctx context.Context, changedFiles []string, requestText string) (string, error)

Run executes a review for the given changes.

func (*Reviewer) RunInteractivePostReview added in v0.6.0

func (r *Reviewer) RunInteractivePostReview(ctx context.Context) error

RunInteractivePostReview starts a continuous chat loop with the developer.

func (*Reviewer) SetDiff added in v0.8.0

func (r *Reviewer) SetDiff(diffText string)

SetDiff parses the unified diff and sets the in-memory file diff map.

func (*Reviewer) SetDiffMap added in v0.8.0

func (r *Reviewer) SetDiffMap(diffMap map[string]string)

SetDiffMap sets the pre-parsed in-memory file diff map for on-demand diff retrieval.

func (*Reviewer) SetHistory added in v0.8.0

func (r *Reviewer) SetHistory(history []llm.Message)

SetHistory sets the conversation history on the Reviewer's Agent.

func (*Reviewer) SetSession added in v0.8.0

func (r *Reviewer) SetSession(store SessionStore, sessionID string)

SetSession sets or updates the SessionStore and session ID on the Reviewer's Agent.

func (*Reviewer) SetVerdict added in v0.8.0

func (r *Reviewer) SetVerdict(v ReviewVerdict)

SetVerdict sets the current review verdict in a thread-safe manner.

type SessionMetrics added in v0.4.0

type SessionMetrics struct {
	Tokens     TokenMetrics    `json:"tokens"`
	Iterations int             `json:"iterations"`
	ToolCalls  ToolCallMetrics `json:"tool_calls"`
}

SessionMetrics captures detailed usage and execution metrics for an agent session.

func (*SessionMetrics) Add added in v0.8.0

func (m *SessionMetrics) Add(other SessionMetrics)

Add accumulates other's token, iteration, and tool-call counts into m.

type SessionStore added in v0.8.0

type SessionStore interface {
	// AppendMessages appends messages to the session's messages.jsonl.
	AppendMessages(ctx context.Context, sessionID string, msgs ...llm.Message) error
	// LoadSession reads and parses all messages from the session's messages.jsonl.
	LoadSession(ctx context.Context, sessionID string) ([]llm.Message, error)
	// SessionExists returns true if messages.jsonl exists and is non-empty for sessionID.
	SessionExists(sessionID string) bool
}

SessionStore manages persisting and loading conversation sessions.

func NewSessionStore added in v0.8.0

func NewSessionStore(configFolder string) SessionStore

NewSessionStore returns a ConcreteSessionStore rooted at the given config folder, or a NoopSessionStore if configFolder is empty.

type SessionWaiter added in v0.8.0

type SessionWaiter interface {
	WaitForSession(ctx context.Context) error
	IsLoadedSession() bool
	LoadedMessages() []llm.Message
	SessionID() string
}

SessionWaiter is an optional interface implemented by reporters (such as ACP) that wait for a session handshake (new or load) before proceeding.

type StructuredReview

type StructuredReview struct {
	RawFreeText       string       `json:"raw_free_text"`
	Approval          Approval     `json:"approval"`
	NonSpecificReview string       `json:"non_specific_review,omitempty"`
	FilesReview       []FileReview `json:"files_review"`
}

StructuredReview represents the final extracted code review in a machine-readable format.

type TokenMetrics added in v0.4.0

type TokenMetrics struct {
	Input       int `json:"input"`
	Output      int `json:"output"`
	Thinking    int `json:"thinking"`
	Cached      int `json:"cached"`
	TotalInput  int `json:"total_input"`
	TotalOutput int `json:"total_output"`
}

TokenMetrics breaks down token consumption by category.

type ToolCallMetrics added in v0.4.0

type ToolCallMetrics struct {
	Total  int            `json:"total"`
	ByTool map[string]int `json:"by_tool"`
}

ToolCallMetrics tracks how many times tools were invoked.

type ToolDispatcher

type ToolDispatcher interface {
	ToTools() []llm.ToolDef
	HandleCall(ctx context.Context, tc llm.ToolCall) (string, error)
}

ToolDispatcher is the minimal interface the Agent needs from a tool registry. *tools.Registry satisfies this interface; tests can supply a lightweight stub.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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