planning

package
v0.3.0 Latest Latest
Warning

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

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

Documentation

Overview

Package planning is the Stage-1 namespace for task planning, decomposition, goals, and suggested tasks. See ../REFACTOR_PLAN.md.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildFormPrompt

func BuildFormPrompt(action *ActionRequired) string

BuildFormPrompt renders a human-readable form prompt for an ActionRequired.

func DecomposePrompt

func DecomposePrompt() string

DecomposePrompt returns a system prompt that instructs the LLM to break a task into numbered subtasks with titles, descriptions, and file lists.

func FormatResponse

func FormatResponse(response *FormResponse) string

FormatResponse renders a FormResponse as a human-readable string.

func FormatTasks

func FormatTasks(tasks []*SuggestedTask) string

FormatTasks formats a list of suggested tasks for display.

func Validate

func Validate(action *ActionRequired, response *FormResponse) []string

Validate checks a FormResponse against the ActionRequired field specs. It returns a slice of validation error strings (empty if valid).

Types

type ActionManager

type ActionManager struct {
	Pending  []*ActionRequired
	History  []*ActionRequired
	PromptFn func(action *ActionRequired) (*FormResponse, error)
	// contains filtered or unexported fields
}

ActionManager coordinates action-required requests, managing pending and historical forms and delegating presentation to the configured PromptFn.

func NewActionManager

func NewActionManager(promptFn func(*ActionRequired) (*FormResponse, error)) *ActionManager

NewActionManager creates an ActionManager with the given prompt function.

func (*ActionManager) Cancel

func (am *ActionManager) Cancel(id string)

Cancel removes a pending action-required by ID and marks it resolved.

func (*ActionManager) GetPending

func (am *ActionManager) GetPending() []*ActionRequired

GetPending returns the currently pending action-required requests.

func (*ActionManager) Request

func (am *ActionManager) Request(action *ActionRequired) (*FormResponse, error)

Request presents an action-required form to the user via PromptFn, waits for a response or timeout, validates the response, and returns it.

func (*ActionManager) RequestChoice

func (am *ActionManager) RequestChoice(title string, choices []string) (string, error)

RequestChoice is a convenience method that requests a single choice from the user.

func (*ActionManager) RequestConfirm

func (am *ActionManager) RequestConfirm(title string) (bool, error)

RequestConfirm is a convenience method that requests a yes/no confirmation from the user.

func (*ActionManager) RequestText

func (am *ActionManager) RequestText(title, description string) (string, error)

RequestText is a convenience method that requests a single text input from the user.

type ActionRequired

type ActionRequired struct {
	ID          string
	Title       string
	Description string
	Fields      []FormField
	Timeout     time.Duration
	Required    bool
	CreatedAt   time.Time
	Response    *FormResponse
	Resolved    bool
}

ActionRequired represents a structured mid-task data collection request presented to the user during agent execution.

type ExecutionPlan

type ExecutionPlan struct {
	Steps              []ExecutionStep
	TotalEstimatedTime time.Duration
	Parallelizable     bool
	Dependencies       map[string][]string // step ID -> list of step IDs it depends on
}

ExecutionPlan represents the full plan for executing a batch of tool calls, including ordering, parallelization groups, and timing estimates.

type ExecutionPlanner

type ExecutionPlanner struct {
	ToolTimings map[string]time.Duration
	// contains filtered or unexported fields
}

ExecutionPlanner analyzes tool calls and determines optimal execution order and parallelization opportunities based on dependency analysis and timing data.

func NewExecutionPlanner

func NewExecutionPlanner() *ExecutionPlanner

NewExecutionPlanner creates an ExecutionPlanner with default timing estimates for common tool operations.

func (*ExecutionPlanner) EstimateDuration

func (ep *ExecutionPlanner) EstimateDuration(plan *ExecutionPlan) time.Duration

EstimateDuration calculates the total estimated execution time for a plan, accounting for parallelism within groups. The total time is the sum of the maximum duration within each group.

func (*ExecutionPlanner) FindDependencies

func (ep *ExecutionPlanner) FindDependencies(calls []PlannedCall) map[string][]string

