Skip to content

Epic: Claude-Powered GitHub Issue Processor - Stage 3: Task Queue and Worker Infrastructure #3

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 3 of N)

This issue focuses on implementing a task queue to manage detected issues and setting up the basic structure for worker processes that will handle these issues.

  • What's being done in this issue: Integrate a task queue (BullMQ with Redis for Node.js), modify the daemon to add tasks, create a basic worker to consume tasks, and implement initial issue state tagging ("AI-processing").
  • What's been done (from #[URL_OF_ISSUE_1_GOES_HERE], #[URL_OF_ISSUE_2_GOES_HERE]): Authentication, logging, project structure, and the issue detection daemon are in place.
  • What's remaining: Full worker implementation (Git operations, Claude integration), PR automation, robust state management, advanced error handling, etc.

Task Details

  1. Task Queue Setup (Node.js with BullMQ):
    • Add bullmq and ioredis as project dependencies.
    • Create a module (e.g., src/queue/taskQueue.js) to initialize and export BullMQ Queue and Worker instances.
    • Configure connection to a Redis instance (details via environment variables like REDIS_HOST, REDIS_PORT).
    • Define a queue name (e.g., GITHUB_ISSUE_PROCESSOR_QUEUE).
    • Relevant Proposal Section: 2.1.3
  2. Modify Daemon (src/daemon.js):
    • Import the task queue instance.
    • When an eligible issue is detected, instead of just logging, create a job and add it to the BullMQ queue.
    • The job payload should contain necessary information for the worker (e.g., issueId, issueNumber, repoOwner, repoName, issueTitle, issueUrl).
    • Log when a task is successfully added to the queue.
  3. Basic Worker Implementation (src/worker.js):
    • Create a new Node.js script that defines and starts a BullMQ worker.
    • The worker should connect to the same queue as the daemon.
    • Worker Process Function:
      • Receive a job from the queue.
      • Log the details of the task being processed.
      • GitHub Issue Tagging:
        • Use the authenticated GitHub client (src/auth/githubAuth.js) to interact with the GitHub API.
        • Add a specific tag (e.g., configurable AI_PROCESSING_TAG="AI-processing") to the GitHub issue to indicate it's being worked on. This helps prevent reprocessing by the daemon.
        • Log the success or failure of the tagging operation.
      • Placeholder for Core Logic: Add a comment indicating where future, more complex processing steps (Git operations, Claude execution, result handling) will be integrated. For now, simulate work with a setTimeout.
      • Error Handling: Implement basic error handling for job processing. Log errors. BullMQ handles retries based on configuration.
  4. Running Workers:
    • Document how to start one or more worker processes (e.g., node src/worker.js). These will run independently of the daemon.
  5. Initial State Management Considerations:
    • The "AI-processing" tag is the first step.
    • Briefly discuss (in comments/documentation) the future need for more robust, persistent state management (e.g., using a simple database like SQLite or Redis) to track the full lifecycle of tasks beyond just GitHub tags. This is crucial for resilience and recovery. (Sec 2.1.4)

Acceptance Criteria

  • BullMQ and Redis are configured and integrated into the project.
  • The daemon (src/daemon.js) successfully adds jobs to the BullMQ queue for detected issues.
  • The worker script (src/worker.js) can be run and processes jobs from the queue.
  • Workers correctly add the "AI-processing" tag to the corresponding GitHub issue.
  • Basic logging is in place for queue operations and worker activity.

