Skip to content

Backend: Create Asynchronous 'analysis_worker.js' Service #243

Closed

Description

@integry

This task involves creating a new standalone worker service responsible for processing jobs from the 'analysis-queue'.

This worker must:

  1. Be a new runnable script, similar to 'src/worker.js' or 'src/daemon.js'.
  2. Listen to the 'ANALYSIS_QUEUE_NAME' ('analysis-queue').
  3. On receiving a job, it should:
    a. Extract the 'executionId', 'sessionId', and 'correlationId'.
    b. Load the fast analysis model name from the new configuration (see Issue Epic: Claude-Powered GitHub Issue Processor - Stage 3: Task Queue and Worker Infrastructure #3).
    c. Fetch the original prompt from Redis (e.g., 'execution:prompt:session:SESSION_ID').
    d. Fetch the full conversation log from the database ('llm_execution_details' table).
    e. Create a "meta-prompt" using 'generateExecutionAnalysisPrompt' (from 'src/claude/prompts/promptGenerator.js').
    f. Call a new, lightweight LLM function in 'src/claude/claudeService.js' that calls the Anthropic API directly (no Docker/worktree needed).
    g. Save the resulting analysis text to the 'analysis_report' column in the 'llm_executions' table.

Activity

  1. integry commented on Nov 14, 2025

    @integry
    OwnerAuthor

    Suggested Implementation

    1. New file: 'src/analysis_worker.js' (Skeleton)

    import 'dotenv/config';
    import { createWorker, ANALYSIS_QUEUE_NAME } from './queue/taskQueue.js';
    import logger from './utils/logger.js';
    import { db } from './db/postgres.js';
    import { getExecutionAnalysis } from './services/analysisService.js'; // To be created
    import { loadSettings } from './config/configRepoManager.js';
    
    async function processAnalysisJob(job) {
      const { executionId, sessionId, correlationId } = job.data;
      const correlatedLogger = logger.withCorrelation(correlationId);
      correlatedLogger.info({ executionId }, 'Starting execution analysis job...');
    
      try {
        // 1. Load fast analysis model from config
        const settings = await loadSettings();
        const fastModel = settings.analysis_model_fast || 'claude-3-5-haiku-20241022';
    
        // 2. Get analysis (this function will do the heavy lifting)
        const analysisReport = await getExecutionAnalysis({
          executionId,
          sessionId,
          correlationId,
          model: fastModel,
        });
    
        // 3. Save to database
        await db('llm_executions')
          .where({ execution_id: executionId })
          .update({ analysis_report: JSON.stringify(analysisReport) });
    
        correlatedLogger.info({ executionId }, 'Execution analysis complete and saved.');
        return { success: true };
      } catch (error) {
        correlatedLogger.error({ executionId, error: error.message }, 'Execution analysis job failed');
        throw error;
      }
    }
    
    function startAnalysisWorker() {
      logger.info({
        queue: ANALYSIS_QUEUE_NAME,
        concurrency: 2, // Keep analysis low-concurrency
      }, 'Starting Analysis Worker...');
      
      createWorker(ANALYSIS_QUEUE_NAME, processAnalysisJob, { concurrency: 2 });
    }
    
    startAnalysisWorker();

    2. New file: 'src/services/analysisService.js' (Skeleton)

    import Redis from 'ioredis';
    import { db } from '../db/postgres.js';
    import { generateExecutionAnalysisPrompt } from '../claude/prompts/promptGenerator.js';
    import { runLightweightLLMAnalysis } from '../claude/claudeService.js'; // To be created
    import logger from '../utils/logger.js';
    
    const redis = new Redis({
      host: process.env.REDIS_HOST || 'redis',
      port: process.env.REDIS_PORT || 6379,
    });
    
    export async function getExecutionAnalysis({ executionId, sessionId, correlationId, model }) {
      const correlatedLogger = logger.withCorrelation(correlationId);
    
      // 1. Fetch prompt from Redis
      const promptKey = `execution:prompt:session:${sessionId}`;
      const promptData = JSON.parse(await redis.get(promptKey) || '{}');
      const originalPrompt = promptData.prompt || 'Original prompt not found.';
    
      // 2. Fetch conversation log from DB
      const conversationLog = await db('llm_execution_details')
        .where({ execution_id: executionId })
        .orderBy('sequence_number', 'asc');
      
      if (conversationLog.length === 0) {
        correlatedLogger.warn({ executionId }, 'No execution details found for analysis.');
        return { error: 'No execution details found.' };
      }
    
      // 3. Generate the meta-prompt
      // This function needs to be created in src/claude/prompts/promptGenerator.js
      const metaPrompt = generateExecutionAnalysisPrompt(originalPrompt, conversationLog, model);
    
      // 4. Call lightweight LLM service
      const analysisText = await runLightweightLLMAnalysis(metaPrompt, model, correlationId);
      
      // 5. TODO: Parse analysisText into structured JSON if desired
      const analysisReport = {
        generatedAt: new Date().toISOString(),
        modelUsed: model,
        report: analysisText, // Store raw text for now
      };
    
      return analysisReport;
    }

    3. New function in 'src/claude/claudeService.js'

    // ... existing imports
    // Import Anthropic SDK
    // import Anthropic from '@anthropic-ai/sdk';
    // const anthropic = new Anthropic(); // API key from process.env.ANTHROPIC_API_KEY
    
    export async function runLightweightLLMAnalysis(prompt, model, correlationId) {
      const correlatedLogger = logger.withCorrelation(correlationId);
      correlatedLogger.info({ model }, 'Running lightweight LLM analysis...');
      
      // This is a placeholder. Implement with the actual LLM SDK (e.g., Anthropic's)
      // This call does NOT use Docker.
      
      // Example (needs Anthropic SDK installed):
      /*
      try {
        const response = await anthropic.messages.create({
          model: model,
          max_tokens: 4096,
          messages: [{ role: 'user', content: prompt }],
        });
        return response.content[0].text;
      } catch (error) {
        correlatedLogger.error({ error: error.message, model }, 'Lightweight LLM analysis failed');
        throw error;
      }
      */
      
      // Placeholder implementation:
      await new Promise(resolve => setTimeout(resolve, 1000));
      return `This is a placeholder analysis report for model '${model}'.\n\n- Efficiency: Good\n- Prompt Improvement: None needed.`;
    }
  2. added and removed on Nov 14, 2025
  3. propr-dev commented on Nov 14, 2025

    @propr-dev
    Contributor

    🤖 AI processing has started for this issue using claude-sonnet-4-5-20250929 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Model: claude-sonnet-4-5-20250929
    • Branch: ai-fix/243-backend-create-asynchrono-20251114-1448-claude-sonnet-4-5-20250929-kjt
    • Base Branch: main
    • Worktree: issue-243-20251114-1448-claude-sonnet-4-5-20250929-kjt
  4. added a commit that references this issue on Nov 14, 2025
  5. added a commit that references this issue on Nov 14, 2025
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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions