summaryrefslogtreecommitdiff
path: root/internal/task/task.go
blob: 3745e948f693108da64adac43174a52c2e3e7bff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package task

import (
	"time"
)

type State string

const (
	StatePending        State = "PENDING"
	StateQueued         State = "QUEUED"
	StateRunning        State = "RUNNING"
	StateReady          State = "READY"
	StateCompleted      State = "COMPLETED"
	StateFailed         State = "FAILED"
	StateTimedOut       State = "TIMED_OUT"
	StateCancelled      State = "CANCELLED"
	StateBudgetExceeded State = "BUDGET_EXCEEDED"
	StateBlocked        State = "BLOCKED"
)

type Priority string

const (
	PriorityHigh   Priority = "high"
	PriorityNormal Priority = "normal"
	PriorityLow    Priority = "low"
)

type AgentConfig struct {
	Type  string `yaml:"type"               json:"type"`
	Model string `yaml:"model"               json:"model"`
	// Role, when non-empty, names an internal/role.RoleConfig to dispatch
	// through: internal/executor.Pool.execute() resolves tier 0 of the
	// active role_configs row's EscalationLadder for the initial dispatch
	// (setting Type/Model from the resolved rung), and internal/scheduler
	// walks the ladder on failure (retry-then-escalate). Tasks with
	// Role == "" (every existing YAML/chatbot task shape) are completely
	// unaffected — this is purely additive.
	Role               string   `yaml:"role,omitempty" json:"role,omitempty"`
	ContextFiles       []string `yaml:"context_files"       json:"context_files"`
	Instructions       string   `yaml:"instructions"        json:"instructions"`
	ContainerImage     string   `yaml:"container_image"     json:"container_image"`
	MaxBudgetUSD       float64  `yaml:"max_budget_usd"      json:"max_budget_usd"`
	PermissionMode     string   `yaml:"permission_mode"     json:"permission_mode"`
	AllowedTools       []string `yaml:"allowed_tools"       json:"allowed_tools"`
	DisallowedTools    []string `yaml:"disallowed_tools"    json:"disallowed_tools"`
	SystemPromptAppend string   `yaml:"system_prompt_append" json:"system_prompt_append"`
	AdditionalArgs     []string `yaml:"additional_args"     json:"additional_args"`
	ProjectDir         string   `yaml:"project_dir"         json:"project_dir,omitempty"`
	SkipPlanning       bool     `yaml:"skip_planning"       json:"skip_planning"`

	// Local-runner sampling controls. Pointer for Temperature so a 0 value can
	// mean "deterministic" rather than "unset, use server default".
	Temperature *float64 `yaml:"temperature,omitempty" json:"temperature,omitempty"`
	MaxTokens   int      `yaml:"max_tokens,omitempty"  json:"max_tokens,omitempty"`
}

type RetryConfig struct {
	MaxAttempts int    `yaml:"max_attempts" json:"max_attempts"`
	Backoff     string `yaml:"backoff"      json:"backoff"` // "linear", "exponential"
}

// GitCommit represents a single git commit created during a task execution.
type GitCommit struct {
	Hash    string `json:"hash"`
	Message string `json:"message"`
}

// Changestats records file/line change metrics from an agent execution.
type Changestats struct {
	FilesChanged int `json:"files_changed"`
	LinesAdded   int `json:"lines_added"`
	LinesRemoved int `json:"lines_removed"`
}

// Interaction records a single question/answer exchange between an agent and the user.
type Interaction struct {
	QuestionText string    `json:"question_text"`
	Options      []string  `json:"options,omitempty"`
	Answer       string    `json:"answer,omitempty"`
	AskedAt      time.Time `json:"asked_at"`
}

