diff options
| author | Peter Stone <thepeterstone@gmail.com> | 2026-03-24 21:54:31 +0000 |
|---|---|---|
| committer | Peter Stone <thepeterstone@gmail.com> | 2026-03-24 21:54:31 +0000 |
| commit | 407fbc8d346b986bf864452c865282aa726272e2 (patch) | |
| tree | 274aa7861a6e4316c1919e93d944023d60846b44 /internal/executor | |
| parent | e3954992af63440986bd39cce889e9c62e1a6b92 (diff) | |
| parent | b2e77009c55ba0f07bb9ff904d9f2f6cc9ff0ee2 (diff) | |
fix: resolve merge conflict — integrate agent's story-aware ContainerRunner
Agent added: Store on ContainerRunner (direct story/project lookup), --reference
clone for speed, explicit story branch push, checkStoryCompletion → SHIPPABLE.
My additions: BranchName on Task as fallback when Store is nil, tests updated
to match checkout-after-clone approach.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Diffstat (limited to 'internal/executor')
| -rw-r--r-- | internal/executor/container.go | 50 | ||||
| -rw-r--r-- | internal/executor/container_test.go | 23 | ||||
| -rw-r--r-- | internal/executor/executor.go | 28 | ||||
| -rw-r--r-- | internal/executor/executor_test.go | 96 |
4 files changed, 175 insertions, 22 deletions
diff --git a/internal/executor/container.go b/internal/executor/container.go index d270e20..8b244c6 100644 --- a/internal/executor/container.go +++ b/internal/executor/container.go @@ -28,6 +28,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 // Command allows mocking exec.CommandContext for tests. Command func(ctx context.Context, name string, arg ...string) *exec.Cmd } @@ -95,21 +96,46 @@ 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 + } + } + } + } + // Fall back to task-level BranchName (e.g. set explicitly by executor or tests). + if storyBranch == "" { + storyBranch = t.BranchName + } + // 2. Clone repo into workspace if not resuming. // git clone requires the target directory to not exist; remove the MkdirTemp-created dir first. if !isResume { if err := os.Remove(workspace); err != nil { return fmt.Errorf("removing workspace before clone: %w", err) } - r.Logger.Info("cloning repository", "url", repoURL, "workspace", workspace, "branch", t.BranchName) - cloneArgs := []string{"clone"} - if t.BranchName != "" { - cloneArgs = append(cloneArgs, "--branch", t.BranchName) + r.Logger.Info("cloning repository", "url", repoURL, "workspace", workspace) + var cloneArgs []string + if storyLocalPath != "" { + cloneArgs = []string{"clone", "--reference", storyLocalPath, repoURL, workspace} + } else { + cloneArgs = []string{"clone", repoURL, workspace} } - cloneArgs = append(cloneArgs, repoURL, 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 err = os.Chmod(workspace, 0755); err != nil { return fmt.Errorf("chmod cloned workspace: %w", err) } @@ -150,7 +176,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) + runErr := r.runContainer(ctx, t, e, workspace, agentHome, isResume, storyBranch) 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() @@ -164,7 +190,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) + runErr = r.runContainer(ctx, t, e, workspace, agentHome, isResume, storyBranch) } if runErr == nil { @@ -180,7 +206,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) error { +func (r *ContainerRunner) runContainer(ctx context.Context, t *task.Task, e *storage.Execution, workspace, agentHome string, isResume bool, storyBranch string) error { repoURL := t.RepositoryURL image := t.Agent.ContainerImage @@ -327,8 +353,12 @@ func (r *ContainerRunner) runContainer(ctx context.Context, t *task.Task, e *sto } if hasCommits { - r.Logger.Info("pushing changes back to remote", "url", repoURL) - if out, err := r.command(ctx, "git", "-C", workspace, "push", "origin", "HEAD").CombinedOutput(); err != nil { + pushRef := "HEAD" + if storyBranch != "" { + pushRef = storyBranch + } + 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 { r.Logger.Warn("git push failed", "error", err, "output", string(out)) return fmt.Errorf("git push failed: %w\n%s", err, string(out)) } diff --git a/internal/executor/container_test.go b/internal/executor/container_test.go index c56d1b2..15c147f 100644 --- a/internal/executor/container_test.go +++ b/internal/executor/container_test.go @@ -518,18 +518,23 @@ func TestContainerRunner_AuthError_SyncsAndRetries(t *testing.T) { func TestContainerRunner_ClonesStoryBranch(t *testing.T) { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) - var cloneArgs []string + var checkoutArgs []string runner := &ContainerRunner{ Logger: logger, Image: "busybox", Command: func(ctx context.Context, name string, arg ...string) *exec.Cmd { if name == "git" && len(arg) > 0 && arg[0] == "clone" { - cloneArgs = append([]string{}, arg...) dir := arg[len(arg)-1] os.MkdirAll(dir, 0755) return exec.Command("true") } - // docker run fails so the test exits quickly + // Capture checkout calls: both "git checkout <branch>" and "git -C <dir> checkout <branch>" + for i, a := range arg { + if a == "checkout" { + checkoutArgs = append([]string{}, arg[i:]...) + break + } + } if name == "docker" { return exec.Command("sh", "-c", "exit 1") } @@ -548,19 +553,19 @@ func TestContainerRunner_ClonesStoryBranch(t *testing.T) { runner.Run(context.Background(), tk, e) os.RemoveAll(e.SandboxDir) - // Assert git clone was called with --branch <branchName> - if len(cloneArgs) < 3 { - t.Fatalf("expected clone args, got %v", cloneArgs) + // Assert git checkout was called with the story branch name. + if len(checkoutArgs) == 0 { + t.Fatal("expected git checkout to be called for story branch, but it was not") } found := false - for i, a := range cloneArgs { - if a == "--branch" && i+1 < len(cloneArgs) && cloneArgs[i+1] == "story/my-feature" { + for _, a := range checkoutArgs { + if a == "story/my-feature" { found = true break } } if !found { - t.Errorf("expected git clone --branch story/my-feature, got args: %v", cloneArgs) + t.Errorf("expected git checkout story/my-feature, got args: %v", checkoutArgs) } } diff --git a/internal/executor/executor.go b/internal/executor/executor.go index 6489060..8dfb196 100644 --- a/internal/executor/executor.go +++ b/internal/executor/executor.go @@ -34,6 +34,8 @@ type Store interface { 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 } // LogPather is an optional interface runners can implement to provide the log @@ -406,6 +408,9 @@ func (p *Pool) handleRunResult(ctx context.Context, t *task.Task, exec *storage. } p.maybeUnblockParent(t.ParentTaskID) } + if t.StoryID != "" { + go p.checkStoryCompletion(ctx, t.StoryID) + } } summary := exec.Summary @@ -437,6 +442,29 @@ 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 tasks in a story have reached a terminal +// success state and transitions the story to SHIPPABLE if so. +func (p *Pool) checkStoryCompletion(ctx context.Context, storyID string) { + 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 + } + for _, t := range tasks { + if t.State != task.StateCompleted && t.State != task.StateReady { + return // not all tasks done + } + } + 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) +} + // UndrainingAgent resets the drain state and failure counter for the given agent type. func (p *Pool) UndrainingAgent(agentType string) { p.mu.Lock() diff --git a/internal/executor/executor_test.go b/internal/executor/executor_test.go index 2e01230..b93e819 100644 --- a/internal/executor/executor_test.go +++ b/internal/executor/executor_test.go @@ -1056,9 +1056,11 @@ func (m *minimalMockStore) UpdateExecutionChangestats(execID string, stats *task m.mu.Unlock() return nil } -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) 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) lastStateUpdate() (string, task.State, bool) { m.mu.Lock() @@ -1625,6 +1627,94 @@ 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 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.ParentTaskID = "fake-parent" // so it goes to COMPLETED + 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.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 task driven to COMPLETED. + tk1 := makeTask("sptask-1") + tk1.StoryID = "story-partial-1" + tk1.ParentTaskID = "fake-parent" + store.CreateTask(tk1) + for _, s := range []task.State{task.StateQueued, task.StateRunning, task.StateCompleted} { + store.UpdateTaskState("sptask-1", s) + } + + // Second task still in PENDING (not done). + tk2 := makeTask("sptask-2") + tk2.StoryID = "story-partial-1" + tk2.ParentTaskID = "fake-parent" + 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_Undrain_ResumesExecution(t *testing.T) { store := testStore(t) |
