run

package
v1.0.9 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package run provides helper functions for audit logging agent events.

Package run provides helpers for async worker dispatch and collection.

Test helpers for async dispatch behavior.

Package run provides branch lifecycle management for task execution.

Package run provides helpers for reading worker dispatch metadata.

Package run provides helpers for governator run orchestration safeguards.

Package run provides execute orchestration helpers.

Package run defines the execution workstream controller implementation.

Package run provides execution-progress helpers used by supervisor orchestration.

Package run provides git helpers for deterministic Governator commits.

Package run provides merge flow operations for transitioning reviewed tasks to done.

Package run provides the main orchestration logic for the run command.

Package run defines helpers for emitting standardized run output events.

Package run implements Governator run orchestration helpers.

Package run defines the planning workstream controller implementation.

Package run seeds and maintains the planning task index entries.

Package run provides helpers for determining planning progress from the task index.

Package run provides the planning spec loader and validation helpers.

Package run defines the planning workstream as an ordered compound task.

Package run provides resume logic for timed-out tasks.

Package run provides task inventory functionality for planning completion.

Package run provides execution backlog triage helpers.

Package run provides unified supervisor orchestration.

Package run provides unified supervisor control helpers.

Package run provides the planning validation execution engine.

Package run provides helpers for terminating timed-out worker processes.

Package run defines workstream abstractions used by the run orchestration.

Package run provides workstream execution orchestration.

Index

Constants

View Source
const PlanningCompleteState = "governator_planning_complete"

PlanningCompleteState marks the planning task as completed in the task index.

View Source
const PlanningNotStartedState = "governator_planning_not_started"

PlanningNotStartedState marks the planning task as not yet started in the task index.

Variables

View Source
var ErrPlanningDrift = errors.New("planning drift detected")

ErrPlanningDrift indicates stored planning digests no longer match the repo state.

Functions

func BlockTaskWithRetryExceeded

func BlockTaskWithRetryExceeded(idx *index.Index, taskID string, maxAttempts int, auditor index.TransitionAuditor) error

BlockTaskWithRetryExceeded blocks a task that has exceeded its retry limit.

func CheckPlanningDrift

func CheckPlanningDrift(repoRoot string, stored index.Digests) error

CheckPlanningDrift stops a run when planning digests changed since planning.

func ClearTriageState

func ClearTriageState(repoRoot string) error

ClearTriageState removes persisted triage state.

func EnsureBranchForTask

func EnsureBranchForTask(repoRoot string, task index.Task, baseBranch string, auditor *audit.Logger) error

EnsureBranchForTask creates a branch for a task if it doesn't exist. This is called just-in-time before creating a worktree for dispatch. Branches are stable/long-lived - only create if missing, never force-update.

func ExecuteConflictResolutionAgent

func ExecuteConflictResolutionAgent(repoRoot, worktreePath string, task index.Task, cfg config.Config, idx index.Index, auditor *audit.Logger, opts Options) (worker.IngestResult, roles.RoleAssignmentResult, error)

ExecuteConflictResolutionAgent runs the conflict resolution agent for a specific task.

func ExecuteReviewAgent

func ExecuteReviewAgent(repoRoot, worktreePath string, task index.Task, cfg config.Config, auditor *audit.Logger, opts Options) (worker.IngestResult, error)

ExecuteReviewAgent runs the review agent for a specific task.

func ExecuteTestAgent

func ExecuteTestAgent(repoRoot, worktreePath string, task index.Task, cfg config.Config, auditor *audit.Logger, opts Options) (worker.IngestResult, error)

ExecuteTestAgent runs the test agent for a specific task.

func ExecuteWorkAgent

func ExecuteWorkAgent(repoRoot, worktreePath string, task index.Task, cfg config.Config, auditor *audit.Logger, opts Options) (worker.IngestResult, error)

ExecuteWorkAgent runs the work agent for a specific task.

func MarkSupervisorTransition added in v1.0.2

func MarkSupervisorTransition(state supervisor.SupervisorStateInfo) supervisor.SupervisorStateInfo

MarkSupervisorTransition updates the transition timestamp for the supervisor state.

func PrepareTaskForResume

func PrepareTaskForResume(idx *index.Index, taskID string, auditor index.TransitionAuditor) error

PrepareTaskForResume increments the attempt counter and transitions the task to open.

func ReadDispatchWrapperPID added in v1.0.7

func ReadDispatchWrapperPID(workerStateDir string) (int, bool, error)

