Documentation
¶
Overview ¶
Package agent provides the agent runtime pool and runner for processing tasks as goroutines with session lifecycle management and cost recording.
Index ¶
- Constants
- Variables
- func BranchSlug(issueNumber int, title string) string
- func BuildResumePrompt(checkpointContent string) string
- func BuildSystemPrompt(task Task, fileContext map[string]string, patterns ...string) string
- func ChangedFiles(workDir string) ([]string, error)
- func CheckDocGate(changed []string) (needsDoc bool, codeFiles []string)
- func CommitAndPush(workDir, commitMsg string) (changed bool, err error)
- func CreateWorkspace(repoDir, sessionID string, issueNumber int, logger *zap.Logger) (wsPath string, cleanup func(), retErr error)
- func DetectProjectType(labels []string) string
- func FetchLatest(repoDir string, logger *zap.Logger)
- func FetchRelevantPatterns(ctx context.Context, client *synapset.Client, query string, maxResults int) ([]string, error)
- func FindLatestCheckpoint(comments []*forge.Comment) string
- func FindLatestProgress(comments []*forge.Comment) string
- func FormatCheckpoint(sessionID, partialOutput string) string
- func FormatProgress(sessionID, partialOutput string) string
- func GenerateAgentCLAUDEMD(projectType, issueBody string) string
- func HashCheckpoint(content string) string
- func PruneStaleWorktrees(logger *zap.Logger)
- func ReadWorkspaceFiles(dir string, paths []string, maxBytes int) map[string]string
- func WriteMCPConfig(worktreeDir string) error
- type FileEdit
- type ParseResponse
- type Pool
- func (p *Pool) AddWorkers(n int) error
- func (p *Pool) Done() <-chan struct{}
- func (p *Pool) RegistryRouting() map[string][]string
- func (p *Pool) RemoveWorkers(n int) int
- func (p *Pool) Resize(target int) error
- func (p *Pool) SetMaxWorkers(limit int)
- func (p *Pool) SetOnComplete(fn func(TaskResult))
- func (p *Pool) SetRepoDir(dir string)
- func (p *Pool) SetSynapset(sc *synapset.Client)
- func (p *Pool) Shutdown()
- func (p *Pool) Snapshot() metrics.PoolSnapshot
- func (p *Pool) Submit(task Task) error
- func (p *Pool) Workers() int
- type Runner
- func (r *Runner) Run(ctx context.Context, task Task) error
- func (r *Runner) SetPRManager(pm forge.PullRequestManager)
- func (r *Runner) SetPolicy(p autonomy.AutonomyPolicy)
- func (r *Runner) SetProgressInterval(d time.Duration)
- func (r *Runner) SetRepoDir(dir string)
- func (r *Runner) SetRepoWriter(rw forge.RepoWriter)
- func (r *Runner) SetSynapset(sc *synapset.Client)
- type Task
- type TaskResult
- type ValidationError
- type ValidationResult
Constants ¶
const ( ProjectTypeGo = "go" ProjectTypeFrontend = "frontend" ProjectTypeFullstack = "fullstack" )
Project type constants for CI checklist selection.
Variables ¶
var ErrMaxWorkers = errors.New("pool: would exceed maximum worker count")
ErrMaxWorkers is returned when AddWorkers or Resize would exceed the configured maximum worker count.
var ErrPoolShutdown = errors.New("pool is shut down")
ErrPoolShutdown is returned when Submit is called on a shut-down pool.
Functions ¶
func BranchSlug ¶ added in v0.1.5
BranchSlug generates a branch name from an issue number and title. Format: agent/issue-{N}-{slug}, truncated to 50 chars.
func BuildResumePrompt ¶ added in v0.1.13
BuildResumePrompt creates the system prompt injection that instructs the model to continue from a prior checkpoint rather than starting over.
func BuildSystemPrompt ¶ added in v0.1.3
BuildSystemPrompt dispatches to per-agent-type prompt builders and appends file context and known patterns when available. Agent types that are not AI-driven (human, orchestrator, dispatcher) return an empty string.
func ChangedFiles ¶ added in v0.1.16
ChangedFiles returns the list of files changed in the most recent commit relative to the workspace directory.
func CheckDocGate ¶ added in v0.1.16
CheckDocGate examines a list of changed files and returns true if infrastructure or code files were modified without corresponding documentation updates. Returns false for test-only or docs-only changes.
func CommitAndPush ¶ added in v0.1.16
CommitAndPush stages all changes in the workspace directory, commits with the given message, and pushes to origin. Returns true if changes were committed, false if the workspace was clean.
func CreateWorkspace ¶ added in v0.1.16
func CreateWorkspace(repoDir, sessionID string, issueNumber int, logger *zap.Logger) (wsPath string, cleanup func(), retErr error)
CreateWorkspace creates an isolated git worktree for agent task execution. The worktree is branched from HEAD at agent/<issueNumber>. Returns the workspace path and a cleanup function that removes the worktree and its branch. The cleanup function is safe to call multiple times.
func DetectProjectType ¶ added in v0.1.16
DetectProjectType infers the project type from issue labels. Labels are checked for frontend/fullstack indicators. Falls back to Go (the primary language of Samverk).
func FetchLatest ¶ added in v0.1.16
FetchLatest pulls the latest code from origin into the shared clone and resets local main to match. This ensures new worktrees branch from current code. Errors are logged as warnings and do not block task execution.
func FetchRelevantPatterns ¶ added in v0.1.16
func FetchRelevantPatterns(ctx context.Context, client *synapset.Client, query string, maxResults int) ([]string, error)
FetchRelevantPatterns queries Synapset for patterns relevant to the given query string. Returns up to maxResults pattern descriptions. Returns an empty slice (not error) if the client is nil or Synapset is unavailable.
func FindLatestCheckpoint ¶ added in v0.1.13
FindLatestCheckpoint scans issue comments (newest first) for the most recent CHECKPOINT block and returns its content. Returns empty string if no checkpoint exists.
func FindLatestProgress ¶ added in v0.1.13
FindLatestProgress scans issue comments (newest first) for the most recent PROGRESS block and returns its content. Returns empty string if no progress comment exists.
func FormatCheckpoint ¶ added in v0.1.13
FormatCheckpoint wraps partial output in the checkpoint comment format. The session ID is embedded so multi-retry scenarios can identify which attempt produced the checkpoint.
func FormatProgress ¶ added in v0.1.13
FormatProgress wraps partial output in the progress comment format. Unlike CHECKPOINT (posted on failure), PROGRESS is posted periodically during long-running tasks to create resumable mid-task state.
func GenerateAgentCLAUDEMD ¶ added in v0.1.16
GenerateAgentCLAUDEMD builds a per-worktree CLAUDE.md for agents. It includes core principles, git safety rules, a CI checklist selected by project type, known gotchas, and the issue body as task context.
func HashCheckpoint ¶ added in v0.1.13
HashCheckpoint returns a hex-encoded SHA-256 of the checkpoint content. Used to dedup: if a session already posted this exact checkpoint, skip.
func PruneStaleWorktrees ¶ added in v0.1.16
PruneStaleWorktrees removes agent worktree directories that are older than staleWorktreeAge (2 hours). This prevents leaked worktrees from accumulating after crashes or ungraceful shutdowns.
func ReadWorkspaceFiles ¶ added in v0.1.16
ReadWorkspaceFiles reads file contents from the given directory for the specified paths. Returns a map of path to content. Files that cannot be read are included with empty content. The total content size is capped at maxBytes.
func WriteMCPConfig ¶ added in v0.1.16
WriteMCPConfig writes a .claude/.mcp.json file into the given worktree directory, configuring Samverk and Synapset MCP endpoints for CLI agents.
Types ¶
type FileEdit ¶ added in v0.1.5
FileEdit represents a single file edit extracted from an agent response.
func DeduplicateEdits ¶ added in v0.1.13
DeduplicateEdits filters out EDIT blocks from newEdits that already exist in the checkpoint content. Two edits match when they have the same path and identical content hash. This prevents writing files that were already committed to the branch in a prior attempt.
type ParseResponse ¶ added in v0.1.5
ParseResponse holds the parsed result of an agent's response.
func ParseEditBlocks ¶ added in v0.1.5
func ParseEditBlocks(response string) *ParseResponse
ParseEditBlocks extracts EDIT/END file blocks and the PR_TITLE line from an agent response string. Returns nil edits if no EDIT blocks found.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool manages a set of worker goroutines that process agent tasks. Workers may be added or removed at runtime via AddWorkers/RemoveWorkers/Resize.
func NewPool ¶
func NewPool(registry *provider.Registry, tracker forge.IssueTracker, st store.Store, costs *cost.Tracker, workers int, logger *zap.Logger) *Pool
NewPool creates a pool with the given number of worker goroutines and starts them immediately. If workers is <= 0, it defaults to 3. The default maximum is runtime.NumCPU(); call SetMaxWorkers to override before scaling.
func (*Pool) AddWorkers ¶ added in v0.1.11
AddWorkers starts n additional worker goroutines. Returns ErrPoolShutdown if the pool has already been shut down, or ErrMaxWorkers if the addition would exceed the configured maximum. No-op if n <= 0.
func (*Pool) Done ¶
func (p *Pool) Done() <-chan struct{}
Done returns a channel that is closed after Shutdown completes.
func (*Pool) RegistryRouting ¶ added in v0.1.16
RegistryRouting returns the routing table from the underlying provider registry. Used by the dispatcher for pre-flight health gate checks.
func (*Pool) RemoveWorkers ¶ added in v0.1.11
RemoveWorkers signals n workers to exit after completing their current task. To protect liveness, at least one worker is always kept running; the actual number removed may be less than n. Returns the number of quit signals sent.
func (*Pool) Resize ¶ added in v0.1.11
Resize sets the pool's worker count to target, adding or removing workers as needed. It enforces the same minimum (1) and maximum bounds as AddWorkers and RemoveWorkers. Returns ErrPoolShutdown if the pool has been shut down.
func (*Pool) SetMaxWorkers ¶ added in v0.1.11
SetMaxWorkers sets the maximum number of workers the pool may hold at any time. A value <= 0 removes the limit. Must be called before scaling; not safe to call concurrently with AddWorkers or Resize.
func (*Pool) SetOnComplete ¶ added in v0.1.10
func (p *Pool) SetOnComplete(fn func(TaskResult))
SetOnComplete registers a callback invoked after each task finishes.
func (*Pool) SetRepoDir ¶ added in v0.1.16
SetRepoDir configures the local git repository path used to create isolated worktrees for agent sessions. When set, code-gen and test agents get their own worktree branched from the latest origin/main.
func (*Pool) SetSynapset ¶ added in v0.1.16
SetSynapset configures a Synapset memory client for all runners in the pool. When set, runners enrich prompts with relevant memories before provider calls and store task outcomes after completion.
func (*Pool) Shutdown ¶
func (p *Pool) Shutdown()
Shutdown signals all workers to stop and waits for in-flight tasks to complete. After Shutdown returns, Submit will return ErrPoolShutdown.
func (*Pool) Snapshot ¶ added in v0.1.11
func (p *Pool) Snapshot() metrics.PoolSnapshot
Snapshot returns a point-in-time view of pool state for the scaling policy.
func (*Pool) Submit ¶
Submit enqueues a task for processing. Returns ErrPoolShutdown if the pool has been shut down.
The lock is held across the channel send to prevent a TOCTOU race with Shutdown: without it, Shutdown can close the channel between the flag check and the send, causing a panic. The channel is buffered (workers×2) so the send is almost always non-blocking. In the rare case the buffer is full, workers will drain it without acquiring mu, so no deadlock.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
Runner executes a single agent task: sends the issue to an AI provider, records cost, and posts the response as an issue comment or opens a PR.
func NewRunner ¶
func NewRunner(p provider.Provider, model string, tracker forge.IssueTracker, st store.Store, costs *cost.Tracker, logger *zap.Logger) *Runner
NewRunner creates a runner bound to a specific provider and model. The repoWriter and prManager are optional; when nil, code-gen/test agents fall back to posting comments instead of opening PRs.
func (*Runner) Run ¶
Run processes a single task through the AI provider pipeline.
Steps:
- Update session status to "active"
- Check budget -- if exceeded, mark "failed" and return
- Detect prior checkpoint for resume
- Build system prompt and chat request (with resume context if available)
- Call provider.Chat
- Record cost via cost tracker
- Post response as issue comment (dedup edits against checkpoint)
- Mark session "completed"
On any error, the session is marked "failed" and an error comment is posted.
func (*Runner) SetPRManager ¶ added in v0.1.5
func (r *Runner) SetPRManager(pm forge.PullRequestManager)
SetPRManager configures pull request operations.
func (*Runner) SetPolicy ¶ added in v0.1.16
func (r *Runner) SetPolicy(p autonomy.AutonomyPolicy)
SetPolicy configures the autonomy policy for tier enforcement. When nil, all actions are allowed (backward compatible).
func (*Runner) SetProgressInterval ¶ added in v0.1.13
SetProgressInterval overrides the default interval between PROGRESS posts. A value of 0 disables periodic progress posting entirely.
func (*Runner) SetRepoDir ¶ added in v0.1.16
SetRepoDir configures the local repository path for workspace isolation. When set, code-gen and test agents execute in isolated git worktrees.
func (*Runner) SetRepoWriter ¶ added in v0.1.5
func (r *Runner) SetRepoWriter(rw forge.RepoWriter)
SetRepoWriter configures write access for branch/file operations.
func (*Runner) SetSynapset ¶ added in v0.1.16
SetSynapset configures the Synapset memory client for context enrichment. When nil, memory enrichment is disabled.
type Task ¶
type Task struct {
Issue *forge.Issue
Tracker forge.IssueTracker // per-task tracker for comments/labels; when nil, pool falls back to its default
Owner string // repository owner for this task
Repo string // repository name for this task
AgentType models.AgentType
SessionID string
ProviderKey string // routing chain key; defaults to string(AgentType) when empty
Timeout time.Duration // per-task timeout; 0 means no deadline
HeartbeatFunc func() // called periodically while running; signals dispatcher that work is in progress; may be nil
Frontmatter *models.IssueFrontmatter // parsed frontmatter from issue body; may be nil
}
Task represents a unit of work to be processed by the agent pool.
type TaskResult ¶ added in v0.1.10
type TaskResult struct {
IssueNumber int
Owner string // repository owner
Repo string // repository name
SessionID string
AgentType models.AgentType
ProviderKey string // routing chain key used for this task
Success bool
Error string
}
TaskResult reports the outcome of a pool task back to the dispatcher.
type ValidationError ¶ added in v0.1.16
type ValidationError struct {
Phase string // "build", "test", "format"
Message string
Output string // truncated command output (max 2000 chars)
}
ValidationError describes a single validation failure.
type ValidationResult ¶ added in v0.1.16
type ValidationResult struct {
Pass bool
Retryable bool // false for infrastructure failures; true for code errors
Errors []ValidationError
Duration time.Duration
}
ValidationResult reports the outcome of pre-posting validation.
func ValidateBeforePost ¶ added in v0.1.16
func ValidateBeforePost(ctx context.Context, agentType models.AgentType, workDir, response string, logger *zap.Logger) *ValidationResult
ValidateBeforePost checks agent output quality before posting. For code-gen/test agents with a worktree (CLI flow): runs build/test on the worktree. For code-gen/test agents without a worktree (API flow): skips (no local context to validate). For analytical agents: checks format only. Returns nil when no validation is needed.