FindDependencies builds a dependency graph from the planned calls based on file target analysis. A write/edit to file X creates a dependency for any subsequent read/edit of the same file.

func (*ExecutionPlanner) FormatPlan

func (ep *ExecutionPlanner) FormatPlan(plan *ExecutionPlan) string

FormatPlan produces a human-readable representation of the execution plan showing groups, parallelism, and timing estimates.

func (*ExecutionPlanner) GroupParallel

func (ep *ExecutionPlanner) GroupParallel(plan *ExecutionPlan) [][]ExecutionStep

GroupParallel groups execution steps that can run simultaneously into batches. Steps within the same group have no mutual dependencies and can execute in parallel.

func (*ExecutionPlanner) Optimize

func (ep *ExecutionPlanner) Optimize(plan *ExecutionPlan) *ExecutionPlan

Optimize reorders plan steps to minimize total execution time by maximizing parallelism. It reassigns priorities and groups to achieve the optimal schedule.

func (*ExecutionPlanner) Plan

func (ep *ExecutionPlanner) Plan(toolCalls []PlannedCall) *ExecutionPlan

Plan analyzes the given tool calls for dependencies and groups them into an optimized execution plan that maximizes parallelism while respecting ordering constraints.

func (*ExecutionPlanner) RecordTiming

func (ep *ExecutionPlanner) RecordTiming(tool string, duration time.Duration)

RecordTiming updates the timing estimate for a tool based on actual observed duration. Uses exponential moving average to smooth estimates.

type ExecutionStep

type ExecutionStep struct {
	ID                string
	ToolName          string
	Args              map[string]interface{}
	DependsOn         []string
	EstimatedDuration time.Duration
	CanParallel       bool
	Priority          int
	Group             int
}

ExecutionStep represents a single tool invocation within an execution plan.

type FormField

type FormField struct {
	Name       string
	Label      string
	Type       string // "text", "choice", "boolean", "number", "password"
	Required   bool
	Default    string
	Choices    []string
	Validation string // regex pattern
}

FormField defines a single input field in an action-required form.

type FormResponse

type FormResponse struct {
	Values      map[string]string
	SubmittedAt time.Time
	TimedOut    bool
}

FormResponse holds the user's submitted values for an action-required form.

type Goal

type Goal struct {
	ID           string
	Description  string
	Status       GoalStatus
	SubGoals     []Goal
	TokenBudget  int
	TokensUsed   int
	CreatedAt    time.Time
	CompletedAt  *time.Time
	Priority     int // 1=highest, 5=lowest
	Dependencies []string
	Tags         []string
	Progress     float64 // 0.0 - 1.0
	ParentID     string  // empty if top-level
}

Goal represents a tracked objective within a session.

type GoalEvent

type GoalEvent struct {
	GoalID    string
	EventType string // "created", "started", "completed", "failed", "blocked", "progress"
	Message   string
	Timestamp time.Time
}

GoalEvent records a state change in the goal lifecycle.

type GoalOption

type GoalOption func(*Goal)

GoalOption is a functional option for configuring a new goal.

func WithBudget

func WithBudget(tokens int) GoalOption

WithBudget sets the maximum token budget for the goal.

func WithDependencies

func WithDependencies(deps ...string) GoalOption

WithDependencies sets the IDs of goals that must complete before this one.

func WithPriority

func WithPriority(p int) GoalOption

WithPriority sets the goal's priority (1=highest, 5=lowest).

func WithTags

func WithTags(tags ...string) GoalOption

WithTags assigns tags to the goal for filtering/categorization.

type GoalStatus

type GoalStatus string

GoalStatus represents the current state of a goal.

const (
	GoalPending    GoalStatus = "pending"
	GoalInProgress GoalStatus = "in_progress"
	GoalCompleted  GoalStatus = "completed"
	GoalBlocked    GoalStatus = "blocked"
	GoalFailed     GoalStatus = "failed"
)

type GoalTracker

type GoalTracker struct {
	Goals      map[string]*Goal
	ActiveGoal *Goal

	History []GoalEvent
	// contains filtered or unexported fields
}

GoalTracker manages the lifecycle and scheduling of goals.

func NewGoalTracker

func NewGoalTracker() *GoalTracker

NewGoalTracker creates and returns an initialized GoalTracker.

func (*GoalTracker) AddGoal

func (gt *GoalTracker) AddGoal(description string, opts ...GoalOption) *Goal

AddGoal creates a new goal with an auto-generated ID and applies options.

func (*GoalTracker) BuildGoalContext

func (gt *GoalTracker) BuildGoalContext() string

BuildGoalContext formats the current goal state for injection into the system prompt.

func (*GoalTracker) CompleteGoal

func (gt *GoalTracker) CompleteGoal(id string) error

CompleteGoal marks a goal as completed and records the completion time. If the goal is a sub-goal, it checks whether the parent can advance.

func (*GoalTracker) ContinuationPrompt

func (gt *GoalTracker) ContinuationPrompt() string

ContinuationPrompt generates a prompt when goals remain incomplete.

func (*GoalTracker) DecomposeGoal

func (gt *GoalTracker) DecomposeGoal(id string, subDescriptions []string) error

DecomposeGoal splits a goal into sub-goals. The parent goal completes automatically when all sub-goals are completed.

func (*GoalTracker) FailGoal

func (gt *GoalTracker) FailGoal(id string, reason string) error

FailGoal marks a goal as failed with a reason.

func (*GoalTracker) GetNextGoal

func (gt *GoalTracker) GetNextGoal() *Goal

GetNextGoal returns the highest-priority unblocked goal. It prefers goals already in_progress, then pending goals ordered by priority.

func (*GoalTracker) IsBudgetExceeded

func (gt *GoalTracker) IsBudgetExceeded(id string) bool

IsBudgetExceeded returns true if the goal has exceeded its token budget.

func (*GoalTracker) RecordTokens

func (gt *GoalTracker) RecordTokens(id string, tokens int)

RecordTokens adds token usage to a goal's running total.

func (*GoalTracker) StartGoal

func (gt *GoalTracker) StartGoal(id string) error

StartGoal transitions a goal to in_progress and sets it as the active goal.

func (*GoalTracker) UpdateProgress

func (gt *GoalTracker) UpdateProgress(id string, progress float64)

UpdateProgress sets the progress for a goal (clamped to 0.0-1.0).

type PlanState

type PlanState struct {
	Name     string
	Subtasks []Subtask
	Current  int
	Active   bool
}

PlanState tracks progress through a set of subtasks.

func NewPlanState

func NewPlanState(name string) *PlanState

NewPlanState creates a new plan with the given name and no subtasks.

func (*PlanState) Format

func (ps *PlanState) Format() string

Format returns a human-readable display of the plan state.

func (*PlanState) MarkDone

func (ps *PlanState) MarkDone(id int)

MarkDone sets the subtask with the given ID to "done".

func (*PlanState) Next

func (ps *PlanState) Next() *Subtask

Next returns the next pending subtask and marks it as in_progress, or nil if none remain.

func (*PlanState) Progress

func (ps *PlanState) Progress() string

Progress returns a short progress string like "3/7 subtasks complete".

func (*PlanState) Skip

func (ps *PlanState) Skip(id int)

Skip sets the subtask with the given ID to "skipped".

type PlannedCall

type PlannedCall struct {
	ToolName string
	Args     map[string]interface{}
	Targets  []string // files affected by this call
}

PlannedCall describes a tool call to be planned, including which files it targets.

type Subtask

type Subtask struct {
	ID          int
	Title       string
	Description string
	Files       []string
	Status      string // "pending", "in_progress", "done", "skipped"
}

Subtask represents a single unit of work within a plan.

func ParseSubtasks

func ParseSubtasks(output string) []Subtask

ParseSubtasks parses LLM output formatted as numbered subtasks. Expected format:

  1. Title here Description of what to do Files: path/to/file.go, another/file.go

type SuggestedTask

type SuggestedTask struct {
	ID          string
	Title       string
	Description string
	Priority    int    // 1=highest (critical), 5=lowest (nice-to-have)
	Category    string // "fix", "improve", "test", "docs", "cleanup", "security"
	Source      string // "git", "lint", "test", "todo", "pr"
	Actionable  bool
	Command     string // suggested hawk command to run
}

SuggestedTask represents a proactive task suggestion based on repository state.