ReadDispatchWrapperPID loads the wrapper PID from a worker state directory when present.

func ResetPlanningToStep added in v1.0.2

func ResetPlanningToStep(repoRoot string, nextStepID string) error

ResetPlanningToStep updates planning state to restart the planning pipeline at a specific step.

func RunUnifiedSupervisor added in v1.0.2

func RunUnifiedSupervisor(repoRoot string, opts UnifiedSupervisorOptions) error

RunUnifiedSupervisor runs the unified supervisor loop until orchestration completes or fails.

func SaveTriageState

func SaveTriageState(repoRoot string, state TriageState) error

SaveTriageState persists the triage state file.

func SeedPlanningIndex

func SeedPlanningIndex(repoRoot string) error

SeedPlanningIndex writes the planning task index on init when it is missing.

func SelectRoleForConflictResolution

func SelectRoleForConflictResolution(task index.Task) roles.RoleAssignmentResult

SelectRoleForConflictResolution uses the role assignment LLM to select an appropriate role for conflict resolution.

func StopUnifiedSupervisor added in v1.0.2

func StopUnifiedSupervisor(repoRoot string, opts UnifiedSupervisorStopOptions) error

StopUnifiedSupervisor terminates the unified supervisor and optionally its active workers.

func SupervisorStateEqual added in v1.0.2

func SupervisorStateEqual(left supervisor.SupervisorStateInfo, right supervisor.SupervisorStateInfo) bool

supervisorStateEqual compares two supervisor state snapshots for equality.

func TaskBranchName

func TaskBranchName(task index.Task) string

TaskBranchName returns the canonical branch name for the provided task. The task ID already contains the slugified title and role (format: <id>-<slug>-<role>), so the branch name is just the task ID.

func TerminateProcess added in v1.0.2

func TerminateProcess(pid int) error

TerminateProcess attempts to terminate a process by PID.

func UpdatePlanningIndex

func UpdatePlanningIndex(worktreePath string, step workstreamStep) error

UpdatePlanningIndex refreshes digests after a completed planning step.

func UpdateTaskStateFromConflictResolution

func UpdateTaskStateFromConflictResolution(idx *index.Index, taskID string, resolutionResult worker.IngestResult, auditor index.TransitionAuditor) error

UpdateTaskStateFromConflictResolution updates the task index based on conflict resolution results.

func UpdateTaskStateFromMerge

func UpdateTaskStateFromMerge(idx *index.Index, taskID string, mergeResult worker.IngestResult, auditor index.TransitionAuditor) error

UpdateTaskStateFromMerge updates the task index based on merge results.

func UpdateTaskStateFromReviewResult

func UpdateTaskStateFromReviewResult(idx *index.Index, taskID string, reviewResult worker.IngestResult, auditor index.TransitionAuditor) (index.ExecutionMetrics, error)

UpdateTaskStateFromReviewResult updates the task index based on review execution results. Returns the metrics that were accumulated for this stage.

func UpdateTaskStateFromTestResult

func UpdateTaskStateFromTestResult(idx *index.Index, taskID string, testResult worker.IngestResult, auditor index.TransitionAuditor) (index.ExecutionMetrics, error)

UpdateTaskStateFromTestResult updates the task index based on test execution results. Returns the metrics that were accumulated for this stage.

func UpdateTaskStateFromWorkResult

func UpdateTaskStateFromWorkResult(idx *index.Index, taskID string, workResult worker.IngestResult, auditor index.TransitionAuditor) (index.ExecutionMetrics, error)

UpdateTaskStateFromWorkResult updates the task index based on work execution results. Returns the metrics that were accumulated for this stage.

Types

type AgentAuditor

type AgentAuditor interface {
	LogAgentInvoke(taskID string, role string, agent string, attempt int) error
	LogAgentOutcome(taskID string, role string, agent string, status string, exitCode int) error
}

AgentAuditor defines the audit methods needed for agent events.

type BranchLifecycleManager

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

BranchLifecycleManager handles creation, management, and cleanup of task branches.

func NewBranchLifecycleManager

func NewBranchLifecycleManager(repoRoot string, auditor *audit.Logger) *BranchLifecycleManager

NewBranchLifecycleManager creates a new branch lifecycle manager.

func (*BranchLifecycleManager) BranchExists

func (blm *BranchLifecycleManager) BranchExists(branchName string) (bool, error)

BranchExists checks if a branch exists in the repository.

func (*BranchLifecycleManager) CheckoutBranch