Activity

  1. integry commented on May 23, 2025

    @integry
    OwnerAuthor

    Suggested Implementation Snippets (Node.js)

    1. Task Queue Setup (src/queue/taskQueue.js)

    Install BullMQ and ioredis:

    npm install bullmq ioredis
    // src/queue/taskQueue.js
    import { Queue, Worker } from 'bullmq';
    import Redis from 'ioredis';
    import logger from '../utils/logger.js';
    import 'dotenv/config';
    
    const REDIS_HOST = process.env.REDIS_HOST || '127.0.0.1';
    const REDIS_PORT = parseInt(process.env.REDIS_PORT || '6379', 10);
    
    const connectionOptions = {
        host: REDIS_HOST,
        port: REDIS_PORT,
        maxRetriesPerRequest: null, // Important for BullMQ
        enableReadyCheck: false,
    };
    
    const redisConnection = new Redis(connectionOptions);
    
    redisConnection.on('connect', () => logger.info('Successfully connected to Redis for BullMQ.'));
    redisConnection.on('error', (err) => logger.error({ err }, 'Redis connection error for BullMQ.'));
    
    export const GITHUB_ISSUE_QUEUE_NAME = process.env.GITHUB_ISSUE_QUEUE_NAME || 'github-issue-processor';
    
    export const issueQueue = new Queue(GITHUB_ISSUE_QUEUE_NAME, { connection: redisConnection });
    
    issueQueue.on('error', err => logger.error({ queue: GITHUB_ISSUE_QUEUE_NAME, err }, 'Queue error'));
    
    /**
     * Creates and starts a BullMQ worker.
     * @param {string} queueName - The name of the queue to process.
     * @param {Function} processorFunction - The async function to process jobs. processorFunction(job)
     */
    export function createWorker(queueName, processorFunction) {
        const worker = new Worker(queueName, processorFunction, {
            connection: redisConnection,
            concurrency: parseInt(process.env.WORKER_CONCURRENCY || '5', 10),
        });
    
        worker.on('completed', (job, result) => {
            logger.info({ jobId: job.id, jobName: job.name, result }, `Job completed.`);
        });
    
        worker.on('failed', (job, err) => {
            logger.error({ jobId: job?.id, jobName: job?.name, data: job?.data, errMessage: err.message, stack: err.stack }, `Job failed.`);
        });
    
        worker.on('error', err => {
            logger.error({ queue: queueName, errMessage: err.message }, 'Worker error');
        });
    
        logger.info(`Worker started & listening to queue: ${queueName}`);
        return worker;
    }

    2. Modify Daemon (src/daemon.js) to add jobs to queue
    (Ensure src/daemon.js is updated as per the diff in the previous response, using issueQueue.add)

    (Example diff line to add: import { issueQueue } from './queue/taskQueue.js';)
    (Example diff line for adding to queue: await issueQueue.add('processGitHubIssue', issue, { jobId: issue-${issue.repoOwner}-${issue.repoName}-${issue.number} });)

    3. Basic Worker Implementation (src/worker.js)

    // src/worker.js
    import 'dotenv/config';
    import { GITHUB_ISSUE_QUEUE_NAME, createWorker } from './queue/taskQueue.js';
    import logger from './utils/logger.js';
    import { getAuthenticatedOctokit } from './auth/githubAuth.js';
    
    const AI_PROCESSING_TAG = process.env.AI_PROCESSING_TAG || 'AI-processing';
    const AI_PRIMARY_TAG = process.env.AI_PRIMARY_TAG || 'AI';
    
    async function processGitHubIssueJob(job) {
        const { id: jobId, name: jobName, data: issue } = job;
        logger.info({ jobId, jobName, issueNumber: issue.number, repo: `${issue.repoOwner}/${issue.repoName}` }, 'Processing job');
    
        let octokit;
        try {
            octokit = await getAuthenticatedOctokit();
        } catch (authError) {
            logger.error({ jobId, errMessage: authError.message }, 'Worker: Failed to get authenticated Octokit instance.');
            throw authError;
        }
    
        try {
            const currentIssueData = await octokit.request('GET /repos/{owner}/{repo}/issues/{issue_number}', {
                owner: issue.repoOwner,
                repo: issue.repoName,
                issue_number: issue.number,
            });
    
            const currentLabels = currentIssueData.data.labels.map(label => label.name);
            const hasProcessingTag = currentLabels.includes(AI_PROCESSING_TAG);
            const hasPrimaryTag = currentLabels.includes(AI_PRIMARY_TAG);
    
            if (!hasPrimaryTag) {
                 logger.warn({ jobId, issueNumber: issue.number }, `Issue no longer has primary tag '${AI_PRIMARY_TAG}'. Skipping.`);
                 return { status: 'skipped', reason: 'Primary tag missing' };
            }
    
            if (hasProcessingTag) {
                logger.warn({ jobId, issueNumber: issue.number }, `Issue already has '${AI_PROCESSING_TAG}' tag. Proceeding with logic.`);
            } else {
                logger.info({ jobId, issueNumber: issue.number }, `Adding '${AI_PROCESSING_TAG}' tag.`);
                await octokit.request('POST /repos/{owner}/{repo}/issues/{issue_number}/labels', {
                    owner: issue.repoOwner,
                    repo: issue.repoName,
                    issue_number: issue.number,
                    labels: [AI_PROCESSING_TAG],
                });
                logger.info({ jobId, issueNumber: issue.number }, `Successfully added '${AI_PROCESSING_TAG}' tag.`);
            }
    
            logger.info({ jobId, issueNumber: issue.number }, 'Starting core processing (Git, Claude)...');
            await new Promise(resolve => setTimeout(resolve, parseInt(process.env.SIMULATED_WORK_MS || '5000', 10) ));
            logger.info({ jobId, issueNumber: issue.number }, 'Core processing simulation complete.');
    
            return { status: 'simulated_processing_complete', issueNumber: issue.number };
    
        } catch (error) {
            logger.error({ jobId, issueNumber: issue.number, errMessage: error.message, stack: error.stack }, 'Error processing GitHub issue job.');
            throw error;
        }
    }
    
    logger.info('Attempting to start GitHub Issue Worker...');
    createWorker(GITHUB_ISSUE_QUEUE_NAME, processGitHubIssueJob);

    Environment Variables Reminder (.env):

    # For Queue & Worker
    REDIS_HOST=127.0.0.1
    REDIS_PORT=6379
    GITHUB_ISSUE_QUEUE_NAME=github-issue-processor
    WORKER_CONCURRENCY=2
    AI_PROCESSING_TAG=AI-processing
    SIMULATED_WORK_MS=5000 # For faster testing
    
    # Inherited:
    # GITHUB_REPOS_TO_MONITOR=...
    # ... and other auth/logging vars

    This comment provides initial code suggestions. Ensure Redis is running and accessible.

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