| iomodo | dea44b0 | 2025-07-29 12:55:25 +0400 | [diff] [blame] | 1 | package task |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 7 | "log/slog" |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 8 | "os" |
| 9 | "os/exec" |
| 10 | "path/filepath" |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 11 | "strings" |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 12 | "time" |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 13 | |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 14 | "github.com/iomodo/staff/git" |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 15 | "github.com/iomodo/staff/llm" |
| 16 | "github.com/iomodo/staff/tm" |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 17 | "golang.org/x/text/cases" |
| 18 | "golang.org/x/text/language" |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 19 | ) |
| 20 | |
| 21 | // SubtaskService handles subtask generation and management |
| 22 | type SubtaskService struct { |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 23 | llmProvider llm.LLMProvider |
| 24 | taskManager tm.TaskManager |
| 25 | agentRoles []string // Available agent roles for assignment |
| 26 | prProvider git.PullRequestProvider // GitHub PR provider |
| 27 | githubOwner string |
| 28 | githubRepo string |
| 29 | cloneManager *git.CloneManager |
| 30 | logger *slog.Logger |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 31 | } |
| 32 | |
| 33 | // NewSubtaskService creates a new subtask service |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 34 | func NewSubtaskService(provider llm.LLMProvider, taskManager tm.TaskManager, agentRoles []string, prProvider git.PullRequestProvider, githubOwner, githubRepo string, cloneManager *git.CloneManager, logger *slog.Logger) *SubtaskService { |
| 35 | if logger == nil { |
| 36 | logger = slog.Default() |
| 37 | } |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 38 | return &SubtaskService{ |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 39 | llmProvider: provider, |
| 40 | taskManager: taskManager, |
| 41 | agentRoles: agentRoles, |
| 42 | prProvider: prProvider, |
| 43 | githubOwner: githubOwner, |
| 44 | githubRepo: githubRepo, |
| 45 | cloneManager: cloneManager, |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 46 | logger: logger, |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 47 | } |
| 48 | } |
| 49 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 50 | // ShouldGenerateSubtasks asks LLM whether a task needs subtasks based on existing agents |
| 51 | func (s *SubtaskService) ShouldGenerateSubtasks(ctx context.Context, task *tm.Task) (*tm.SubtaskDecision, error) { |
| 52 | prompt := s.buildSubtaskDecisionPrompt(task) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 53 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 54 | req := llm.ChatCompletionRequest{ |
| 55 | Model: "gpt-4", |
| 56 | Messages: []llm.Message{ |
| 57 | { |
| 58 | Role: llm.RoleSystem, |
| 59 | Content: s.getSubtaskDecisionSystemPrompt(), |
| 60 | }, |
| 61 | { |
| 62 | Role: llm.RoleUser, |
| 63 | Content: prompt, |
| 64 | }, |
| 65 | }, |
| 66 | MaxTokens: &[]int{1000}[0], |
| 67 | Temperature: &[]float64{0.3}[0], |
| 68 | } |
| 69 | |
| 70 | resp, err := s.llmProvider.ChatCompletion(ctx, req) |
| 71 | if err != nil { |
| 72 | return nil, fmt.Errorf("LLM decision failed: %w", err) |
| 73 | } |
| 74 | |
| 75 | if len(resp.Choices) == 0 { |
| 76 | return nil, fmt.Errorf("no response from LLM") |
| 77 | } |
| 78 | |
| 79 | // Parse the LLM response |
| 80 | decision, err := s.parseSubtaskDecision(resp.Choices[0].Message.Content) |
| 81 | if err != nil { |
| 82 | return nil, fmt.Errorf("failed to parse LLM decision: %w", err) |
| 83 | } |
| 84 | |
| 85 | return decision, nil |
| 86 | } |
| 87 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 88 | // AnalyzeTaskForSubtasks uses LLM to analyze a task and propose subtasks |
| 89 | func (s *SubtaskService) AnalyzeTaskForSubtasks(ctx context.Context, task *tm.Task) (*tm.SubtaskAnalysis, error) { |
| 90 | prompt := s.buildSubtaskAnalysisPrompt(task) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 91 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 92 | req := llm.ChatCompletionRequest{ |
| 93 | Model: "gpt-4", |
| 94 | Messages: []llm.Message{ |
| 95 | { |
| 96 | Role: llm.RoleSystem, |
| 97 | Content: s.getSubtaskAnalysisSystemPrompt(), |
| 98 | }, |
| 99 | { |
| 100 | Role: llm.RoleUser, |
| 101 | Content: prompt, |
| 102 | }, |
| 103 | }, |
| 104 | MaxTokens: &[]int{4000}[0], |
| 105 | Temperature: &[]float64{0.3}[0], |
| 106 | } |
| 107 | |
| 108 | resp, err := s.llmProvider.ChatCompletion(ctx, req) |
| 109 | if err != nil { |
| 110 | return nil, fmt.Errorf("LLM analysis failed: %w", err) |
| 111 | } |
| 112 | |
| 113 | if len(resp.Choices) == 0 { |
| 114 | return nil, fmt.Errorf("no response from LLM") |
| 115 | } |
| 116 | |
| 117 | // Parse the LLM response |
| 118 | analysis, err := s.parseSubtaskAnalysis(resp.Choices[0].Message.Content, task.ID) |
| 119 | if err != nil { |
| 120 | return nil, fmt.Errorf("failed to parse LLM response: %w", err) |
| 121 | } |
| 122 | |
| 123 | return analysis, nil |
| 124 | } |
| 125 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 126 | // getSubtaskDecisionSystemPrompt returns the system prompt for subtask decision |
| 127 | func (s *SubtaskService) getSubtaskDecisionSystemPrompt() string { |
| 128 | availableRoles := strings.Join(s.agentRoles, ", ") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 129 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 130 | return fmt.Sprintf(`You are an expert project manager and task analyst. Your job is to determine whether a task needs to be broken down into subtasks. |
| 131 | |
| 132 | Currently available team roles and their capabilities: %s |
| 133 | |
| 134 | When evaluating a task, consider: |
| 135 | 1. Task complexity and scope |
| 136 | 2. Whether multiple specialized skills are needed |
| 137 | 3. If the task can be completed by a single agent with current capabilities |
| 138 | 4. Whether new agent roles might be needed for specialized skills |
| 139 | |
| 140 | Respond with a JSON object in this exact format: |
| 141 | { |
| 142 | "needs_subtasks": true/false, |
| 143 | "reasoning": "Clear explanation of why subtasks are or aren't needed", |
| 144 | "complexity_score": 5, |
| 145 | "required_skills": ["skill1", "skill2", "skill3"] |
| 146 | } |
| 147 | |
| 148 | Complexity score should be 1-10 where: |
| 149 | - 1-3: Simple tasks that can be handled by one agent |
| 150 | - 4-6: Moderate complexity, might benefit from subtasks |
| 151 | - 7-10: Complex tasks that definitely need breaking down |
| 152 | |
| 153 | Required skills should list all technical/domain skills needed to complete the task.`, availableRoles) |
| 154 | } |
| 155 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 156 | // getSubtaskAnalysisSystemPrompt returns the system prompt for subtask analysis |
| 157 | func (s *SubtaskService) getSubtaskAnalysisSystemPrompt() string { |
| 158 | availableRoles := strings.Join(s.agentRoles, ", ") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 159 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 160 | return fmt.Sprintf(`You are an expert project manager and technical architect. Your job is to analyze complex tasks and break them down into well-defined subtasks that can be assigned to specialized team members. |
| 161 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 162 | Currently available team roles: %s |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 163 | |
| 164 | When analyzing a task, you should: |
| 165 | 1. Understand the task requirements and scope |
| 166 | 2. Break it down into logical, manageable subtasks |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 167 | 3. Assign each subtask to the most appropriate team role OR propose creating new agents |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 168 | 4. Estimate effort and identify dependencies |
| 169 | 5. Provide a clear execution strategy |
| 170 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 171 | If you need specialized skills not covered by existing roles, propose new agent creation. |
| 172 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 173 | Respond with a JSON object in this exact format: |
| 174 | { |
| 175 | "analysis_summary": "Brief analysis of the task and approach", |
| 176 | "subtasks": [ |
| 177 | { |
| 178 | "title": "Subtask title", |
| 179 | "description": "Detailed description of what needs to be done", |
| 180 | "priority": "high|medium|low", |
| 181 | "assigned_to": "role_name", |
| 182 | "estimated_hours": 8, |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 183 | "dependencies": ["subtask_index_1", "subtask_index_2"], |
| 184 | "required_skills": ["skill1", "skill2"] |
| 185 | } |
| 186 | ], |
| 187 | "agent_creations": [ |
| 188 | { |
| 189 | "role": "new_role_name", |
| 190 | "skills": ["specialized_skill1", "specialized_skill2"], |
| 191 | "description": "Description of what this agent does", |
| 192 | "justification": "Why this new agent is needed" |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 193 | } |
| 194 | ], |
| 195 | "recommended_approach": "High-level strategy for executing these subtasks", |
| 196 | "estimated_total_hours": 40, |
| 197 | "risk_assessment": "Potential risks and mitigation strategies" |
| 198 | } |
| 199 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 200 | For existing roles, use: %s |
| 201 | For new agents, propose appropriate role names and skill sets. |
| 202 | Dependencies should reference subtask indices (e.g., ["0", "1"] means depends on first and second subtasks).`, availableRoles, availableRoles) |
| 203 | } |
| 204 | |
| 205 | // buildSubtaskDecisionPrompt creates the user prompt for subtask decision |
| 206 | func (s *SubtaskService) buildSubtaskDecisionPrompt(task *tm.Task) string { |
| 207 | return fmt.Sprintf(`Please evaluate whether the following task needs to be broken down into subtasks: |
| 208 | |
| 209 | **Task Title:** %s |
| 210 | |
| 211 | **Description:** %s |
| 212 | |
| 213 | **Priority:** %s |
| 214 | |
| 215 | **Current Status:** %s |
| 216 | |
| 217 | Consider: |
| 218 | - Can this be completed by a single agent with existing capabilities? |
| 219 | - Does it require multiple specialized skills? |
| 220 | - Is the scope too large for one person? |
| 221 | - Are there logical components that could be parallelized? |
| 222 | |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 223 | Provide your decision in the JSON format specified in the system prompt.`, |
| 224 | task.Title, |
| 225 | task.Description, |
| 226 | task.Priority, |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 227 | task.Status) |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 228 | } |
| 229 | |
| 230 | // buildSubtaskAnalysisPrompt creates the user prompt for LLM analysis |
| 231 | func (s *SubtaskService) buildSubtaskAnalysisPrompt(task *tm.Task) string { |
| 232 | return fmt.Sprintf(`Please analyze the following task and break it down into subtasks: |
| 233 | |
| 234 | **Task Title:** %s |
| 235 | |
| 236 | **Description:** %s |
| 237 | |
| 238 | **Priority:** %s |
| 239 | |
| 240 | **Current Status:** %s |
| 241 | |
| 242 | Please analyze this task and provide a detailed breakdown into subtasks. Consider: |
| 243 | - Technical complexity and requirements |
| 244 | - Logical task dependencies |
| 245 | - Appropriate skill sets needed for each subtask |
| 246 | - Risk factors and potential blockers |
| 247 | - Estimated effort for each component |
| 248 | |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 249 | Provide the analysis in the JSON format specified in the system prompt.`, |
| 250 | task.Title, |
| 251 | task.Description, |
| 252 | task.Priority, |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 253 | task.Status) |
| 254 | } |
| 255 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 256 | // parseSubtaskDecision parses the LLM response into a SubtaskDecision struct |
| 257 | func (s *SubtaskService) parseSubtaskDecision(response string) (*tm.SubtaskDecision, error) { |
| 258 | // Try to extract JSON from the response |
| 259 | jsonStart := strings.Index(response, "{") |
| 260 | jsonEnd := strings.LastIndex(response, "}") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 261 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 262 | if jsonStart == -1 || jsonEnd == -1 { |
| 263 | return nil, fmt.Errorf("no JSON found in LLM response") |
| 264 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 265 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 266 | jsonStr := response[jsonStart : jsonEnd+1] |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 267 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 268 | var decision tm.SubtaskDecision |
| 269 | if err := json.Unmarshal([]byte(jsonStr), &decision); err != nil { |
| 270 | return nil, fmt.Errorf("failed to unmarshal JSON: %w", err) |
| 271 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 272 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 273 | return &decision, nil |
| 274 | } |
| 275 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 276 | // parseSubtaskAnalysis parses the LLM response into a SubtaskAnalysis struct |
| 277 | func (s *SubtaskService) parseSubtaskAnalysis(response string, parentTaskID string) (*tm.SubtaskAnalysis, error) { |
| 278 | // Try to extract JSON from the response (LLM might wrap it in markdown) |
| 279 | jsonStart := strings.Index(response, "{") |
| 280 | jsonEnd := strings.LastIndex(response, "}") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 281 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 282 | if jsonStart == -1 || jsonEnd == -1 { |
| 283 | return nil, fmt.Errorf("no JSON found in LLM response") |
| 284 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 285 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 286 | jsonStr := response[jsonStart : jsonEnd+1] |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 287 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 288 | var rawAnalysis struct { |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 289 | AnalysisSummary string `json:"analysis_summary"` |
| 290 | Subtasks []struct { |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 291 | Title string `json:"title"` |
| 292 | Description string `json:"description"` |
| 293 | Priority string `json:"priority"` |
| 294 | AssignedTo string `json:"assigned_to"` |
| 295 | EstimatedHours int `json:"estimated_hours"` |
| 296 | Dependencies []string `json:"dependencies"` |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 297 | RequiredSkills []string `json:"required_skills"` |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 298 | } `json:"subtasks"` |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 299 | AgentCreations []tm.AgentCreationProposal `json:"agent_creations"` |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 300 | RecommendedApproach string `json:"recommended_approach"` |
| 301 | EstimatedTotalHours int `json:"estimated_total_hours"` |
| 302 | RiskAssessment string `json:"risk_assessment"` |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 303 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 304 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 305 | if err := json.Unmarshal([]byte(jsonStr), &rawAnalysis); err != nil { |
| 306 | return nil, fmt.Errorf("failed to unmarshal JSON: %w", err) |
| 307 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 308 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 309 | // Convert to our types |
| 310 | analysis := &tm.SubtaskAnalysis{ |
| 311 | ParentTaskID: parentTaskID, |
| 312 | AnalysisSummary: rawAnalysis.AnalysisSummary, |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 313 | AgentCreations: rawAnalysis.AgentCreations, |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 314 | RecommendedApproach: rawAnalysis.RecommendedApproach, |
| 315 | EstimatedTotalHours: rawAnalysis.EstimatedTotalHours, |
| 316 | RiskAssessment: rawAnalysis.RiskAssessment, |
| 317 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 318 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 319 | // Convert subtasks |
| 320 | for _, st := range rawAnalysis.Subtasks { |
| 321 | priority := tm.PriorityMedium // default |
| 322 | switch strings.ToLower(st.Priority) { |
| 323 | case "high": |
| 324 | priority = tm.PriorityHigh |
| 325 | case "low": |
| 326 | priority = tm.PriorityLow |
| 327 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 328 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 329 | subtask := tm.SubtaskProposal{ |
| 330 | Title: st.Title, |
| 331 | Description: st.Description, |
| 332 | Priority: priority, |
| 333 | AssignedTo: st.AssignedTo, |
| 334 | EstimatedHours: st.EstimatedHours, |
| 335 | Dependencies: st.Dependencies, |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 336 | RequiredSkills: st.RequiredSkills, |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 337 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 338 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 339 | analysis.Subtasks = append(analysis.Subtasks, subtask) |
| 340 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 341 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 342 | // Validate agent assignments and handle new agent creation |
| 343 | if err := s.validateAndHandleAgentAssignments(analysis); err != nil { |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 344 | s.logger.Warn("Warning during agent assignment handling", slog.String("error", err.Error())) |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 345 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 346 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 347 | return analysis, nil |
| 348 | } |
| 349 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 350 | // validateAndHandleAgentAssignments validates assignments and creates agent creation subtasks if needed |
| 351 | func (s *SubtaskService) validateAndHandleAgentAssignments(analysis *tm.SubtaskAnalysis) error { |
| 352 | // Collect all agent roles that will be available (existing + proposed new ones) |
| 353 | availableRoles := make(map[string]bool) |
| 354 | for _, role := range s.agentRoles { |
| 355 | availableRoles[role] = true |
| 356 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 357 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 358 | // Add proposed new agent roles |
| 359 | for _, agentCreation := range analysis.AgentCreations { |
| 360 | availableRoles[agentCreation.Role] = true |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 361 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 362 | // Create a subtask for agent creation |
| 363 | agentCreationSubtask := tm.SubtaskProposal{ |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 364 | Title: fmt.Sprintf("Create %s Agent", cases.Title(language.English).String(agentCreation.Role)), |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 365 | Description: fmt.Sprintf("Create and configure a new %s agent with skills: %s. %s", agentCreation.Role, strings.Join(agentCreation.Skills, ", "), agentCreation.Justification), |
| 366 | Priority: tm.PriorityHigh, // Agent creation is high priority |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 367 | AssignedTo: "ceo", // CEO creates new agents |
| 368 | EstimatedHours: 4, // Estimated time to set up new agent |
| 369 | Dependencies: []string{}, // No dependencies for agent creation |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 370 | RequiredSkills: []string{"agent_configuration", "system_design"}, |
| 371 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 372 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 373 | // Insert at the beginning so agent creation happens first |
| 374 | analysis.Subtasks = append([]tm.SubtaskProposal{agentCreationSubtask}, analysis.Subtasks...) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 375 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 376 | // Update dependencies to account for the new subtask at index 0 |
| 377 | for i := 1; i < len(analysis.Subtasks); i++ { |
| 378 | for j, dep := range analysis.Subtasks[i].Dependencies { |
| 379 | // Convert dependency index and increment by 1 |
| 380 | if depIndex := s.parseDependencyIndex(dep); depIndex >= 0 { |
| 381 | analysis.Subtasks[i].Dependencies[j] = fmt.Sprintf("%d", depIndex+1) |
| 382 | } |
| 383 | } |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 384 | } |
| 385 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 386 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 387 | // Now validate all assignments against available roles |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 388 | defaultRole := "ceo" // fallback role |
| 389 | if len(s.agentRoles) > 0 { |
| 390 | defaultRole = s.agentRoles[0] |
| 391 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 392 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 393 | for i := range analysis.Subtasks { |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 394 | if !availableRoles[analysis.Subtasks[i].AssignedTo] { |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 395 | s.logger.Warn("Unknown agent role for subtask, using default", |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 396 | slog.String("unknown_role", analysis.Subtasks[i].AssignedTo), |
| 397 | slog.String("subtask_title", analysis.Subtasks[i].Title), |
| 398 | slog.String("assigned_role", defaultRole)) |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 399 | analysis.Subtasks[i].AssignedTo = defaultRole |
| 400 | } |
| 401 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 402 | |
| iomodo | 5c99a44 | 2025-07-28 14:23:52 +0400 | [diff] [blame] | 403 | return nil |
| 404 | } |
| 405 | |
| 406 | // parseDependencyIndex parses a dependency string to an integer index |
| 407 | func (s *SubtaskService) parseDependencyIndex(dep string) int { |
| 408 | var idx int |
| 409 | if _, err := fmt.Sscanf(dep, "%d", &idx); err == nil { |
| 410 | return idx |
| 411 | } |
| 412 | return -1 // Invalid dependency format |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 413 | } |
| 414 | |
| 415 | // isValidAgentRole checks if a role is in the available agent roles |
| 416 | func (s *SubtaskService) isValidAgentRole(role string) bool { |
| 417 | for _, availableRole := range s.agentRoles { |
| 418 | if availableRole == role { |
| 419 | return true |
| 420 | } |
| 421 | } |
| 422 | return false |
| 423 | } |
| 424 | |
| 425 | // GenerateSubtaskPR creates a PR with the proposed subtasks |
| 426 | func (s *SubtaskService) GenerateSubtaskPR(ctx context.Context, analysis *tm.SubtaskAnalysis) (string, error) { |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 427 | if s.prProvider == nil { |
| 428 | return "", fmt.Errorf("PR provider not configured") |
| 429 | } |
| 430 | |
| 431 | // Generate branch name for subtask proposal |
| 432 | branchName := fmt.Sprintf("subtasks/%s-proposal", analysis.ParentTaskID) |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 433 | s.logger.Info("Creating subtask PR", slog.String("branch", branchName)) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 434 | |
| 435 | // Create Git branch and commit subtask proposal |
| 436 | if err := s.createSubtaskBranch(ctx, analysis, branchName); err != nil { |
| 437 | return "", fmt.Errorf("failed to create subtask branch: %w", err) |
| 438 | } |
| 439 | |
| 440 | // Generate PR content |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 441 | prContent := s.generateSubtaskPRContent(analysis) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 442 | title := fmt.Sprintf("Subtask Proposal: %s", analysis.ParentTaskID) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 443 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 444 | // Validate PR content |
| 445 | if title == "" { |
| 446 | return "", fmt.Errorf("PR title cannot be empty") |
| 447 | } |
| 448 | if prContent == "" { |
| 449 | return "", fmt.Errorf("PR description cannot be empty") |
| 450 | } |
| 451 | |
| 452 | // Determine base branch (try main first, fallback to master) |
| 453 | baseBranch := s.determineBaseBranch(ctx) |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 454 | s.logger.Info("Using base branch", slog.String("base_branch", baseBranch)) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 455 | |
| 456 | // Create the pull request |
| 457 | options := git.PullRequestOptions{ |
| 458 | Title: title, |
| 459 | Description: prContent, |
| 460 | HeadBranch: branchName, |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 461 | BaseBranch: baseBranch, |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 462 | Labels: []string{"subtasks", "proposal", "ai-generated"}, |
| 463 | Draft: false, |
| 464 | } |
| 465 | |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 466 | s.logger.Info("Creating PR with options", |
| 467 | slog.String("title", options.Title), |
| 468 | slog.String("head_branch", options.HeadBranch), |
| 469 | slog.String("base_branch", options.BaseBranch)) |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 470 | |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 471 | pr, err := s.prProvider.CreatePullRequest(ctx, options) |
| 472 | if err != nil { |
| 473 | return "", fmt.Errorf("failed to create PR: %w", err) |
| 474 | } |
| 475 | |
| 476 | prURL := fmt.Sprintf("https://github.com/%s/%s/pull/%d", s.githubOwner, s.githubRepo, pr.Number) |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 477 | s.logger.Info("Generated subtask proposal PR", slog.String("pr_url", prURL)) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 478 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 479 | return prURL, nil |
| 480 | } |
| 481 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 482 | // determineBaseBranch determines the correct base branch (main or master) |
| 483 | func (s *SubtaskService) determineBaseBranch(ctx context.Context) string { |
| 484 | if s.cloneManager == nil { |
| 485 | return "main" // default fallback |
| 486 | } |
| 487 | |
| 488 | // Get clone path to check branches |
| 489 | clonePath, err := s.cloneManager.GetAgentClonePath("subtask-service") |
| 490 | if err != nil { |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 491 | s.logger.Warn("Failed to get clone path for base branch detection", slog.String("error", err.Error())) |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 492 | return "main" |
| 493 | } |
| 494 | |
| 495 | // Check if main branch exists |
| 496 | gitCmd := func(args ...string) *exec.Cmd { |
| 497 | return exec.CommandContext(ctx, "git", append([]string{"-C", clonePath}, args...)...) |
| 498 | } |
| 499 | |
| 500 | // Try to checkout main branch |
| 501 | cmd := gitCmd("show-ref", "refs/remotes/origin/main") |
| 502 | if err := cmd.Run(); err == nil { |
| 503 | return "main" |
| 504 | } |
| 505 | |
| 506 | // Try to checkout master branch |
| 507 | cmd = gitCmd("show-ref", "refs/remotes/origin/master") |
| 508 | if err := cmd.Run(); err == nil { |
| 509 | return "master" |
| 510 | } |
| 511 | |
| 512 | // Default to main if neither can be detected |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 513 | s.logger.Warn("Could not determine base branch, defaulting to 'main'") |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 514 | return "main" |
| 515 | } |
| 516 | |
| 517 | // generateSubtaskFile creates the content for an individual subtask file |
| 518 | func (s *SubtaskService) generateSubtaskFile(subtask tm.SubtaskProposal, taskID, parentTaskID string) string { |
| 519 | var content strings.Builder |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 520 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 521 | // Generate YAML frontmatter |
| 522 | content.WriteString("---\n") |
| 523 | content.WriteString(fmt.Sprintf("id: %s\n", taskID)) |
| 524 | content.WriteString(fmt.Sprintf("title: %s\n", subtask.Title)) |
| 525 | content.WriteString(fmt.Sprintf("description: %s\n", subtask.Description)) |
| 526 | content.WriteString(fmt.Sprintf("assignee: %s\n", subtask.AssignedTo)) |
| 527 | content.WriteString(fmt.Sprintf("owner_id: %s\n", subtask.AssignedTo)) |
| 528 | content.WriteString(fmt.Sprintf("owner_name: %s\n", subtask.AssignedTo)) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 529 | content.WriteString("status: todo\n") |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 530 | content.WriteString(fmt.Sprintf("priority: %s\n", strings.ToLower(string(subtask.Priority)))) |
| 531 | content.WriteString(fmt.Sprintf("parent_task_id: %s\n", parentTaskID)) |
| 532 | content.WriteString(fmt.Sprintf("estimated_hours: %d\n", subtask.EstimatedHours)) |
| 533 | content.WriteString(fmt.Sprintf("created_at: %s\n", time.Now().Format(time.RFC3339))) |
| 534 | content.WriteString(fmt.Sprintf("updated_at: %s\n", time.Now().Format(time.RFC3339))) |
| 535 | content.WriteString("completed_at: null\n") |
| 536 | content.WriteString("archived_at: null\n") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 537 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 538 | // Add dependencies if any |
| 539 | if len(subtask.Dependencies) > 0 { |
| 540 | content.WriteString("dependencies:\n") |
| 541 | for _, dep := range subtask.Dependencies { |
| 542 | // Convert dependency index to actual subtask ID |
| 543 | if depIndex := s.parseDependencyIndex(dep); depIndex >= 0 { |
| 544 | depTaskID := fmt.Sprintf("%s-subtask-%d", parentTaskID, depIndex+1) |
| 545 | content.WriteString(fmt.Sprintf(" - %s\n", depTaskID)) |
| 546 | } |
| 547 | } |
| 548 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 549 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 550 | // Add required skills if any |
| 551 | if len(subtask.RequiredSkills) > 0 { |
| 552 | content.WriteString("required_skills:\n") |
| 553 | for _, skill := range subtask.RequiredSkills { |
| 554 | content.WriteString(fmt.Sprintf(" - %s\n", skill)) |
| 555 | } |
| 556 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 557 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 558 | content.WriteString("---\n\n") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 559 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 560 | // Add markdown content |
| 561 | content.WriteString("# Task Description\n\n") |
| 562 | content.WriteString(fmt.Sprintf("%s\n\n", subtask.Description)) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 563 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 564 | if subtask.EstimatedHours > 0 { |
| 565 | content.WriteString("## Estimated Effort\n\n") |
| 566 | content.WriteString(fmt.Sprintf("**Estimated Hours:** %d\n\n", subtask.EstimatedHours)) |
| 567 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 568 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 569 | if len(subtask.RequiredSkills) > 0 { |
| 570 | content.WriteString("## Required Skills\n\n") |
| 571 | for _, skill := range subtask.RequiredSkills { |
| 572 | content.WriteString(fmt.Sprintf("- %s\n", skill)) |
| 573 | } |
| 574 | content.WriteString("\n") |
| 575 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 576 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 577 | if len(subtask.Dependencies) > 0 { |
| 578 | content.WriteString("## Dependencies\n\n") |
| 579 | content.WriteString("This task depends on the completion of:\n\n") |
| 580 | for _, dep := range subtask.Dependencies { |
| 581 | if depIndex := s.parseDependencyIndex(dep); depIndex >= 0 { |
| 582 | depTaskID := fmt.Sprintf("%s-subtask-%d", parentTaskID, depIndex+1) |
| 583 | content.WriteString(fmt.Sprintf("- %s\n", depTaskID)) |
| 584 | } |
| 585 | } |
| 586 | content.WriteString("\n") |
| 587 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 588 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 589 | content.WriteString("## Notes\n\n") |
| 590 | content.WriteString(fmt.Sprintf("This subtask was generated from parent task: %s\n", parentTaskID)) |
| 591 | content.WriteString("Generated by Staff AI Agent System\n\n") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 592 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 593 | return content.String() |
| 594 | } |
| 595 | |
| 596 | // updateParentTaskAsCompleted updates the parent task file to mark it as completed |
| 597 | func (s *SubtaskService) updateParentTaskAsCompleted(taskFilePath string, analysis *tm.SubtaskAnalysis) error { |
| 598 | // Read the existing parent task file |
| 599 | content, err := os.ReadFile(taskFilePath) |
| 600 | if err != nil { |
| 601 | return fmt.Errorf("failed to read parent task file: %w", err) |
| 602 | } |
| 603 | |
| 604 | taskContent := string(content) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 605 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 606 | // Find the YAML frontmatter boundaries |
| 607 | lines := strings.Split(taskContent, "\n") |
| 608 | var frontmatterStart, frontmatterEnd int = -1, -1 |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 609 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 610 | for i, line := range lines { |
| 611 | if line == "---" { |
| 612 | if frontmatterStart == -1 { |
| 613 | frontmatterStart = i |
| 614 | } else { |
| 615 | frontmatterEnd = i |
| 616 | break |
| 617 | } |
| 618 | } |
| 619 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 620 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 621 | if frontmatterStart == -1 || frontmatterEnd == -1 { |
| 622 | return fmt.Errorf("invalid task file format: missing YAML frontmatter") |
| 623 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 624 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 625 | // Update the frontmatter |
| 626 | now := time.Now().Format(time.RFC3339) |
| 627 | var updatedLines []string |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 628 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 629 | // Add lines before frontmatter |
| 630 | updatedLines = append(updatedLines, lines[:frontmatterStart+1]...) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 631 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 632 | // Process frontmatter lines |
| 633 | for i := frontmatterStart + 1; i < frontmatterEnd; i++ { |
| 634 | line := lines[i] |
| 635 | if strings.HasPrefix(line, "status:") { |
| 636 | updatedLines = append(updatedLines, "status: completed") |
| 637 | } else if strings.HasPrefix(line, "updated_at:") { |
| 638 | updatedLines = append(updatedLines, fmt.Sprintf("updated_at: %s", now)) |
| 639 | } else if strings.HasPrefix(line, "completed_at:") { |
| 640 | updatedLines = append(updatedLines, fmt.Sprintf("completed_at: %s", now)) |
| 641 | } else { |
| 642 | updatedLines = append(updatedLines, line) |
| 643 | } |
| 644 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 645 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 646 | // Add closing frontmatter and rest of content |
| 647 | updatedLines = append(updatedLines, lines[frontmatterEnd:]...) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 648 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 649 | // Add subtask information to the task description |
| 650 | if frontmatterEnd+1 < len(lines) { |
| 651 | // Add subtask information |
| 652 | subtaskInfo := fmt.Sprintf("\n\n## Subtasks Created\n\nThis task has been broken down into %d subtasks:\n\n", len(analysis.Subtasks)) |
| 653 | for i, subtask := range analysis.Subtasks { |
| 654 | subtaskID := fmt.Sprintf("%s-subtask-%d", analysis.ParentTaskID, i+1) |
| 655 | subtaskInfo += fmt.Sprintf("- **%s**: %s (assigned to %s)\n", subtaskID, subtask.Title, subtask.AssignedTo) |
| 656 | } |
| 657 | subtaskInfo += fmt.Sprintf("\n**Total Estimated Hours:** %d\n", analysis.EstimatedTotalHours) |
| 658 | subtaskInfo += fmt.Sprintf("**Completed:** %s - Task broken down into actionable subtasks\n", now) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 659 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 660 | // Insert subtask info before any existing body content |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 661 | updatedContent := strings.Join(updatedLines[:], "\n") + subtaskInfo |
| 662 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 663 | // Write the updated content back to the file |
| 664 | if err := os.WriteFile(taskFilePath, []byte(updatedContent), 0644); err != nil { |
| 665 | return fmt.Errorf("failed to write updated parent task file: %w", err) |
| 666 | } |
| 667 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 668 | |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 669 | s.logger.Info("Updated parent task to completed status", slog.String("task_id", analysis.ParentTaskID)) |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 670 | return nil |
| 671 | } |
| 672 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 673 | // generateSubtaskPRContent creates markdown content for the subtask proposal PR |
| 674 | func (s *SubtaskService) generateSubtaskPRContent(analysis *tm.SubtaskAnalysis) string { |
| 675 | var content strings.Builder |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 676 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 677 | content.WriteString(fmt.Sprintf("# Subtasks Created for Task %s\n\n", analysis.ParentTaskID)) |
| 678 | content.WriteString(fmt.Sprintf("This PR creates **%d individual task files** in `/operations/tasks/` ready for agent assignment.\n\n", len(analysis.Subtasks))) |
| 679 | content.WriteString(fmt.Sprintf("✅ **Parent task `%s` has been marked as completed** - the complex task has been successfully broken down into actionable subtasks.\n\n", analysis.ParentTaskID)) |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 680 | content.WriteString(fmt.Sprintf("## Analysis Summary\n%s\n\n", analysis.AnalysisSummary)) |
| 681 | content.WriteString(fmt.Sprintf("## Recommended Approach\n%s\n\n", analysis.RecommendedApproach)) |
| 682 | content.WriteString(fmt.Sprintf("**Estimated Total Hours:** %d\n\n", analysis.EstimatedTotalHours)) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 683 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 684 | // List the created task files |
| 685 | content.WriteString("## Created Task Files\n\n") |
| 686 | for i, subtask := range analysis.Subtasks { |
| 687 | taskID := fmt.Sprintf("%s-subtask-%d", analysis.ParentTaskID, i+1) |
| 688 | content.WriteString(fmt.Sprintf("### %d. `%s.md`\n", i+1, taskID)) |
| 689 | content.WriteString(fmt.Sprintf("- **Title:** %s\n", subtask.Title)) |
| 690 | content.WriteString(fmt.Sprintf("- **Assigned to:** %s\n", subtask.AssignedTo)) |
| 691 | content.WriteString(fmt.Sprintf("- **Priority:** %s\n", subtask.Priority)) |
| 692 | content.WriteString(fmt.Sprintf("- **Estimated Hours:** %d\n", subtask.EstimatedHours)) |
| 693 | content.WriteString(fmt.Sprintf("- **Description:** %s\n\n", subtask.Description)) |
| 694 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 695 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 696 | if analysis.RiskAssessment != "" { |
| 697 | content.WriteString(fmt.Sprintf("## Risk Assessment\n%s\n\n", analysis.RiskAssessment)) |
| 698 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 699 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 700 | content.WriteString("## Proposed Subtasks\n\n") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 701 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 702 | for i, subtask := range analysis.Subtasks { |
| 703 | content.WriteString(fmt.Sprintf("### %d. %s\n", i+1, subtask.Title)) |
| 704 | content.WriteString(fmt.Sprintf("- **Assigned to:** %s\n", subtask.AssignedTo)) |
| 705 | content.WriteString(fmt.Sprintf("- **Priority:** %s\n", subtask.Priority)) |
| 706 | content.WriteString(fmt.Sprintf("- **Estimated Hours:** %d\n", subtask.EstimatedHours)) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 707 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 708 | if len(subtask.Dependencies) > 0 { |
| 709 | deps := strings.Join(subtask.Dependencies, ", ") |
| 710 | content.WriteString(fmt.Sprintf("- **Dependencies:** %s\n", deps)) |
| 711 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 712 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 713 | content.WriteString(fmt.Sprintf("- **Description:** %s\n\n", subtask.Description)) |
| 714 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 715 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 716 | content.WriteString("---\n") |
| 717 | content.WriteString("*Generated by Staff AI Agent System*\n\n") |
| 718 | content.WriteString("**Instructions:**\n") |
| 719 | content.WriteString("- Review the proposed subtasks\n") |
| 720 | content.WriteString("- Approve or request changes\n") |
| 721 | content.WriteString("- When merged, the subtasks will be automatically created and assigned\n") |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 722 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 723 | return content.String() |
| 724 | } |
| 725 | |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 726 | // createSubtaskBranch creates a Git branch with subtask proposal content |
| 727 | func (s *SubtaskService) createSubtaskBranch(ctx context.Context, analysis *tm.SubtaskAnalysis, branchName string) error { |
| 728 | if s.cloneManager == nil { |
| 729 | return fmt.Errorf("clone manager not configured") |
| 730 | } |
| 731 | |
| 732 | // Get a temporary clone for creating the subtask branch |
| 733 | clonePath, err := s.cloneManager.GetAgentClonePath("subtask-service") |
| 734 | if err != nil { |
| 735 | return fmt.Errorf("failed to get clone path: %w", err) |
| 736 | } |
| 737 | |
| 738 | // All Git operations use the clone directory |
| 739 | gitCmd := func(args ...string) *exec.Cmd { |
| 740 | return exec.CommandContext(ctx, "git", append([]string{"-C", clonePath}, args...)...) |
| 741 | } |
| 742 | |
| 743 | // Ensure we're on main branch before creating new branch |
| 744 | cmd := gitCmd("checkout", "main") |
| 745 | if err := cmd.Run(); err != nil { |
| 746 | // Try master branch if main doesn't exist |
| 747 | cmd = gitCmd("checkout", "master") |
| 748 | if err := cmd.Run(); err != nil { |
| 749 | return fmt.Errorf("failed to checkout main/master branch: %w", err) |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | // Pull latest changes |
| 754 | cmd = gitCmd("pull", "origin") |
| 755 | if err := cmd.Run(); err != nil { |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 756 | s.logger.Warn("Failed to pull latest changes", slog.String("error", err.Error())) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 757 | } |
| 758 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 759 | // Delete branch if it exists (cleanup from previous attempts) |
| 760 | cmd = gitCmd("branch", "-D", branchName) |
| 761 | _ = cmd.Run() // Ignore error if branch doesn't exist |
| 762 | |
| 763 | // Also delete remote tracking branch if it exists |
| 764 | cmd = gitCmd("push", "origin", "--delete", branchName) |
| 765 | _ = cmd.Run() // Ignore error if branch doesn't exist |
| 766 | |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 767 | // Create and checkout new branch |
| 768 | cmd = gitCmd("checkout", "-b", branchName) |
| 769 | if err := cmd.Run(); err != nil { |
| 770 | return fmt.Errorf("failed to create branch: %w", err) |
| 771 | } |
| 772 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 773 | // Create individual task files for each subtask |
| 774 | tasksDir := filepath.Join(clonePath, "operations", "tasks") |
| 775 | if err := os.MkdirAll(tasksDir, 0755); err != nil { |
| 776 | return fmt.Errorf("failed to create tasks directory: %w", err) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 777 | } |
| 778 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 779 | var stagedFiles []string |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 780 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 781 | // Update parent task to mark as completed |
| 782 | parentTaskFile := filepath.Join(tasksDir, fmt.Sprintf("%s.md", analysis.ParentTaskID)) |
| 783 | if err := s.updateParentTaskAsCompleted(parentTaskFile, analysis); err != nil { |
| 784 | return fmt.Errorf("failed to update parent task: %w", err) |
| 785 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 786 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 787 | // Track parent task file for staging |
| 788 | parentRelativeFile := filepath.Join("operations", "tasks", fmt.Sprintf("%s.md", analysis.ParentTaskID)) |
| 789 | stagedFiles = append(stagedFiles, parentRelativeFile) |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 790 | s.logger.Info("Updated parent task file", slog.String("file", parentRelativeFile)) |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 791 | |
| 792 | // Create a file for each subtask |
| 793 | for i, subtask := range analysis.Subtasks { |
| 794 | taskID := fmt.Sprintf("%s-subtask-%d", analysis.ParentTaskID, i+1) |
| 795 | taskFile := filepath.Join(tasksDir, fmt.Sprintf("%s.md", taskID)) |
| 796 | taskContent := s.generateSubtaskFile(subtask, taskID, analysis.ParentTaskID) |
| 797 | |
| 798 | if err := os.WriteFile(taskFile, []byte(taskContent), 0644); err != nil { |
| 799 | return fmt.Errorf("failed to write subtask file %s: %w", taskID, err) |
| 800 | } |
| 801 | |
| 802 | // Track file for staging |
| 803 | relativeFile := filepath.Join("operations", "tasks", fmt.Sprintf("%s.md", taskID)) |
| 804 | stagedFiles = append(stagedFiles, relativeFile) |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 805 | s.logger.Info("Created subtask file", slog.String("file", relativeFile)) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 806 | } |
| 807 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 808 | // Stage all subtask files |
| 809 | for _, file := range stagedFiles { |
| 810 | cmd = gitCmd("add", file) |
| 811 | if err := cmd.Run(); err != nil { |
| 812 | return fmt.Errorf("failed to stage file %s: %w", file, err) |
| 813 | } |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 814 | } |
| 815 | |
| 816 | // Commit changes |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 817 | commitMsg := fmt.Sprintf("Create %d subtasks for task %s and mark parent as completed\n\nGenerated by Staff AI Agent System\n\nFiles modified:\n- %s.md (marked as completed)\n\nCreated individual task files:\n", |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 818 | len(analysis.Subtasks), analysis.ParentTaskID, analysis.ParentTaskID) |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 819 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 820 | // Add list of created files to commit message |
| 821 | for i := range analysis.Subtasks { |
| 822 | taskID := fmt.Sprintf("%s-subtask-%d", analysis.ParentTaskID, i+1) |
| 823 | commitMsg += fmt.Sprintf("- %s.md\n", taskID) |
| 824 | } |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 825 | |
| iomodo | 43ec6ae | 2025-07-28 17:40:12 +0400 | [diff] [blame] | 826 | if len(analysis.AgentCreations) > 0 { |
| 827 | commitMsg += fmt.Sprintf("\nProposed %d new agents for specialized skills", len(analysis.AgentCreations)) |
| 828 | } |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 829 | cmd = gitCmd("commit", "-m", commitMsg) |
| 830 | if err := cmd.Run(); err != nil { |
| 831 | return fmt.Errorf("failed to commit: %w", err) |
| 832 | } |
| 833 | |
| 834 | // Push branch |
| 835 | cmd = gitCmd("push", "-u", "origin", branchName) |
| 836 | if err := cmd.Run(); err != nil { |
| 837 | return fmt.Errorf("failed to push branch: %w", err) |
| 838 | } |
| 839 | |
| iomodo | 62da94a | 2025-07-28 19:01:55 +0400 | [diff] [blame] | 840 | s.logger.Info("Created subtask proposal branch", slog.String("branch", branchName)) |
| iomodo | 443b20a | 2025-07-28 15:24:05 +0400 | [diff] [blame] | 841 | return nil |
| 842 | } |
| 843 | |
| iomodo | d9ff8da | 2025-07-28 11:42:22 +0400 | [diff] [blame] | 844 | // Close cleans up the service |
| 845 | func (s *SubtaskService) Close() error { |
| 846 | if s.llmProvider != nil { |
| 847 | return s.llmProvider.Close() |
| 848 | } |
| 849 | return nil |
| iomodo | af99879 | 2025-07-28 19:05:18 +0400 | [diff] [blame] | 850 | } |