func (blm *BranchLifecycleManager) CheckoutBranch(branch string) error

CheckoutBranch checks out the specified branch.

func (*BranchLifecycleManager) CleanupTaskBranch

func (blm *BranchLifecycleManager) CleanupTaskBranch(task index.Task) error

CleanupTaskBranch removes a task branch after successful completion. This should be called after the task has been successfully merged to main.

func (*BranchLifecycleManager) CreateTaskBranch

func (blm *BranchLifecycleManager) CreateTaskBranch(task index.Task, baseBranch string) error

CreateTaskBranch creates a new branch for a task when it transitions to open state.

func (*BranchLifecycleManager) CreateTaskBranchWithoutCheckout

func (blm *BranchLifecycleManager) CreateTaskBranchWithoutCheckout(task index.Task, baseBranch string) error

CreateTaskBranchWithoutCheckout creates a new branch for a task without checking it out. The base branch must already be checked out and up-to-date before calling this method. This is useful for batch branch creation where you want to create multiple branches without repeatedly switching between them.

Use PrepareBaseBranch() before calling this in a loop.

func (*BranchLifecycleManager) EnsureTaskBranch

func (blm *BranchLifecycleManager) EnsureTaskBranch(task index.Task, baseBranch string) error

EnsureTaskBranch ensures a task branch exists and is properly set up. This is used during resume operations or when a task needs to be worked on. NOTE: This method WILL checkout the task branch, leaving you on that branch. For batch branch creation without checkout, use CreateTaskBranchWithoutCheckout.

func (*BranchLifecycleManager) GetTaskBranchName

func (blm *BranchLifecycleManager) GetTaskBranchName(task index.Task) string

GetTaskBranchName returns the deterministic branch name for a task.

func (*BranchLifecycleManager) PrepareBaseBranch

func (blm *BranchLifecycleManager) PrepareBaseBranch(baseBranch string) error

PrepareBaseBranch checks out the base branch. This should be called before batch branch creation operations to ensure all branches are created from the same consistent base.

type ConflictResolutionStageResult

type ConflictResolutionStageResult struct {
	TasksDispatched int
	TasksResolved   int
	TasksBlocked    int
	InFlightUpdated bool
	Metrics         map[string]index.ExecutionMetrics // Metrics by task ID
}

ConflictResolutionStageResult captures the outcome of conflict resolution stage execution.

func ExecuteConflictResolutionStage

func ExecuteConflictResolutionStage(repoRoot string, idx *index.Index, cfg config.Config, caps scheduler.RoleCaps, inFlight inflight.Set, worktreeOverrides map[string]string, transitionAuditor index.TransitionAuditor, workerAuditor *audit.Logger, opts Options) (ConflictResolutionStageResult, error)

ExecuteConflictResolutionStage processes tasks in the conflict state by dispatching conflict resolution agents.

type MergeFlowInput

type MergeFlowInput struct {
	RepoRoot     string
	WorktreePath string
	Task         index.Task
	MainBranch   string
	Auditor      *audit.Logger
}

MergeFlowInput defines the inputs required for the review merge flow.

type MergeFlowResult

type MergeFlowResult struct {
	Success       bool
	NewState      index.TaskState
	ConflictError string
}

MergeFlowResult captures the outcome of the review merge flow.

func ExecuteConflictResolutionMergeFlow

func ExecuteConflictResolutionMergeFlow(input MergeFlowInput) (MergeFlowResult, error)

ExecuteConflictResolutionMergeFlow handles merge flow for resolved tasks. This is similar to the review merge flow but starts from resolved state.

func ExecuteReviewMergeFlow

func ExecuteReviewMergeFlow(input MergeFlowInput) (MergeFlowResult, error)

ExecuteReviewMergeFlow performs local git rebase and merge operations for a reviewed task. This implements the flow: rebase on main → squash in isolated worktree → update local main → done. On conflict: mark as conflict state for manual resolution.

type MergeStageResult

type MergeStageResult struct {
	TasksProcessed int
	TasksMerged    int
	TasksConflict  int
}

MergeStageResult captures the outcome of merge stage execution.

func ExecuteMergeStage

func ExecuteMergeStage(repoRoot string, idx *index.Index, cfg config.Config, caps scheduler.RoleCaps, worktreeOverrides map[string]string, transitionAuditor index.TransitionAuditor, workerAuditor *audit.Logger, opts Options) (MergeStageResult, error)

ExecuteMergeStage processes tasks in the resolved state through the merge flow.

type Options

