diff options
Diffstat (limited to 'internal/executor')
| -rw-r--r-- | internal/executor/container.go | 73 | ||||
| -rw-r--r-- | internal/executor/container_test.go | 41 | ||||
| -rw-r--r-- | internal/executor/executor.go | 353 | ||||
| -rw-r--r-- | internal/executor/executor_test.go | 548 |
4 files changed, 54 insertions, 961 deletions
diff --git a/internal/executor/container.go b/internal/executor/container.go index a00448c..6179ffc 100644 --- a/internal/executor/container.go +++ b/internal/executor/container.go @@ -29,7 +29,7 @@ type ContainerRunner struct { GeminiBinary string // optional path to gemini binary in container ClaudeConfigDir string // host path to ~/.claude; mounted into container for auth credentials CredentialSyncCmd string // optional path to sync-credentials script for auth-error auto-recovery - Store Store // optional; used to look up stories and projects for story-aware cloning + Store Store // optional; used to look up projects for local-path cloning // Registry mints the per-task MCP token; when set, the agent gets an // mcp-config pointing at the host agent MCP server. Registry *Registry @@ -62,16 +62,16 @@ func (r *ContainerRunner) ExecLogDir(execID string) string { return filepath.Join(r.LogDir, execID) } -// ensureStoryBranch checks whether branchName exists in remoteURL and creates -// it from main if not. Uses localPath as a reference clone for speed if set. -func (r *ContainerRunner) ensureStoryBranch(ctx context.Context, remoteURL, branchName, localPath string) error { +// ensureBranch checks whether branchName exists in remoteURL and creates +// it from main if it does not exist. Uses localPath as a reference clone for speed if set. +func (r *ContainerRunner) ensureBranch(ctx context.Context, remoteURL, branchName, localPath string) error { // Check if branch already exists. out, err := r.command(ctx, "git", "ls-remote", "--heads", remoteURL, branchName).CombinedOutput() if err == nil && len(strings.TrimSpace(string(out))) > 0 { return nil // already exists } - r.Logger.Info("story branch missing, creating from main", "branch", branchName, "remote", remoteURL) + r.Logger.Info("branch missing, creating from main", "branch", branchName, "remote", remoteURL) // Clone into a temp dir so we can create the branch. tmp, err := os.MkdirTemp("", "claudomator-branchsetup-*") @@ -142,38 +142,21 @@ func (r *ContainerRunner) Run(ctx context.Context, t *task.Task, e *storage.Exec } }() - // Resolve story branch and project local path if this is a story task. - var storyBranch string - var storyLocalPath string - if t.StoryID != "" && r.Store != nil { - if story, err := r.Store.GetStory(t.StoryID); err == nil && story != nil { - storyBranch = story.BranchName - if story.ProjectID != "" { - if proj, err := r.Store.GetProject(story.ProjectID); err == nil && proj != nil { - storyLocalPath = proj.LocalPath - } - } - } - } - // For non-story tasks (e.g. CI webhook tasks), also resolve local path from the task's - // project field. This lets the runner clone from the local mirror instead of an HTTPS - // remote that may require credentials not available on the host. - if storyLocalPath == "" && t.Project != "" && r.Store != nil { + // Resolve branch and local path for cloning. + branch := t.BranchName + var localPath string + // Resolve local path from project field to avoid HTTPS auth requirements. + if t.Project != "" && r.Store != nil { if proj, err := r.Store.GetProject(t.Project); err == nil && proj != nil && proj.LocalPath != "" { - storyLocalPath = proj.LocalPath + localPath = proj.LocalPath } } - // Fall back to task-level BranchName (e.g. set explicitly by executor or tests). - if storyBranch == "" { - storyBranch = t.BranchName - } - // 2. Ensure story branch exists in the remote before cloning. - // If the branch is missing (e.g. story approved before fix, or branch push failed), - // create it from main using the project local path as a reference repo. - if storyBranch != "" && !isResume { - if err := r.ensureStoryBranch(ctx, repoURL, storyBranch, storyLocalPath); err != nil { - r.Logger.Warn("ensureStoryBranch failed (will attempt checkout anyway)", "branch", storyBranch, "error", err) + // 2. Ensure branch exists in the remote before cloning. + // If the branch is missing, create it from main using the project local path as a reference repo. + if branch != "" && !isResume { + if err := r.ensureBranch(ctx, repoURL, branch, localPath); err != nil { + r.Logger.Warn("ensureBranch failed (will attempt checkout anyway)", "branch", branch, "error", err) } } @@ -184,21 +167,19 @@ func (r *ContainerRunner) Run(ctx context.Context, t *task.Task, e *storage.Exec return fmt.Errorf("removing workspace before clone: %w", err) } // Prefer the local path as the clone source to avoid HTTPS auth requirements. - // For story tasks the storyLocalPath is also available as a speed reference, - // but we clone from the local path directly since it is already authoritative. cloneSrc := repoURL - if storyLocalPath != "" { - cloneSrc = storyLocalPath + if localPath != "" { + cloneSrc = localPath } r.Logger.Info("cloning repository", "src", cloneSrc, "workspace", workspace) cloneArgs := []string{"clone", cloneSrc, workspace} if out, err := r.command(ctx, "git", cloneArgs...).CombinedOutput(); err != nil { return fmt.Errorf("git clone failed: %w\n%s", err, string(out)) } - if storyBranch != "" { - r.Logger.Info("checking out story branch", "branch", storyBranch) - if out, err := r.command(ctx, "git", "-C", workspace, "checkout", storyBranch).CombinedOutput(); err != nil { - return fmt.Errorf("git checkout story branch %q failed: %w\n%s", storyBranch, err, string(out)) + if branch != "" { + r.Logger.Info("checking out branch", "branch", branch) + if out, err := r.command(ctx, "git", "-C", workspace, "checkout", branch).CombinedOutput(); err != nil { + return fmt.Errorf("git checkout branch %q failed: %w\n%s", branch, err, string(out)) } } if err = os.Chmod(workspace, 0755); err != nil { @@ -241,7 +222,7 @@ func (r *ContainerRunner) Run(ctx context.Context, t *task.Task, e *storage.Exec } // Run container (with auth retry on failure). - runErr := r.runContainer(ctx, t, e, workspace, agentHome, isResume, storyBranch, ch) + runErr := r.runContainer(ctx, t, e, workspace, agentHome, isResume, branch, ch) if runErr != nil && isAuthError(runErr) && r.CredentialSyncCmd != "" { r.Logger.Warn("auth failure detected, syncing credentials and retrying once", "taskID", t.ID) syncOut, syncErr := r.command(ctx, r.CredentialSyncCmd).CombinedOutput() @@ -255,7 +236,7 @@ func (r *ContainerRunner) Run(ctx context.Context, t *task.Task, e *storage.Exec if srcData, readErr := os.ReadFile(filepath.Join(r.ClaudeConfigDir, ".claude.json")); readErr == nil { _ = os.WriteFile(filepath.Join(agentHome, ".claude.json"), srcData, 0644) } - runErr = r.runContainer(ctx, t, e, workspace, agentHome, isResume, storyBranch, ch) + runErr = r.runContainer(ctx, t, e, workspace, agentHome, isResume, branch, ch) } if runErr == nil { @@ -271,7 +252,7 @@ func (r *ContainerRunner) Run(ctx context.Context, t *task.Task, e *storage.Exec // runContainer runs the docker container for the given task and handles log setup, // environment files, instructions, and post-execution git operations. -func (r *ContainerRunner) runContainer(ctx context.Context, t *task.Task, e *storage.Execution, workspace, agentHome string, isResume bool, storyBranch string, ch AgentChannel) error { +func (r *ContainerRunner) runContainer(ctx context.Context, t *task.Task, e *storage.Execution, workspace, agentHome string, isResume bool, branch string, ch AgentChannel) error { repoURL := t.RepositoryURL image := t.Agent.ContainerImage @@ -426,8 +407,8 @@ func (r *ContainerRunner) runContainer(ctx context.Context, t *task.Task, e *sto if hasCommits { pushRef := "HEAD" - if storyBranch != "" { - pushRef = storyBranch + if branch != "" { + pushRef = branch } r.Logger.Info("pushing changes back to remote", "url", repoURL, "ref", pushRef) if out, err := r.command(ctx, "git", "-C", workspace, "push", "origin", pushRef).CombinedOutput(); err != nil { diff --git a/internal/executor/container_test.go b/internal/executor/container_test.go index 8c00a0f..b06d153 100644 --- a/internal/executor/container_test.go +++ b/internal/executor/container_test.go @@ -620,9 +620,9 @@ func TestContainerRunner_ClonesStoryBranch(t *testing.T) { runner.Run(context.Background(), tk, e, newStoreChannel(nil, tk.ID)) os.RemoveAll(e.SandboxDir) - // Assert git checkout was called with the story branch name. + // Assert git checkout was called with the branch name. if len(checkoutArgs) == 0 { - t.Fatal("expected git checkout to be called for story branch, but it was not") + t.Fatal("expected git checkout to be called for branch, but it was not") } found := false for _, a := range checkoutArgs { @@ -741,27 +741,30 @@ func TestContainerRunner_ClonesFromLocalPathForCITask(t *testing.T) { } } -func TestEnsureStoryBranch_CreatesMissingBranch(t *testing.T) { +func TestEnsureBranch_CreatesMissingBranch(t *testing.T) { // Set up a bare repo and a local clone to test branch creation. dir := t.TempDir() bare := filepath.Join(dir, "bare.git") local := filepath.Join(dir, "local") - // Create bare repo with an initial commit. - if out, err := exec.Command("git", "init", "--bare", bare).CombinedOutput(); err != nil { - t.Fatalf("git init bare: %v\n%s", err, out) + // Create bare repo with an initial commit on main. + if out, err := exec.Command("git", "init", "--bare", "--initial-branch=main", bare).CombinedOutput(); err != nil { + // Fallback for older git: init bare then update HEAD manually. + if out2, err2 := exec.Command("git", "init", "--bare", bare).CombinedOutput(); err2 != nil { + t.Fatalf("git init bare: %v\n%s", err2, out2) + } + if out2, err2 := exec.Command("git", "-C", bare, "symbolic-ref", "HEAD", "refs/heads/main").CombinedOutput(); err2 != nil { + t.Fatalf("set HEAD to main: %v\n%s\n%s", err, out, out2) + } } if out, err := exec.Command("git", "clone", bare, local).CombinedOutput(); err != nil { t.Fatalf("git clone: %v\n%s", err, out) } - if out, err := exec.Command("git", "-C", local, "commit", "--allow-empty", "-m", "init").CombinedOutput(); err != nil { + if out, err := exec.Command("git", "-C", local, "-c", "user.email=test@test.com", "-c", "user.name=Test", "commit", "--allow-empty", "-m", "init").CombinedOutput(); err != nil { t.Fatalf("git commit: %v\n%s", err, out) } if out, err := exec.Command("git", "-C", local, "push", "origin", "main").CombinedOutput(); err != nil { - // try master - if out2, err2 := exec.Command("git", "-C", local, "push", "origin", "HEAD:main").CombinedOutput(); err2 != nil { - t.Fatalf("git push main: %v\n%s\n%s", err, out, out2) - } + t.Fatalf("git push main: %v\n%s", err, out) } runner := &ContainerRunner{Logger: slog.Default()} @@ -771,21 +774,21 @@ func TestEnsureStoryBranch_CreatesMissingBranch(t *testing.T) { // Branch should not exist yet. out, _ := exec.Command("git", "ls-remote", "--heads", bare, branch).CombinedOutput() if len(strings.TrimSpace(string(out))) > 0 { - t.Fatal("branch should not exist before ensureStoryBranch") + t.Fatal("branch should not exist before ensureBranch") } - if err := runner.ensureStoryBranch(context.Background(), bare, branch, ""); err != nil { - t.Fatalf("ensureStoryBranch: %v", err) + if err := runner.ensureBranch(context.Background(), bare, branch, ""); err != nil { + t.Fatalf("ensureBranch: %v", err) } // Branch should now exist in the bare repo. out, err := exec.Command("git", "ls-remote", "--heads", bare, branch).CombinedOutput() if err != nil || len(strings.TrimSpace(string(out))) == 0 { - t.Errorf("branch %q not found in bare repo after ensureStoryBranch: %s", branch, out) + t.Errorf("branch %q not found in bare repo after ensureBranch: %s", branch, out) } } -func TestEnsureStoryBranch_IdempotentIfExists(t *testing.T) { +func TestEnsureBranch_IdempotentIfExists(t *testing.T) { dir := t.TempDir() bare := filepath.Join(dir, "bare.git") local := filepath.Join(dir, "local") @@ -796,7 +799,7 @@ func TestEnsureStoryBranch_IdempotentIfExists(t *testing.T) { if out, err := exec.Command("git", "clone", bare, local).CombinedOutput(); err != nil { t.Fatalf("git clone: %v\n%s", err, out) } - if out, err := exec.Command("git", "-C", local, "commit", "--allow-empty", "-m", "init").CombinedOutput(); err != nil { + if out, err := exec.Command("git", "-C", local, "-c", "user.email=test@test.com", "-c", "user.name=Test", "commit", "--allow-empty", "-m", "init").CombinedOutput(); err != nil { t.Fatalf("git commit: %v\n%s", err, out) } if _, err := exec.Command("git", "-C", local, "push", "origin", "HEAD:main").CombinedOutput(); err != nil { @@ -815,8 +818,8 @@ func TestEnsureStoryBranch_IdempotentIfExists(t *testing.T) { runner := &ContainerRunner{Logger: slog.Default()} // Should be a no-op, not an error. - if err := runner.ensureStoryBranch(context.Background(), bare, branch, ""); err != nil { - t.Fatalf("ensureStoryBranch on existing branch: %v", err) + if err := runner.ensureBranch(context.Background(), bare, branch, ""); err != nil { + t.Fatalf("ensureBranch on existing branch: %v", err) } } diff --git a/internal/executor/executor.go b/internal/executor/executor.go index 507c65b..51cf5d9 100644 --- a/internal/executor/executor.go +++ b/internal/executor/executor.go @@ -2,11 +2,9 @@ package executor import ( "context" - "encoding/json" "errors" "fmt" "log/slog" - "os/exec" "path/filepath" "strings" "sync" @@ -38,13 +36,8 @@ type Store interface { UpdateExecutionChangestats(execID string, stats *task.Changestats) error RecordAgentEvent(e storage.AgentEvent) error GetProject(id string) (*task.Project, error) - GetStory(id string) (*task.Story, error) - ListTasksByStory(storyID string) ([]*task.Task, error) - UpdateStoryStatus(id string, status task.StoryState) error CreateTask(t *task.Task) error CreateEvent(e *event.Event) error - UpdateTaskCheckerReport(id, report string) error - GetCheckerTask(checkedTaskID string) (*task.Task, error) } // LogPather is an optional interface runners can implement to provide the log @@ -400,12 +393,6 @@ func (p *Pool) executeResume(ctx context.Context, t *task.Task, exec *storage.Ex t.RepositoryURL = proj.RemoteURL } } - // Populate BranchName from Story if missing (ADR-007). - if t.BranchName == "" && t.StoryID != "" { - if story, err := p.store.GetStory(t.StoryID); err == nil && story.BranchName != "" { - t.BranchName = story.BranchName - } - } sc := newStoreChannel(p.store, t.ID) err = runner.Run(ctx, t, exec, sc) @@ -496,47 +483,11 @@ func (p *Pool) handleRunResult(ctx context.Context, t *task.Task, exec *storage. p.consecutiveFailures[agentType]++ p.mu.Unlock() } - // If this is a checker task, attach the failure report for any terminal - // failure state (FAILED, TIMED_OUT, CANCELLED, BUDGET_EXCEEDED). - if t.CheckerForTaskID != "" && exec.ErrorMsg != "" { - if reportErr := p.store.UpdateTaskCheckerReport(t.CheckerForTaskID, exec.ErrorMsg); reportErr != nil { - p.logger.Error("handleRunResult: failed to set checker report", "taskID", t.CheckerForTaskID, "error", reportErr) - } - } - if t.StoryID != "" && exec.Status == "FAILED" { - storyID := t.StoryID - errMsg := exec.ErrorMsg - go func() { - story, getErr := p.store.GetStory(storyID) - if getErr != nil { - return - } - if story.Status == task.StoryValidating { - p.checkValidationResult(ctx, storyID, task.StateFailed, errMsg) - } - }() - } } else { p.mu.Lock() p.consecutiveFailures[agentType] = 0 p.mu.Unlock() - if t.CheckerForTaskID != "" { - // Checker task succeeded — auto-accept the checked task. - exec.Status = "COMPLETED" - if err := p.store.UpdateTaskState(t.ID, task.StateCompleted); err != nil { - p.logger.Error("handleRunResult: failed to complete checker task", "taskID", t.ID, "error", err) - } - checkedTask, getErr := p.store.GetTask(t.CheckerForTaskID) - if getErr == nil { - if acceptErr := p.store.UpdateTaskState(t.CheckerForTaskID, task.StateCompleted); acceptErr != nil { - p.logger.Error("handleRunResult: failed to auto-accept checked task", "taskID", t.CheckerForTaskID, "error", acceptErr) - } else if checkedTask.StoryID != "" { - go p.checkStoryCompletion(context.Background(), checkedTask.StoryID) - } - } else { - p.logger.Error("handleRunResult: failed to get checked task", "taskID", t.CheckerForTaskID, "error", getErr) - } - } else if t.ParentTaskID == "" { + if t.ParentTaskID == "" { subtasks, subErr := p.store.ListSubtasks(t.ID) if subErr != nil { p.logger.Error("failed to list subtasks", "taskID", t.ID, "error", subErr) @@ -551,9 +502,6 @@ func (p *Pool) handleRunResult(ctx context.Context, t *task.Task, exec *storage. if err := p.store.UpdateTaskState(t.ID, task.StateReady); err != nil { p.logger.Error("failed to update task state", "taskID", t.ID, "state", task.StateReady, "error", err) } - if agentType != "local" { - go p.spawnCheckerTask(context.Background(), t, exec) - } } } else { exec.Status = "COMPLETED" @@ -562,21 +510,6 @@ func (p *Pool) handleRunResult(ctx context.Context, t *task.Task, exec *storage. } p.maybeUnblockParent(t.ParentTaskID) } - if t.StoryID != "" { - storyID := t.StoryID - go func() { - story, getErr := p.store.GetStory(storyID) - if getErr != nil { - p.logger.Error("handleRunResult: failed to get story", "storyID", storyID, "error", getErr) - return - } - if story.Status == task.StoryValidating { - p.checkValidationResult(ctx, storyID, task.StateCompleted, "") - } else { - p.checkStoryCompletion(ctx, storyID) - } - }() - } } summary := exec.Summary @@ -591,13 +524,6 @@ func (p *Pool) handleRunResult(ctx context.Context, t *task.Task, exec *storage. p.logger.Error("failed to update task summary", "taskID", t.ID, "error", summaryErr) } } - terminalFailure := exec.Status == "FAILED" || exec.Status == "TIMED_OUT" || exec.Status == "CANCELLED" || exec.Status == "BUDGET_EXCEEDED" - if t.CheckerForTaskID != "" && terminalFailure && summary != "" { - // Overwrite the initial error-message report with the richer summary. - if reportErr := p.store.UpdateTaskCheckerReport(t.CheckerForTaskID, summary); reportErr != nil { - p.logger.Error("handleRunResult: failed to update checker report with summary", "taskID", t.CheckerForTaskID, "error", reportErr) - } - } if exec.StdoutPath != "" { if cs := task.ParseChangestatFromFile(exec.StdoutPath); cs != nil { exec.Changestats = cs @@ -612,266 +538,6 @@ func (p *Pool) handleRunResult(ctx context.Context, t *task.Task, exec *storage. p.resultCh <- &Result{TaskID: t.ID, Execution: exec, Err: err} } -// checkStoryCompletion checks whether all top-level tasks in a story have reached -// a terminal success state and transitions the story to SHIPPABLE if so. -// Subtasks are intentionally excluded — a parent task reaching READY/COMPLETED -// already accounts for its subtasks. -// CheckStoryCompletion is the exported entry point for story completion checks -// called from outside the package (e.g. the API accept handler). -func (p *Pool) CheckStoryCompletion(ctx context.Context, storyID string) { - p.checkStoryCompletion(ctx, storyID) -} - -func (p *Pool) checkStoryCompletion(ctx context.Context, storyID string) { - story, err := p.store.GetStory(storyID) - if err != nil { - p.logger.Error("checkStoryCompletion: failed to get story", "storyID", storyID, "error", err) - return - } - if story.Status != task.StoryInProgress { - return // already SHIPPABLE or beyond — nothing to do - } - tasks, err := p.store.ListTasksByStory(storyID) - if err != nil { - p.logger.Error("checkStoryCompletion: failed to list tasks", "storyID", storyID, "error", err) - return - } - if len(tasks) == 0 { - return - } - topLevelCount := 0 - for _, t := range tasks { - if t.ParentTaskID != "" { - continue // subtasks are covered by their parent - } - topLevelCount++ - if t.State != task.StateCompleted { - return // not all top-level tasks done; READY alone is not sufficient (checker may be pending) - } - } - if topLevelCount == 0 { - return // no top-level tasks — don't auto-complete - } - if err := p.store.UpdateStoryStatus(storyID, task.StoryShippable); err != nil { - p.logger.Error("checkStoryCompletion: failed to update story status", "storyID", storyID, "error", err) - return - } - p.logger.Info("story transitioned to SHIPPABLE", "storyID", storyID) - // Deploy is now triggered explicitly by the human via POST /api/stories/{id}/ship. -} - -// ShipStory merges the story branch and runs the deploy script. -// Returns an error if the story is not in SHIPPABLE state. -func (p *Pool) ShipStory(ctx context.Context, storyID string) error { - story, err := p.store.GetStory(storyID) - if err != nil { - return fmt.Errorf("story not found: %w", err) - } - if story.Status != task.StoryShippable { - return fmt.Errorf("story is not SHIPPABLE (current status: %s)", story.Status) - } - go p.triggerStoryDeploy(context.Background(), storyID) - return nil -} - -// spawnCheckerTask creates and submits a checker task for the given completed task. -// Guards: not called for subtasks, checker tasks, tasks without a repository URL, -// or tasks that already have a checker. -func (p *Pool) spawnCheckerTask(ctx context.Context, checked *task.Task, exec *storage.Execution) { - // Never spawn a checker for subtasks, checker tasks, or tasks without a repository. - if checked.ParentTaskID != "" || checked.CheckerForTaskID != "" || checked.RepositoryURL == "" { - return - } - // Idempotent: don't create a second checker if one already exists. - existing, err := p.store.GetCheckerTask(checked.ID) - if err != nil { - p.logger.Error("spawnCheckerTask: GetCheckerTask failed", "taskID", checked.ID, "error", err) - return - } - if existing != nil { - return - } - - criteria := checked.AcceptanceCriteria - if criteria == "" { - criteria = checked.Agent.Instructions - } - - // Embed the execution log so the checker can verify output without needing - // Docker, API access, or repository cloning. - logSnippet := "" - if exec != nil && exec.StdoutPath != "" { - logSnippet = "\n\nExecution log (last 200 lines):\n<execution_log>\n" + - tailFile(exec.StdoutPath, 200) + - "\n</execution_log>" - } - - instructions := fmt.Sprintf(`You are validating a completed task. Do not make any changes to the code or repository. - -Task: %s -Instructions given to the implementor: -%s - -Acceptance criteria: -%s%s - -Steps: -1. Review the execution log above to determine what the agent did. -2. If the task involved code changes, use Read/Grep/Glob to inspect the repository at %s. -3. Verify each acceptance criterion is met. Run tests or make HTTP requests as needed. -4. If all criteria are satisfied, exit normally (success). -5. If any criterion is not met, use the Bash tool to exit with a non-zero code: - bash -c "exit 1" - Before exiting, write a brief summary of what failed.`, - checked.Name, checked.Agent.Instructions, criteria, logSnippet, checked.RepositoryURL) - - now := time.Now().UTC() - checker := &task.Task{ - ID: uuid.New().String(), - Name: "Check: " + checked.Name, - CheckerForTaskID: checked.ID, - RepositoryURL: checked.RepositoryURL, - Agent: task.AgentConfig{ - Type: "claude", - Instructions: instructions, - MaxBudgetUSD: 0.50, - AllowedTools: []string{"Bash", "Read", "Glob", "Grep"}, - }, - Timeout: task.Duration{Duration: 10 * time.Minute}, - Priority: task.PriorityNormal, - Tags: []string{}, - DependsOn: []string{}, - Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"}, - State: task.StatePending, - CreatedAt: now, - UpdatedAt: now, - } - - if err := p.store.CreateTask(checker); err != nil { - p.logger.Error("spawnCheckerTask: CreateTask failed", "error", err) - return - } - checker.State = task.StateQueued - if err := p.store.UpdateTaskState(checker.ID, task.StateQueued); err != nil { - p.logger.Error("spawnCheckerTask: UpdateTaskState failed", "error", err) - return - } - if err := p.Submit(ctx, checker); err != nil { - p.logger.Error("spawnCheckerTask: Submit failed", "error", err) - } -} - -// triggerStoryDeploy runs the project deploy script for a SHIPPABLE story -// and advances it to DEPLOYED on success. -func (p *Pool) triggerStoryDeploy(ctx context.Context, storyID string) { - story, err := p.store.GetStory(storyID) - if err != nil { - p.logger.Error("triggerStoryDeploy: failed to get story", "storyID", storyID, "error", err) - return - } - if story.ProjectID == "" { - return - } - proj, err := p.store.GetProject(story.ProjectID) - if err != nil { - p.logger.Error("triggerStoryDeploy: failed to get project", "storyID", storyID, "projectID", story.ProjectID, "error", err) - return - } - if proj.DeployScript == "" { - return - } - // Merge story branch to main before deploying (ADR-007). - if story.BranchName != "" && proj.LocalPath != "" { - mergeSteps := [][]string{ - {"git", "-C", proj.LocalPath, "fetch", "origin"}, - {"git", "-C", proj.LocalPath, "checkout", "main"}, - {"git", "-C", proj.LocalPath, "merge", "--no-ff", story.BranchName, "-m", "Merge " + story.BranchName}, - {"git", "-C", proj.LocalPath, "push", "origin", "main"}, - } - for _, args := range mergeSteps { - if mergeOut, mergeErr := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput(); mergeErr != nil { - p.logger.Error("triggerStoryDeploy: merge failed", "cmd", args, "output", string(mergeOut), "error", mergeErr) - return - } - } - p.logger.Info("story branch merged to main", "storyID", storyID, "branch", story.BranchName) - } - out, err := exec.CommandContext(ctx, proj.DeployScript).CombinedOutput() - if err != nil { - p.logger.Error("triggerStoryDeploy: deploy script failed", "storyID", storyID, "script", proj.DeployScript, "output", string(out), "error", err) - return - } - if err := p.store.UpdateStoryStatus(storyID, task.StoryDeployed); err != nil { - p.logger.Error("triggerStoryDeploy: failed to update story status", "storyID", storyID, "error", err) - return - } - p.logger.Info("story transitioned to DEPLOYED", "storyID", storyID) - go p.createValidationTask(ctx, storyID) -} - -// createValidationTask creates a validation subtask from the story's ValidationJSON -// and transitions the story to VALIDATING. -func (p *Pool) createValidationTask(ctx context.Context, storyID string) { - story, err := p.store.GetStory(storyID) - if err != nil { - p.logger.Error("createValidationTask: failed to get story", "storyID", storyID, "error", err) - return - } - if story.ValidationJSON == "" { - p.logger.Warn("createValidationTask: story has no ValidationJSON, skipping", "storyID", storyID) - return - } - - var spec map[string]interface{} - if err := json.Unmarshal([]byte(story.ValidationJSON), &spec); err != nil { - p.logger.Error("createValidationTask: failed to parse ValidationJSON", "storyID", storyID, "error", err) - return - } - - instructions := fmt.Sprintf("Validate the deployment for story %q.\n\nValidation spec:\n%s", story.Name, story.ValidationJSON) - - now := time.Now().UTC() - vtask := &task.Task{ - ID: uuid.New().String(), - Name: fmt.Sprintf("validation: %s", story.Name), - StoryID: storyID, - State: task.StateQueued, - Agent: task.AgentConfig{Type: "claude", Instructions: instructions}, - Tags: []string{}, - DependsOn: []string{}, - CreatedAt: now, - UpdatedAt: now, - } - - if err := p.store.CreateTask(vtask); err != nil { - p.logger.Error("createValidationTask: failed to create task", "storyID", storyID, "error", err) - return - } - if err := p.store.UpdateStoryStatus(storyID, task.StoryValidating); err != nil { - p.logger.Error("createValidationTask: failed to update story status", "storyID", storyID, "error", err) - return - } - p.logger.Info("validation task created and story transitioned to VALIDATING", "storyID", storyID, "taskID", vtask.ID) - p.Submit(ctx, vtask) //nolint:errcheck -} - -// checkValidationResult inspects a completed validation task and transitions -// the story to REVIEW_READY or NEEDS_FIX accordingly. -func (p *Pool) checkValidationResult(ctx context.Context, storyID string, taskState task.State, errorMsg string) { - if taskState == task.StateCompleted { - if err := p.store.UpdateStoryStatus(storyID, task.StoryReviewReady); err != nil { - p.logger.Error("checkValidationResult: failed to update story status", "storyID", storyID, "error", err) - return - } - p.logger.Info("story transitioned to REVIEW_READY", "storyID", storyID) - } else { - if err := p.store.UpdateStoryStatus(storyID, task.StoryNeedsFix); err != nil { - p.logger.Error("checkValidationResult: failed to update story status", "storyID", storyID, "error", err) - return - } - p.logger.Info("story transitioned to NEEDS_FIX", "storyID", storyID, "error", errorMsg) - } -} // ActiveCount returns the number of currently running tasks. func (p *Pool) ActiveCount() int { @@ -1137,12 +803,6 @@ func (p *Pool) execute(ctx context.Context, t *task.Task) { t.RepositoryURL = proj.RemoteURL } } - // Populate BranchName from Story if missing (ADR-007). - if t.BranchName == "" && t.StoryID != "" { - if story, err := p.store.GetStory(t.StoryID); err == nil && story.BranchName != "" { - t.BranchName = story.BranchName - } - } // Run the task. sc := newStoreChannel(p.store, t.ID) @@ -1220,11 +880,9 @@ func (p *Pool) RecoverStaleQueued(ctx context.Context) { // RecoverStaleBlocked promotes any BLOCKED or QUEUED parent task to READY when // all of its subtasks are already COMPLETED. This handles the case where the // server was restarted after subtasks finished but before maybeUnblockParent -// could fire, and also the case where story approval pre-created subtasks -// without ever running the parent task. +// could fire. // Call this once on server startup, after RecoverStaleRunning and RecoverStaleQueued. func (p *Pool) RecoverStaleBlocked() { - ctx := context.Background() for _, state := range []task.State{task.StateBlocked, task.StateQueued} { tasks, err := p.store.ListTasks(storage.TaskFilter{State: state}) if err != nil { @@ -1235,12 +893,7 @@ func (p *Pool) RecoverStaleBlocked() { if t.ParentTaskID != "" { continue // only promote actual parents } - before := t.State p.maybeUnblockParent(t.ID) - // If the parent was promoted, check story completion. - if after, err := p.store.GetTask(t.ID); err == nil && after.State != before && t.StoryID != "" { - p.checkStoryCompletion(ctx, t.StoryID) - } } } } @@ -1318,7 +971,7 @@ func withFailureHistory(t *task.Task, execs []*storage.Execution, err error) *ta // maybeUnblockParent transitions the parent task to READY if all of its subtasks // are in the COMPLETED state. Handles both BLOCKED parents (ran, created subtasks, -// paused) and QUEUED parents (story approval created subtasks without running parent). +// paused) and QUEUED parents (subtasks created before parent ran). func (p *Pool) maybeUnblockParent(parentID string) { parent, err := p.store.GetTask(parentID) if err != nil { diff --git a/internal/executor/executor_test.go b/internal/executor/executor_test.go index b737e22..cb6554c 100644 --- a/internal/executor/executor_test.go +++ b/internal/executor/executor_test.go @@ -5,7 +5,6 @@ import ( "fmt" "log/slog" "os" - "os/exec" "path/filepath" "strings" "sync" @@ -805,53 +804,6 @@ func TestPool_RecoverStaleBlocked_KeepsBlockedWhenSubtaskIncomplete(t *testing.T } } -func TestPool_RecoverStaleBlocked_PromotesQueuedParentWithAllSubtasksDone(t *testing.T) { - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - now := time.Now().UTC() - story := &task.Story{ - ID: "story-queued-parent", Name: "Queued Parent Story", - Status: task.StoryInProgress, CreatedAt: now, UpdatedAt: now, - } - store.CreateStory(story) - - // Parent task stuck QUEUED (approved with pre-created subtasks, never run). - parent := makeTask("queued-parent-1") - parent.State = task.StateQueued - parent.StoryID = story.ID - store.CreateTask(parent) - - for i := 0; i < 2; i++ { - sub := makeTask(fmt.Sprintf("queued-sub-%d", i)) - sub.ParentTaskID = parent.ID - sub.StoryID = story.ID - sub.State = task.StateCompleted - store.CreateTask(sub) - } - - pool.RecoverStaleBlocked() - - got, err := store.GetTask(parent.ID) - if err != nil { - t.Fatalf("GetTask: %v", err) - } - if got.State != task.StateReady { - t.Errorf("parent state: want READY, got %s", got.State) - } - - // Story should still be IN_PROGRESS — READY tasks don't satisfy the completion check; - // the task must be accepted (READY → COMPLETED) before the story advances to SHIPPABLE. - s, err := store.GetStory(story.ID) - if err != nil { - t.Fatalf("GetStory: %v", err) - } - if s.Status != task.StoryInProgress { - t.Errorf("story status: want IN_PROGRESS, got %s", s.Status) - } -} - // TestPool_RecoverStaleBlocked_DoesNotPromoteQueuedLeafTask verifies that a top-level // QUEUED task with NO subtasks is not promoted to READY by RecoverStaleBlocked. // This guards against the bug where a task that failed to start (stuck in QUEUED due @@ -878,46 +830,6 @@ func TestPool_RecoverStaleBlocked_DoesNotPromoteQueuedLeafTask(t *testing.T) { } } -// TestPool_CheckStoryCompletion_ReadyTasksNotSufficient verifies that READY tasks -// alone do not advance a story to SHIPPABLE — tasks must be COMPLETED. -func TestPool_CheckStoryCompletion_ReadyTasksNotSufficient(t *testing.T) { - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - now := time.Now().UTC() - story := &task.Story{ - ID: "story-ready-only", - Name: "Ready Only Story", - Status: task.StoryInProgress, - CreatedAt: now, - UpdatedAt: now, - } - store.CreateStory(story) - - // One task driven to READY (checker pending), one COMPLETED. - tk1 := makeTask("ro-task-1") - tk1.StoryID = story.ID - store.CreateTask(tk1) - for _, s := range []task.State{task.StateQueued, task.StateRunning, task.StateReady} { - store.UpdateTaskState(tk1.ID, s) - } - - tk2 := makeTask("ro-task-2") - tk2.StoryID = story.ID - store.CreateTask(tk2) - for _, s := range []task.State{task.StateQueued, task.StateRunning, task.StateReady, task.StateCompleted} { - store.UpdateTaskState(tk2.ID, s) - } - - pool.checkStoryCompletion(context.Background(), story.ID) - - got, _ := store.GetStory(story.ID) - if got.Status != task.StoryInProgress { - t.Errorf("story status: want IN_PROGRESS (tk1 still READY/checker pending), got %s", got.Status) - } -} - func TestPool_ActivePerAgent_DeletesZeroEntries(t *testing.T) { store := testStore(t) runner := &mockRunner{} @@ -1248,13 +1160,8 @@ func (m *minimalMockStore) UpdateExecutionChangestats(execID string, stats *task } func (m *minimalMockStore) RecordAgentEvent(_ storage.AgentEvent) error { return nil } func (m *minimalMockStore) GetProject(_ string) (*task.Project, error) { return nil, nil } -func (m *minimalMockStore) GetStory(_ string) (*task.Story, error) { return nil, nil } -func (m *minimalMockStore) ListTasksByStory(_ string) ([]*task.Task, error) { return nil, nil } -func (m *minimalMockStore) UpdateStoryStatus(_ string, _ task.StoryState) error { return nil } -func (m *minimalMockStore) CreateTask(_ *task.Task) error { return nil } -func (m *minimalMockStore) CreateEvent(_ *event.Event) error { return nil } -func (m *minimalMockStore) UpdateTaskCheckerReport(_ string, _ string) error { return nil } -func (m *minimalMockStore) GetCheckerTask(_ string) (*task.Task, error) { return nil, nil } +func (m *minimalMockStore) CreateTask(_ *task.Task) error { return nil } +func (m *minimalMockStore) CreateEvent(_ *event.Event) error { return nil } func (m *minimalMockStore) lastStateUpdate() (string, task.State, bool) { m.mu.Lock() @@ -1778,290 +1685,6 @@ func TestPool_ConsecutiveFailures_ResetOnSuccess(t *testing.T) { } } -func TestPool_CheckStoryCompletion_AllComplete(t *testing.T) { - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - // Create a story in IN_PROGRESS state. - now := time.Now().UTC() - story := &task.Story{ - ID: "story-comp-1", - Name: "Completion Test", - Status: task.StoryInProgress, - CreatedAt: now, - UpdatedAt: now, - } - if err := store.CreateStory(story); err != nil { - t.Fatalf("CreateStory: %v", err) - } - - // Create two top-level story tasks and drive them through valid transitions to COMPLETED. - for i, id := range []string{"sctask-1", "sctask-2"} { - tk := makeTask(id) - tk.StoryID = "story-comp-1" - tk.State = task.StatePending - if err := store.CreateTask(tk); err != nil { - t.Fatalf("CreateTask %d: %v", i, err) - } - for _, s := range []task.State{task.StateQueued, task.StateRunning, task.StateReady, task.StateCompleted} { - if err := store.UpdateTaskState(id, s); err != nil { - t.Fatalf("UpdateTaskState %s → %s: %v", id, s, err) - } - } - } - - pool.checkStoryCompletion(context.Background(), "story-comp-1") - - got, err := store.GetStory("story-comp-1") - if err != nil { - t.Fatalf("GetStory: %v", err) - } - if got.Status != task.StoryShippable { - t.Errorf("story status: want SHIPPABLE, got %v", got.Status) - } -} - -func TestPool_CheckStoryCompletion_PartialComplete(t *testing.T) { - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - now := time.Now().UTC() - story := &task.Story{ - ID: "story-partial-1", - Name: "Partial Test", - Status: task.StoryInProgress, - CreatedAt: now, - UpdatedAt: now, - } - if err := store.CreateStory(story); err != nil { - t.Fatalf("CreateStory: %v", err) - } - - // First top-level task driven to READY. - tk1 := makeTask("sptask-1") - tk1.StoryID = "story-partial-1" - store.CreateTask(tk1) - for _, s := range []task.State{task.StateQueued, task.StateRunning, task.StateReady} { - store.UpdateTaskState("sptask-1", s) - } - - // Second top-level task still in PENDING (not done). - tk2 := makeTask("sptask-2") - tk2.StoryID = "story-partial-1" - store.CreateTask(tk2) - - pool.checkStoryCompletion(context.Background(), "story-partial-1") - - got, err := store.GetStory("story-partial-1") - if err != nil { - t.Fatalf("GetStory: %v", err) - } - if got.Status != task.StoryInProgress { - t.Errorf("story status: want IN_PROGRESS (no transition), got %v", got.Status) - } -} - -func TestPool_StoryDeploy_RunsDeployScript(t *testing.T) { - store := testStore(t) - runner := &mockRunner{} - runners := map[string]Runner{"claude": runner} - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, runners, store, logger) - - // Create a deploy script that writes a marker file. - tmpDir := t.TempDir() - markerFile := filepath.Join(tmpDir, "deployed.marker") - scriptPath := filepath.Join(tmpDir, "deploy.sh") - scriptContent := "#!/bin/sh\ntouch " + markerFile + "\n" - if err := os.WriteFile(scriptPath, []byte(scriptContent), 0755); err != nil { - t.Fatalf("write deploy script: %v", err) - } - - proj := &task.Project{ - ID: "proj-deploy-1", - Name: "Deploy Test Project", - DeployScript: scriptPath, - } - if err := store.CreateProject(proj); err != nil { - t.Fatalf("create project: %v", err) - } - - story := &task.Story{ - ID: "story-deploy-1", - Name: "Deploy Test Story", - ProjectID: proj.ID, - Status: task.StoryShippable, - } - if err := store.CreateStory(story); err != nil { - t.Fatalf("create story: %v", err) - } - - pool.triggerStoryDeploy(context.Background(), story.ID) - - if _, err := os.Stat(markerFile); os.IsNotExist(err) { - t.Error("deploy script did not run: marker file not found") - } - - got, err := store.GetStory(story.ID) - if err != nil { - t.Fatalf("get story: %v", err) - } - if got.Status != task.StoryDeployed { - t.Errorf("story status: want DEPLOYED, got %q", got.Status) - } -} - -func runGit(t *testing.T, dir string, args ...string) { - t.Helper() - cmd := exec.Command("git", args...) - if dir != "" { - cmd.Dir = dir - } - if out, err := cmd.CombinedOutput(); err != nil { - t.Fatalf("git %v: %v\n%s", args, err, out) - } -} - -func TestPool_StoryDeploy_MergesStoryBranch(t *testing.T) { - tmpDir := t.TempDir() - - // Set up bare repo + working copy with a story branch. - bareDir := filepath.Join(tmpDir, "bare.git") - localDir := filepath.Join(tmpDir, "local") - runGit(t, "", "init", "--bare", bareDir) - runGit(t, "", "clone", bareDir, localDir) - runGit(t, localDir, "config", "user.email", "test@test.com") - runGit(t, localDir, "config", "user.name", "Test") - - // Initial commit on main. - runGit(t, localDir, "checkout", "-b", "main") - os.WriteFile(filepath.Join(localDir, "README.md"), []byte("initial"), 0644) - runGit(t, localDir, "add", ".") - runGit(t, localDir, "commit", "-m", "initial") - runGit(t, localDir, "push", "-u", "origin", "main") - - // Story branch with a feature commit. - runGit(t, localDir, "checkout", "-b", "story/test-feature") - os.WriteFile(filepath.Join(localDir, "feature.go"), []byte("package main"), 0644) - runGit(t, localDir, "add", ".") - runGit(t, localDir, "commit", "-m", "feature work") - runGit(t, localDir, "push", "origin", "story/test-feature") - runGit(t, localDir, "checkout", "main") - - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - scriptPath := filepath.Join(tmpDir, "deploy.sh") - os.WriteFile(scriptPath, []byte("#!/bin/sh\nexit 0\n"), 0755) - - proj := &task.Project{ - ID: "proj-merge-1", Name: "Merge Test", - LocalPath: localDir, DeployScript: scriptPath, - } - if err := store.CreateProject(proj); err != nil { - t.Fatalf("create project: %v", err) - } - story := &task.Story{ - ID: "story-merge-1", Name: "Merge Test Story", - ProjectID: proj.ID, BranchName: "story/test-feature", - Status: task.StoryShippable, - } - if err := store.CreateStory(story); err != nil { - t.Fatalf("create story: %v", err) - } - - pool.triggerStoryDeploy(context.Background(), story.ID) - - // feature.go should now be on main in the working copy. - if _, err := os.Stat(filepath.Join(localDir, "feature.go")); os.IsNotExist(err) { - t.Error("story branch was not merged to main: feature.go missing") - } - got, _ := store.GetStory(story.ID) - if got.Status != task.StoryDeployed { - t.Errorf("story status: want DEPLOYED, got %q", got.Status) - } -} - -func TestPool_PostDeploy_CreatesValidationTask(t *testing.T) { - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - now := time.Now().UTC() - validationSpec := `{"type":"smoke","steps":["curl /health"],"success_criteria":"status 200"}` - story := &task.Story{ - ID: "story-postdeploy-1", - Name: "Post Deploy Test", - Status: task.StoryDeployed, - ValidationJSON: validationSpec, - CreatedAt: now, - UpdatedAt: now, - } - if err := store.CreateStory(story); err != nil { - t.Fatalf("CreateStory: %v", err) - } - - pool.createValidationTask(context.Background(), story.ID) - - // Story should now be VALIDATING. - got, err := store.GetStory(story.ID) - if err != nil { - t.Fatalf("GetStory: %v", err) - } - if got.Status != task.StoryValidating { - t.Errorf("story status: want VALIDATING, got %q", got.Status) - } - - // A validation task should have been created. - tasks, err := store.ListTasksByStory(story.ID) - if err != nil { - t.Fatalf("ListTasksByStory: %v", err) - } - if len(tasks) == 0 { - t.Fatal("expected a validation task to be created, got none") - } - vtask := tasks[0] - if !strings.Contains(strings.ToLower(vtask.Name), "validation") { - t.Errorf("task name %q does not contain 'validation'", vtask.Name) - } - if vtask.StoryID != story.ID { - t.Errorf("task story_id: want %q, got %q", story.ID, vtask.StoryID) - } - if !strings.Contains(vtask.Agent.Instructions, "smoke") { - t.Errorf("task instructions %q do not reference validation spec content", vtask.Agent.Instructions) - } -} - -func TestPool_ValidationTask_Pass_SetsReviewReady(t *testing.T) { - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - now := time.Now().UTC() - story := &task.Story{ - ID: "story-val-pass-1", - Name: "Validation Pass", - Status: task.StoryValidating, - CreatedAt: now, - UpdatedAt: now, - } - if err := store.CreateStory(story); err != nil { - t.Fatalf("CreateStory: %v", err) - } - - pool.checkValidationResult(context.Background(), story.ID, task.StateCompleted, "") - - got, err := store.GetStory(story.ID) - if err != nil { - t.Fatalf("GetStory: %v", err) - } - if got.Status != task.StoryReviewReady { - t.Errorf("story status: want REVIEW_READY, got %q", got.Status) - } -} // TestPool_DependsOn_NoDeadlock verifies that a task waiting for a dependency // does NOT hold the per-agent slot, allowing the dependency to run first. @@ -2118,35 +1741,6 @@ func TestPool_DependsOn_NoDeadlock(t *testing.T) { } } -func TestPool_ValidationTask_Fail_SetsNeedsFix(t *testing.T) { - store := testStore(t) - logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) - pool := NewPool(2, map[string]Runner{"claude": &mockRunner{}}, store, logger) - - now := time.Now().UTC() - story := &task.Story{ - ID: "story-val-fail-1", - Name: "Validation Fail", - Status: task.StoryValidating, - CreatedAt: now, - UpdatedAt: now, - } - if err := store.CreateStory(story); err != nil { - t.Fatalf("CreateStory: %v", err) - } - - execErr := "smoke test failed: /health returned 503" - pool.checkValidationResult(context.Background(), story.ID, task.StateFailed, execErr) - - got, err := store.GetStory(story.ID) - if err != nil { - t.Fatalf("GetStory: %v", err) - } - if got.Status != task.StoryNeedsFix { - t.Errorf("story status: want NEEDS_FIX, got %q", got.Status) - } -} - func TestPool_Shutdown_WaitsForWorkers(t *testing.T) { store := testStore(t) started := make(chan struct{}) @@ -2229,141 +1823,3 @@ func TestPool_Shutdown_TimesOut(t *testing.T) { close(unblock) // cleanup } -func TestPool_CheckerSpawned_OnReady(t *testing.T) { - store := testStore(t) - runner := &mockRunner{} // succeeds instantly - pool := NewPool(2, map[string]Runner{"claude": runner}, store, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))) - - tk := makeTask("checker-spawn-1") - tk.RepositoryURL = "https://github.com/x/y" - store.CreateTask(tk) - pool.Submit(context.Background(), tk) - <-pool.Results() // wait for original task to finish - - // Poll until the async spawnCheckerTask goroutine has written the checker task. - var checker *task.Task - var err error - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - checker, err = store.GetCheckerTask("checker-spawn-1") - if err != nil { - t.Fatalf("GetCheckerTask: %v", err) - } - if checker != nil { - break - } - time.Sleep(50 * time.Millisecond) - } - if checker == nil { - t.Fatal("expected a checker task to be created, got nil") - } - if checker.CheckerForTaskID != "checker-spawn-1" { - t.Errorf("expected CheckerForTaskID=checker-spawn-1, got %q", checker.CheckerForTaskID) - } -} - -func TestPool_CheckerNotSpawned_ForSubtask(t *testing.T) { - store := testStore(t) - runner := &mockRunner{} - pool := NewPool(2, map[string]Runner{"claude": runner}, store, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))) - - parent := makeTask("no-checker-parent") - parent.RepositoryURL = "https://github.com/x/y" - store.CreateTask(parent) - - sub := makeTask("no-checker-sub") - sub.ParentTaskID = "no-checker-parent" - sub.RepositoryURL = "https://github.com/x/y" - store.CreateTask(sub) - - pool.Submit(context.Background(), sub) - <-pool.Results() - - time.Sleep(100 * time.Millisecond) - - checker, err := store.GetCheckerTask("no-checker-sub") - if err != nil { - t.Fatalf("GetCheckerTask: %v", err) - } - if checker != nil { - t.Error("expected no checker for subtask, but one was created") - } -} - -func TestPool_CheckerPass_AutoAcceptsTask(t *testing.T) { - store := testStore(t) - // Two-phase: first runner succeeds (original task), second also succeeds (checker). - runner := &mockRunner{ - onRun: func(t *task.Task, e *storage.Execution) error { - return nil // both original and checker succeed - }, - } - pool := NewPool(2, map[string]Runner{"claude": runner}, store, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))) - - tk := makeTask("autoaccept-1") - tk.RepositoryURL = "https://github.com/x/y" - store.CreateTask(tk) - pool.Submit(context.Background(), tk) - <-pool.Results() // original finishes → READY + checker spawned - - // Wait for checker to run and complete. - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - got, _ := store.GetTask("autoaccept-1") - if got != nil && got.State == task.StateCompleted { - break - } - <-pool.Results() - } - - got, err := store.GetTask("autoaccept-1") - if err != nil { - t.Fatalf("GetTask: %v", err) - } - if got.State != task.StateCompleted { - t.Errorf("expected COMPLETED after checker pass, got %s", got.State) - } -} - -func TestPool_CheckerFail_AttachesReport(t *testing.T) { - store := testStore(t) - runner := &mockRunner{ - onRun: func(t *task.Task, e *storage.Execution) error { - if t.CheckerForTaskID != "" { - return fmt.Errorf("test suite failed: 3 failures") - } - return nil // original task succeeds - }, - } - pool := NewPool(2, map[string]Runner{"claude": runner}, store, slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))) - - tk := makeTask("fail-checker-1") - tk.RepositoryURL = "https://github.com/x/y" - store.CreateTask(tk) - pool.Submit(context.Background(), tk) - <-pool.Results() // original → READY - - // Wait for checker to fail. - deadline := time.Now().Add(5 * time.Second) - for time.Now().Before(deadline) { - got, _ := store.GetTask("fail-checker-1") - if got != nil && got.CheckerReport != "" { - break - } - select { - case <-pool.Results(): - case <-time.After(100 * time.Millisecond): - } - } - - got, err := store.GetTask("fail-checker-1") - if err != nil { - t.Fatalf("GetTask: %v", err) - } - if got.State != task.StateReady { - t.Errorf("expected task to stay READY after checker fail, got %s", got.State) - } - if got.CheckerReport == "" { - t.Error("expected checker_report to be set after checker failure") - } -} |