type Task struct {
	ID            string      `yaml:"id"            json:"id"`
	ParentTaskID  string      `yaml:"parent_task_id" json:"parent_task_id"`
	Name          string      `yaml:"name"          json:"name"`
	Description   string      `yaml:"description"    json:"description"`
	Project       string      `yaml:"project"        json:"project"` // Human-readable project name
	RepositoryURL string      `yaml:"repository_url" json:"repository_url"`
	Agent         AgentConfig `yaml:"agent"          json:"agent"`
	Timeout       Duration    `yaml:"timeout"        json:"timeout"`
	Retry         RetryConfig `yaml:"retry"          json:"retry"`
	Priority      Priority    `yaml:"priority"   json:"priority"`
	Tags          []string    `yaml:"tags"       json:"tags"`
	DependsOn     []string    `yaml:"depends_on" json:"depends_on"`
	// AcceptanceCriteria, when non-empty, states what this task's work must
	// satisfy — set by a decomposing parent via spawn_subtask's
	// acceptance_criteria parameter (mirrors story.Story.AcceptanceCriteria
	// exactly). Unused by execution itself; a later phase's arbitrated-review
	// generalization reads it when evaluating this task's work, falling back
	// to the enclosing story's own AcceptanceCriteria when empty.
	AcceptanceCriteria []string      `yaml:"acceptance_criteria" json:"acceptance_criteria"`
	BranchName         string        `yaml:"-"          json:"branch_name,omitempty"`
	State              State         `yaml:"-"          json:"state"`
	RejectionComment   string        `yaml:"-"          json:"rejection_comment,omitempty"`
	QuestionJSON       string        `yaml:"-"          json:"question,omitempty"`
	ElaborationInput   string        `yaml:"-"          json:"elaboration_input,omitempty"`
	Summary            string        `yaml:"-"          json:"summary,omitempty"`
	Interactions       []Interaction `yaml:"-"          json:"interactions,omitempty"`
	CreatedAt          time.Time     `yaml:"-"          json:"created_at"`
	UpdatedAt          time.Time     `yaml:"-"          json:"updated_at"`
	// NeedsReview is set by internal/scheduler.Scheduler when it resumes a
	// BLOCKED role-typed task past its ask_user-timeout with a system-authored
	// fallback answer rather than a real human answer — a flag for a human to
	// find and double-check later (GET /api/tasks?needs_review=true), not a
	// state-machine state.
	NeedsReview bool `yaml:"-" json:"needs_review,omitempty"`
}

// Duration wraps time.Duration for YAML unmarshaling from strings like "30m".
type Duration struct {
	time.Duration
}

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
	var s string
	if err := unmarshal(&s); err != nil {
		return err
	}
	dur, err := time.ParseDuration(s)
	if err != nil {
		return err
	}
	d.Duration = dur
	return nil
}

func (d Duration) MarshalYAML() (interface{}, error) {
	return d.Duration.String(), nil
}

// BatchFile represents a YAML file containing multiple tasks.
type BatchFile struct {
	Tasks []Task `yaml:"tasks"`
}

// validTransitions maps each state to the set of states it may transition into.
// COMPLETED is the only true terminal state (no outgoing edges).
// CANCELLED, FAILED, TIMED_OUT, and BUDGET_EXCEEDED all allow re-entry at QUEUED
// (restart or retry).
// READY may go back to PENDING on user rejection.
// BLOCKED may advance to READY when all subtasks complete, or back to QUEUED on user answer.
var validTransitions = map[State]map[State]bool{
	StatePending:        {StateQueued: true, StateCancelled: true},
	StateQueued:         {StateRunning: true, StateCancelled: true, StateReady: true, StateBudgetExceeded: true}, // READY: subtask delegation; BUDGET_EXCEEDED: dispatcher budget gate blocks before running
	StateRunning:        {StateReady: true, StateCompleted: true, StateFailed: true, StateTimedOut: true, StateCancelled: true, StateBudgetExceeded: true, StateBlocked: true},
	StateReady:          {StateCompleted: true, StatePending: true},
	StateFailed:         {StateQueued: true}, // retry
	StateTimedOut:       {StateQueued: true}, // retry or resume
	StateCancelled:      {StateQueued: true}, // restart
	StateBudgetExceeded: {StateQueued: true}, // retry
	StateBlocked:        {StateQueued: true, StateReady: true, StateCompleted: true, StateCancelled: true},
}

// ValidTransition returns true if moving from the current state to next is allowed.
func ValidTransition(from, to State) bool {
	return validTransitions[from][to]
}