type Options struct {
	Stdout io.Writer
	Stderr io.Writer
	// DisableDispatch prevents new work from dispatching while allowing in-flight collection.
	DisableDispatch bool
	// SkipPlanningDrift disables planning drift checks for this run invocation.
	SkipPlanningDrift bool
}

Options defines the configuration for a run execution.

type PlanningDriftReport added in v1.0.3

type PlanningDriftReport struct {
	HasDrift bool
	Details  []string
	Message  string
}

PlanningDriftReport summarizes planning digest drift detected since the last refresh.

func DetectPlanningDrift added in v1.0.3

func DetectPlanningDrift(repoRoot string, stored index.Digests) (PlanningDriftReport, error)

DetectPlanningDrift reports planning digest drift relative to stored digests.

type PlanningSpec

type PlanningSpec struct {
	Version int                `json:"version"`
	Steps   []PlanningStepSpec `json:"steps"`
}

PlanningSpec defines the JSON schema for the planning workstream.

func LoadPlanningSpec

func LoadPlanningSpec(repoRoot string) (PlanningSpec, error)

LoadPlanningSpec reads and parses the planning spec from the repository.

func ParsePlanningSpec

func ParsePlanningSpec(data []byte) (PlanningSpec, error)

ParsePlanningSpec decodes and validates a planning spec payload.

type PlanningStepSpec

type PlanningStepSpec struct {
	ID          string                   `json:"id"`
	Name        string                   `json:"name"`
	Prompt      string                   `json:"prompt"`
	Role        string                   `json:"role"`
	Validations []PlanningValidationSpec `json:"validations,omitempty"`
}

PlanningStepSpec declares a single step in the planning workstream.

type PlanningValidationSpec

type PlanningValidationSpec struct {
	Type           string `json:"type"` // "command", "file", "directory", or "prompt"
	Command        string `json:"command,omitempty"`
	Expect         string `json:"expect,omitempty"` // for command: expected exit behavior
	StdoutRegex    string `json:"stdout_regex,omitempty"`
	StdoutContains string `json:"stdout_contains,omitempty"`
	Path           string `json:"path,omitempty"`        // for file/directory validation
	FileRegex      string `json:"regex,omitempty"`       // for file content validation
	PromptRole     string `json:"role,omitempty"`        // for prompt validation
	Inline         string `json:"inline,omitempty"`      // for prompt validation
	PromptPath     string `json:"prompt_path,omitempty"` // for prompt validation
}

PlanningValidationSpec defines a validation check to run after step completion.

type Result

type Result struct {
	ResumedTasks []string
	BlockedTasks []string
	Message      string
}

Result captures the outcome of a run execution.

func Execute

func Execute(repoRoot string, opts Options) (Result, error)

Execute runs execution orchestration when planning is complete.

func Run

func Run(repoRoot string, opts Options) (Result, error)

Run executes the main run orchestration including resume logic and task execution.

type ResumeCandidate

type ResumeCandidate struct {
	Task         index.Task
	WorktreePath string
	Attempt      int
}

ResumeCandidate represents a task that may be eligible for resume.

func DetectResumeCandidates

func DetectResumeCandidates(repoRoot string, idx index.Index, cfg config.Config) ([]ResumeCandidate, error)

DetectResumeCandidates identifies tasks with preserved worktrees that can be resumed.

type ResumeResult

type ResumeResult struct {
	Candidates []ResumeCandidate
	Resumed    []ResumeCandidate
	Blocked    []ResumeCandidate
}

ResumeResult captures the outcome of resume detection and processing.

func ProcessResumeCandidates

func ProcessResumeCandidates(candidates []ResumeCandidate, cfg config.Config) ResumeResult

ProcessResumeCandidates determines which candidates should be resumed vs blocked.

type ReviewStageResult

type ReviewStageResult struct {
	TasksDispatched int
	TasksReviewed   int
	TasksBlocked    int
	InFlightUpdated bool
	Metrics         map[string]index.ExecutionMetrics // Metrics by task ID
}

ReviewStageResult captures the outcome of review stage execution.

func ExecuteReviewStage

func ExecuteReviewStage(repoRoot string, idx *index.Index, cfg config.Config, caps scheduler.RoleCaps, inFlight inflight.Set, worktreeOverrides map[string]string, transitionAuditor index.TransitionAuditor, workerAuditor *audit.Logger, opts Options) (ReviewStageResult, error)

ExecuteReviewStage processes tasks in the tested state through the review stage.

type TaskInventory

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