func ScanGitTasks

func ScanGitTasks(projectDir string) []*SuggestedTask

ScanGitTasks scans the git repository for actionable git-related tasks.

func ScanTODOs

func ScanTODOs(projectDir string) []*SuggestedTask

ScanTODOs walks source files looking for TODO, FIXME, and HACK comments.

func ScanTestFailures

func ScanTestFailures(projectDir string) []*SuggestedTask

ScanTestFailures runs a quick test check and generates tasks for failures.

type Task

type Task struct {
	ID              string
	Description     string
	Type            string // "read", "analyze", "plan", "implement", "test", "review"
	Dependencies    []string
	EstimatedTokens int
	Priority        int
	Status          string // "pending", "running", "done", "failed"
	Result          string
}

Task represents a single unit of work within a decomposed plan.

type TaskDecomposer

type TaskDecomposer struct {
	MaxTasks int
	// contains filtered or unexported fields
}

TaskDecomposer breaks complex goals into ordered sub-tasks.

func NewTaskDecomposer

func NewTaskDecomposer() *TaskDecomposer

NewTaskDecomposer creates a TaskDecomposer with default settings.

func (*TaskDecomposer) DebuggingPlan

func (td *TaskDecomposer) DebuggingPlan(goal string) []Task

DebuggingPlan returns the task sequence for fixing a bug.

func (*TaskDecomposer) Decompose

func (td *TaskDecomposer) Decompose(goal string) *TaskPlan

Decompose analyzes a goal and returns a structured TaskPlan.

func (*TaskDecomposer) DetectPattern

func (td *TaskDecomposer) DetectPattern(goal string) string

DetectPattern determines the type of work from goal keywords.

func (*TaskDecomposer) EstimateComplexity

func (td *TaskDecomposer) EstimateComplexity(goal string) int

EstimateComplexity scores a goal's complexity based on word count and keyword multipliers.

func (*TaskDecomposer) FindParallelGroups

func (td *TaskDecomposer) FindParallelGroups(tasks []Task) [][]string

FindParallelGroups groups tasks by dependency level so independent tasks can run concurrently within the same group.

func (*TaskDecomposer) FormatPlan

func (td *TaskDecomposer) FormatPlan(plan *TaskPlan) string

FormatPlan returns a human-readable display of the task plan.

func (*TaskDecomposer) ImplementationPlan

func (td *TaskDecomposer) ImplementationPlan(goal string) []Task

ImplementationPlan returns the task sequence for implementing a feature.

func (*TaskDecomposer) RefactoringPlan

func (td *TaskDecomposer) RefactoringPlan(goal string) []Task

RefactoringPlan returns the task sequence for refactoring code.

func (*TaskDecomposer) TestingPlan

func (td *TaskDecomposer) TestingPlan(goal string) []Task

TestingPlan returns the task sequence for adding tests.

type TaskPlan

type TaskPlan struct {
	Goal           string
	Tasks          []Task
	EstimatedTotal int
	Parallel       [][]string // groups of task IDs that can run concurrently
}

TaskPlan holds a full decomposition of a goal into ordered tasks.

type TaskQueue

type TaskQueue struct {
	Tasks     []*SuggestedTask
	Dismissed []string
	// contains filtered or unexported fields
}

TaskQueue manages a queue of suggested tasks with dismissal tracking.

func NewTaskQueue

func NewTaskQueue() *TaskQueue

NewTaskQueue creates a new empty TaskQueue.

func (*TaskQueue) Dismiss

func (tq *TaskQueue) Dismiss(taskID string)

Dismiss marks a task as dismissed so it won't appear in future GetTop calls.

func (*TaskQueue) GetTop

func (tq *TaskQueue) GetTop(n int) []*SuggestedTask

GetTop returns the top N suggested tasks by priority, excluding dismissed ones.

func (*TaskQueue) Refresh

func (tq *TaskQueue) Refresh(projectDir string) error

Refresh rescans the project directory and updates the task queue.

func (*TaskQueue) Scan

func (tq *TaskQueue) Scan(projectDir string) ([]*SuggestedTask, error)

Scan scans the project directory for actionable items from multiple sources.

Jump to

Keyboard shortcuts

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