Skip to content

Epic: Claude-Powered GitHub Issue Processor - Stage 4: Git Environment Management for Workers #4

Closed

Description

@integry

General Goal of the Epic

To create an automated system that monitors GitHub issues, uses Anthropic's Claude Code to generate solutions, and automates the Git workflow including PR creation.

Current Stage (Issue 4 of N)

This issue focuses on enabling worker processes to set up and manage local Git environments for processing individual GitHub issues. This involves cloning repositories and creating isolated worktrees.

  • What's being done in this issue: Implement scripts/modules within the worker to handle repository cloning (efficiently), create new Git worktrees for each issue, and manage branch creation within these worktrees.
  • What's been done (from #[URL_OF_ISSUE_1_GOES_HERE], #[URL_OF_ISSUE_2_GOES_HERE], #[URL_OF_ISSUE_3_GOES_HERE]): Authentication, logging, daemon for issue detection, task queue, and basic worker infrastructure (including 'AI-processing' tagging) are established.
  • What's remaining: Claude Code integration, automated code changes, PR creation, comprehensive error handling, and cleanup.

Task Details

This task enables the worker to prepare a dedicated coding environment for each issue. (Refers to Proposal Section 2.2)

  1. Repository Cloning/Fetching Logic (Node.js module: src/git/repoManager.js or Bash script):
    • Develop a function/script that a worker can call with repository details (owner, name, default branch).
    • Cloning:
      • If the repository is not already cloned locally to a base directory (e.g., /opt/git-processor/clones/\<owner>/\<repo_name>), clone it using the GitHub token (from Issue 1's githubAuth.js).
      • Consider shallow clones (--depth 1) initially for efficiency, but note that Claude might benefit from more history (Sec 2.2.1). Make depth configurable.
    • Fetching Updates:
      • If the repository is already cloned, fetch updates (git fetch origin) to ensure it's up-to-date.
    • The base path for clones should be configurable.
  2. Git Worktree Creation Logic (part of repoManager.js or separate script):
    • Develop a function/script to create a new Git worktree for a given issue. (Sec 2.2.2)
    • Inputs: Path to the main cloned repository, issue ID, issue title, base branch name (e.g., 'main', 'develop' - should be configurable per repo or globally).
    • Worktree Path: Create a unique path for the worktree (e.g., /opt/git-processor/worktrees/\<owner>/\<repo_name>/\<issue_id>). This base path should be configurable.
    • Branch Creation:
      • Create a new branch for the worktree, named systematically (e.g., ai-fix/${issue_id}-${sanitized_issue_title}). (Sec 2.2.3)
      • Use git worktree add <path> -b <new_branch_name> <base_branch_name>.
    • Return the path to the created worktree directory.
  3. Directory Structure and Configuration:
    • Define and document the local directory structure for cloned repos and worktrees (Sec 2.2.4).
    • Ensure base paths for clones and worktrees are configurable via environment variables.
  4. Error Handling:
    • Implement robust error handling for all Git commands (clone, fetch, worktree add). Log errors clearly.
    • If a Git operation fails, the worker should report this failure back to the main worker loop (to be handled by updating issue state/tags in a later issue).
  5. Worker Integration:
    • The worker script (src/worker.js from Issue 3) should call these Git management functions after picking up a task and before Claude execution.
    • The path to the worktree should be passed to subsequent processing steps.

Acceptance Criteria

  • Worker can clone a new repository if it doesn't exist locally.
  • Worker can fetch updates for an existing local repository clone.
  • Worker can create a new Git worktree from a specified base branch, creating a new issue-specific branch.
  • Branch and worktree directory naming conventions are followed.
  • Paths for clones and worktrees are configurable.
  • Basic error handling for Git operations is implemented and logged.
  • The worker script integrates these steps successfully.

Activity

  1. integry commented on May 23, 2025

    @integry
    OwnerAuthor

    Suggested Implementation (Node.js / Bash)

    Node.js is preferred for easier integration with the existing worker, using libraries like simple-git or by spawning git child processes. Bash can be used for standalone git utility scripts invoked by the worker.

    1. Node.js Example using simple-git (Install simple-git)

    // src/git/repoManager.js
    import simpleGit from 'simple-git';
    import fs from 'fs-extra';
    import path from 'path';
    import logger from '../utils/logger.js';
    
    const CLONES_BASE_PATH = process.env.GIT_CLONES_BASE_PATH || "/opt/git-processor/clones";
    const WORKTREES_BASE_PATH = process.env.GIT_WORKTREES_BASE_PATH || "/opt/git-processor/worktrees";
    const GIT_DEFAULT_BRANCH = process.env.GIT_DEFAULT_BRANCH || 'main';
    const GIT_SHALLOW_CLONE_DEPTH = process.env.GIT_SHALLOW_CLONE_DEPTH ? parseInt(process.env.GIT_SHALLOW_CLONE_DEPTH) : undefined; // undefined for full clone
    
    async function getRepoPath(owner, repoName) {
        return path.join(CLONES_BASE_PATH, owner, repoName);
    }
    
    export async function ensureRepoCloned(repoUrl, owner, repoName, authToken) {
        const localRepoPath = await getRepoPath(owner, repoName);
        const git = simpleGit();
    
        try {
            if (await fs.pathExists(path.join(localRepoPath, ".git"))) {
                logger.info({ repo: repoUrl, path: localRepoPath }, 'Repository exists. Fetching updates...');
                await simpleGit(localRepoPath).fetch();
            } else {
                logger.info({ repo: repoUrl, path: localRepoPath }, 'Cloning repository...');
                await fs.ensureDir(localRepoPath);
                const cloneOptions = GIT_SHALLOW_CLONE_DEPTH ? [`--depth=${GIT_SHALLOW_CLONE_DEPTH}`] : [];
                const remoteWithAuth = repoUrl.replace('https://', `https://x-access-token:${authToken}@`);
                await git.clone(remoteWithAuth, localRepoPath, cloneOptions);
            }
            return localRepoPath;
        } catch (error) {
            logger.error({ repo: repoUrl, err: error.message }, 'Failed to clone/fetch repository.');
            throw error;
        }
    }
    
    export async function createWorktreeForIssue(localRepoPath, issueId, issueTitle, baseBranch = GIT_DEFAULT_BRANCH, owner, repoName) {
        const sanitizedTitle = issueTitle.toLowerCase().replace(/[^a-z0-9_]+/g, '-').substring(0, 50);
        const branchName = `ai-fix/${issueId}-${sanitizedTitle}`;
        const worktreeDirName = \`issue-\${issueId}\`;
        const worktreePath = path.join(WORKTREES_BASE_PATH, owner, repoName, worktreeDirName);
    
        try {
            if (await fs.pathExists(worktreePath)) {
                logger.warn({ worktreePath }, 'Worktree path already exists. Attempting to remove and recreate.');
                // First try git worktree remove (if it was a valid worktree)
                try {
                    await simpleGit(localRepoPath).raw([worktree, remove, worktreePath, --force]);
                } catch (removeError) {
                    logger.warn({ worktreePath, err: removeError.message }, 'Failed to remove existing worktree with git command, attempting direct fs delete.');
                }
                await fs.remove(worktreePath); // Force remove directory if git worktree remove failed or dir was orphaned
            }
    
            await fs.ensureDir(path.dirname(worktreePath));
            logger.info({ localRepoPath, worktreePath, branchName, baseBranch }, 'Creating worktree...');
            await simpleGit(localRepoPath).raw([worktree, add, worktreePath, -b, branchName, baseBranch]);
            logger.info(\`Worktree created at \${worktreePath} on branch \${branchName}\`);
            return worktreePath;
        } catch (error) {
            logger.error({ worktreePath, branchName, err: error.message }, 'Failed to create worktree.');
            throw error;
        }
    }
    
    export async function cleanupWorktree(localRepoPath, worktreePath, branchName) {
        logger.info({ worktreePath, branchName }, "Cleaning up worktree...");
        const gitRepo = simpleGit(localRepoPath);
        try {
            await gitRepo.raw(['worktree', 'remove', worktreePath, '--force']);
        } catch (error) {
            logger.warn({ worktreePath, err: error.message }, 'Failed to remove worktree using git command. Will attempt to delete directory directly.');
        }
        try {
            await fs.remove(worktreePath); // Ensure directory is gone
            logger.info({ worktreePath }, 'Worktree directory removed.');
        } catch (fsError) {
            logger.error({ worktreePath, err: fsError.message }, 'Failed to delete worktree directory.');
        }
        // Optional: Delete the local branch if not pushed / not needed anymore
        // try {
        //     await gitRepo.deleteLocalBranch(branchName, true); // true for force delete
        //     logger.info({ branchName }, "Local branch deleted.");
        // } catch (branchError) {
        //     logger.warn({ branchName, err: branchError.message }, "Failed to delete local branch.");
        // }
         // Periodically run `git worktree prune` on the main repo clone (outside this function, e.g. cron)
    }

    This comment provides initial code suggestions. Ensure simple-git and fs-extra are installed (npm install simple-git fs-extra). Error handling and cleanup logic (especially for orphaned worktrees or failed removals) should be robust.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions