Skip to content

Epic: Claude-Powered GitHub Issue Processor - Stage 2: GitHub Issue Detection Daemon #2

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

This issue focuses on developing the daemon responsible for detecting relevant GitHub issues eligible for AI processing.

  • What's being done in this issue: Create a Node.js daemon that polls specified GitHub repositories for issues matching defined criteria (specific tags present/absent).
  • What's been done (from #[URL_OF_ISSUE_1_GOES_HERE]): Foundational setup including authentication for GitHub, logging utilities, and basic project structure.
  • What's remaining: Task queuing for detected issues, worker implementation for processing, Git operations, Claude integration, PR automation, etc.

Task Details

  1. Daemon Implementation (Node.js - src/daemon.js):
    • Utilize the GitHub authentication module (src/auth/githubAuth.js) established in #[URL_OF_ISSUE_1_GOES_HERE].
    • Implement a primary function that periodically polls GitHub for issues.
  2. Configuration:
    • Load target repositories from an environment variable (e.g., GITHUB_REPOS_TO_MONITOR="owner1/repoA,owner2/repoB").
    • Load polling interval from an environment variable (e.g., POLLING_INTERVAL_MS="60000").
    • Define configurable primary tag for "AI" issues (e.g., AI_PRIMARY_TAG="AI") and exclusion tags (e.g., AI_EXCLUDE_TAGS_PROCESSING="AI-processing", AI_EXCLUDE_TAGS_DONE="AI-done").
  3. Issue Searching Logic (Polling):
    • For each configured repository:
      • Construct a GitHub search query string. Example: repo:${owner}/${repo} is:issue is:open label:"${AI_PRIMARY_TAG}" -label:"${AI_EXCLUDE_TAGS_PROCESSING}" -label:"${AI_EXCLUDE_TAGS_DONE}".
      • Use the authenticated Octokit client to execute this search query.
    • Decision Rationale: Polling is chosen for initial simplicity over webhooks, aligning with Sec 2.1.1 of the proposal. Webhooks (Sec 2.1.2) can be a future enhancement for efficiency.
  4. Logging:
    • Log daemon startup, polling attempts (including target repositories).
    • Log the number of relevant issues found in each polling cycle.
    • For each detected issue, log key details (ID, number, title, URL).
  5. Error Handling:
    • Implement robust error handling for API calls (e.g., rate limits, network errors). Log errors using the established logger and ensure the daemon can continue polling or implement a simple retry/backoff.
  6. Output/Next Step Integration:
    • For now, the daemon will log the details of detected issues.
    • In the subsequent issue (Task Queuing), this will be modified to add detected issues as tasks to a message queue.

Acceptance Criteria

  • The daemon script can be run as a Node.js process.
  • It successfully polls the configured GitHub repositories at the specified interval.
  • It correctly identifies and logs issues based on the presence of the primary "AI" tag and the absence of "AI-done" / "AI-processing" tags.
  • Configuration (repositories, interval, tags) is managed via environment variables.
  • Errors during polling are logged gracefully.

Activity

  1. integry commented on May 23, 2025

    @integry
    OwnerAuthor

    Suggested Implementation Snippet (Node.js - src/daemon.js)

    This snippet outlines the core polling logic for the daemon.

    // src/daemon.js
    import 'dotenv/config';
    import { getAuthenticatedOctokit } from './auth/githubAuth.js'; // Assumes this is from Issue 1
    import logger from './utils/logger.js'; // Assumes this is from Issue 1
    
    const GITHUB_REPOS_TO_MONITOR = process.env.GITHUB_REPOS_TO_MONITOR; // comma-separated "owner/repo"
    const POLLING_INTERVAL_MS = parseInt(process.env.POLLING_INTERVAL_MS || '60000', 10);
    const AI_PRIMARY_TAG = process.env.AI_PRIMARY_TAG || 'AI';
    const AI_EXCLUDE_TAGS_PROCESSING = process.env.AI_EXCLUDE_TAGS_PROCESSING || 'AI-processing';
    const AI_EXCLUDE_TAGS_DONE = process.env.AI_EXCLUDE_TAGS_DONE || 'AI-done';
    
    if (!GITHUB_REPOS_TO_MONITOR) {
        logger.error('GITHUB_REPOS_TO_MONITOR environment variable is not set. Exiting.');
        process.exit(1);
    }
    const repos = GITHUB_REPOS_TO_MONITOR.split(',').map(r => r.trim());
    
    async function fetchIssuesForRepo(octokit, repoFullName) {
        const [owner, repo] = repoFullName.split('/');
        if (!owner || !repo) {
            logger.warn({ repo: repoFullName }, 'Invalid repository format. Skipping.');
            return [];
        }
    
        const excludeLabelsQuery = [AI_EXCLUDE_TAGS_PROCESSING, AI_EXCLUDE_TAGS_DONE]
            .map(tag => `-label:"${tag}"`)
            .join(' ');
    
        const query = `repo:${owner}/${repo} is:issue is:open label:"${AI_PRIMARY_TAG}" ${excludeLabelsQuery}`;
        logger.debug({ repo: repoFullName, query }, 'Constructed search query');
    
        try {
            const response = await octokit.request('GET /search/issues', {
                q: query,
            });
            logger.info({ repo: repoFullName, count: response.data.total_count }, `Found ${response.data.total_count} matching issues.`);
            return response.data.items.map(issue => ({
                id: issue.id,
                number: issue.number,
                title: issue.title,
                url: issue.html_url,
                repoOwner: owner,
                repoName: repo,
                labels: issue.labels.map(l => l.name),
            }));
        } catch (error) {
            logger.error({ repo: repoFullName, errMessage: error.message, status: error.status }, 'Error fetching issues');
            if (error.status === 403 && error.message && error.message.includes('rate limit exceeded')) {
                logger.warn('GitHub API rate limit likely exceeded. Consider increasing polling interval.');
            }
            return [];
        }
    }
    
    async function pollForIssues() {
        logger.info('Starting GitHub issue polling cycle...');
        let octokit;
        try {
            octokit = await getAuthenticatedOctokit();
        } catch (authError) {
            logger.error({ err: authError }, 'Failed to get authenticated Octokit instance. Halting polling cycle.');
            return;
        }
    
        const allDetectedIssues = [];
        for (const repoFullName of repos) {
            logger.debug(`Polling repository: ${repoFullName}`);
            const issues = await fetchIssuesForRepo(octokit, repoFullName);
            if (issues.length > 0) {
                issues.forEach(issue => {
                    logger.info({ issueId: issue.id, issueNumber: issue.number, issueTitle: issue.title, issueUrl: issue.url }, 'Detected eligible issue');
                    // Placeholder: In the next stage, this issue will be added to a task queue.
                    // e.g., await taskQueue.add('processIssue', issue);
                    allDetectedIssues.push(issue);
                });
            }
        }
        logger.info(`Polling cycle finished. Total eligible issues detected: ${allDetectedIssues.length}`);
    }
    
    function startDaemon() {
        logger.info({
            repos: GITHUB_REPOS_TO_MONITOR,
            interval: POLLING_INTERVAL_MS,
            primaryTag: AI_PRIMARY_TAG,
            excludeProcessing: AI_EXCLUDE_TAGS_PROCESSING,
            excludeDone: AI_EXCLUDE_TAGS_DONE
        },'GitHub Issue Detection Daemon starting...');
        pollForIssues(); // Initial poll
        setInterval(pollForIssues, POLLING_INTERVAL_MS);
    }
    
    startDaemon();

    Environment Variables Reminder (.env):

    GITHUB_REPOS_TO_MONITOR=integry/gitfix # Replace with your actual repo(s)
    POLLING_INTERVAL_MS=60000
    AI_PRIMARY_TAG=AI
    AI_EXCLUDE_TAGS_PROCESSING=AI-processing
    AI_EXCLUDE_TAGS_DONE=AI-done
    # Inherited from previous issue:
    # GH_APP_ID=...
    # GH_PRIVATE_KEY_PATH=...
    # GH_INSTALLATION_ID=...
    # LOG_LEVEL=info

    This comment provides initial code suggestions. Implementation details may vary.

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