TaskInventory performs inventory of task files and updates the index.

func NewTaskInventory

func NewTaskInventory(repoRoot string, idx *index.Index) *TaskInventory

NewTaskInventory creates a new task inventory for the given repository.

func (*TaskInventory) InventoryTasks

func (inventory *TaskInventory) InventoryTasks() (TaskInventoryResult, error)

InventoryTasks scans the tasks directory and adds new tasks to the index.

type TaskInventoryResult

type TaskInventoryResult struct {
	TasksAdded int
	Errors     []error
}

TaskInventoryResult captures the outcome of task inventory.

type TestStageResult

type TestStageResult struct {
	TasksDispatched int
	TasksTested     int
	TasksBlocked    int
	InFlightUpdated bool
	Metrics         map[string]index.ExecutionMetrics // Metrics by task ID
}

TestStageResult captures the outcome of test stage execution.

func ExecuteTestStage

func ExecuteTestStage(repoRoot string, idx *index.Index, cfg config.Config, caps scheduler.RoleCaps, inFlight inflight.Set, worktreeOverrides map[string]string, transitionAuditor index.TransitionAuditor, workerAuditor *audit.Logger, opts Options) (TestStageResult, error)

ExecuteTestStage processes tasks in the worked state through the test stage.

type TriageCycleResult

type TriageCycleResult struct {
	Running        bool
	Completed      bool
	WorkerPID      int
	WorkerStateDir string
}

TriageCycleResult reports the outcome of a triage loop iteration.

func RunBacklogTriage

func RunBacklogTriage(repoRoot string, idx *index.Index, cfg config.Config, opts Options) (TriageCycleResult, error)

RunBacklogTriage handles dispatching and collecting the DAG triage agent.

type TriageState

type TriageState struct {
	Attempt        int       `json:"attempt"`
	RunningPID     int       `json:"running_pid,omitempty"`
	WorkerStateDir string    `json:"worker_state_dir,omitempty"`
	LastError      string    `json:"last_error,omitempty"`
	LastAttemptAt  time.Time `json:"last_attempt_at,omitempty"`
}

TriageState tracks the execution backlog triage lifecycle.

func LoadTriageState

func LoadTriageState(repoRoot string) (TriageState, bool, error)

LoadTriageState reads the triage state file when present.

type TriageTaskInfo added in v1.0.5

type TriageTaskInfo struct {
	Dependencies []string `json:"dependencies,omitempty"`
	Role         string   `json:"role,omitempty"`
}

TriageTaskInfo captures triage agent output for a single task.

type UnifiedSupervisorOptions added in v1.0.2

type UnifiedSupervisorOptions struct {
	Stdout       io.Writer
	Stderr       io.Writer
	PollInterval time.Duration
	LogPath      string
}

UnifiedSupervisorOptions configures the unified supervisor loop.

type UnifiedSupervisorStopOptions added in v1.0.2

type UnifiedSupervisorStopOptions struct {
	StopWorker bool
}

UnifiedSupervisorStopOptions configures stop behavior for the unified supervisor.

type ValidationEngine

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

ValidationEngine executes validation checks against the repository.

func NewValidationEngine

func NewValidationEngine(repoRoot string) *ValidationEngine

NewValidationEngine creates a new validation engine for the given repository.

func (*ValidationEngine) RunValidations

func (engine *ValidationEngine) RunValidations(stepID string, stepName string, validations []PlanningValidationSpec) ([]ValidationResult, error)

RunValidations executes all validations for a planning step and returns the results.

type ValidationResult

type ValidationResult struct {
	Type     string
	Valid    bool
	Message  string
	StepID   string
	StepName string
}

ValidationResult captures the outcome of a single validation check.

type WorkStageResult

type WorkStageResult struct {
	TasksDispatched int
	TasksWorked     int
	TasksBlocked    int
	InFlightUpdated bool
	WorktreePaths   map[string]string
	Metrics         map[string]index.ExecutionMetrics // Metrics by task ID
}

WorkStageResult captures the outcome of work stage execution.

func ExecuteWorkStage

func ExecuteWorkStage(repoRoot string, idx *index.Index, cfg config.Config, caps scheduler.RoleCaps, inFlight inflight.Set, resumeWorktrees map[string]string, transitionAuditor index.TransitionAuditor, workerAuditor *audit.Logger, opts Options) (WorkStageResult, error)

ExecuteWorkStage processes tasks in the open state through the work stage.

Jump to

Keyboard shortcuts

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