All files / agent test-job-execution.ts

0% Statements 0/138
0% Branches 0/1
0% Functions 0/1
0% Lines 0/138

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139                                                                                                                                                                                                                                                                                     
/**
 * Test Script for MVP.4.2.2 - Job Status Updates
 *
 * This script tests the job execution flow with REST API status updates.
 * It simulates what happens when an agent receives a job assignment.
 */

import { BuildHiveAgent } from './src/agent.js';
import type { JobSubmissionRequest } from './src/types.js';
import { readFileSync } from 'fs';
import { homedir } from 'os';
import { join } from 'path';

async function testJobExecution() {
  console.log('='.repeat(60));
  console.log('BuildHive MVP.4.2.2 - Job Status Updates Test');
  console.log('='.repeat(60));
  console.log();

  try {
    // Load agent configuration
    const configPath = join(homedir(), '.buildhive', 'buildhive-agent.json');
    console.log(`📁 Loading config from: ${configPath}`);

    const config = JSON.parse(readFileSync(configPath, 'utf-8'));
    console.log(`✅ Config loaded successfully`);
    console.log(`   Platform URL: ${config.platformUrl}`);
    console.log(`   Agent ID: ${config.agentId}`);
    console.log();

    // Create agent instance
    console.log('🤖 Creating BuildHive agent...');
    const agent = await BuildHiveAgent.create(config);
    console.log('✅ Agent created successfully');
    console.log();

    // Create a test job
    const testJob: JobSubmissionRequest = {
      externalId: `test-job-${Date.now()}`,
      source: 'MANUAL',
      repository: 'buildhive/test',
      branch: 'main',
      commitSha: 'abc123def456',
      jobType: 'test-build',
      dockerImage: 'alpine:latest',
      buildCommand: [
        'echo "=== BuildHive Test Job ==="',
        'echo "Starting execution..."',
        'sleep 2',
        'echo "Step 1: Downloading dependencies..."',
        'sleep 2',
        'echo "Step 2: Running build..."',
        'sleep 2',
        'echo "Step 3: Running tests..."',
        'sleep 2',
        'echo "✅ Build completed successfully!"',
        'echo "Total files built: 42"',
        'echo "Test results: 10/10 passed"'
      ].join(' && '),
      environment: {
        TEST_ENV: 'mvp-4.2.2',
        NODE_ENV: 'test'
      },
      estimatedDuration: 10
    };

    console.log('📋 Test Job Configuration:');
    console.log(`   External ID: ${testJob.externalId}`);
    console.log(`   Repository: ${testJob.repository}`);
    console.log(`   Docker Image: ${testJob.dockerImage}`);
    console.log(`   Estimated Duration: ${testJob.estimatedDuration}s`);
    console.log();

    console.log('🚀 Starting job execution...');
    console.log('   This will test:');
    console.log('   ✓ Job status update to RUNNING');
    console.log('   ✓ Real-time log streaming via REST API');
    console.log('   ✓ Progress updates');
    console.log('   ✓ Job completion with exitCode and duration');
    console.log();

    const startTime = Date.now();

    // Execute the job
    const result = await agent.executeJob(testJob);

    const duration = Math.floor((Date.now() - startTime) / 1000);

    console.log();
    console.log('='.repeat(60));
    console.log('📊 Job Execution Results');
    console.log('='.repeat(60));
    console.log(`   Status: ${result.status}`);
    console.log(`   Exit Code: ${result.exitCode}`);
    console.log(`   Duration: ${duration}s`);
    console.log(`   Artifacts: ${result.artifactUrls?.length || 0}`);

    if (result.status === 'FAILED') {
      console.log(`   Error: ${result.errorMessage}`);
    }

    console.log();
    console.log('📝 Logs Preview:');
    console.log('-'.repeat(60));
    const logLines = (result.logs || '').split('\n');
    logLines.slice(0, 20).forEach(line => console.log(`   ${line}`));
    if (logLines.length > 20) {
      console.log(`   ... (${logLines.length - 20} more lines)`);
    }
    console.log();

    console.log('='.repeat(60));
    console.log('✅ Test Complete!');
    console.log('='.repeat(60));
    console.log();
    console.log('📍 Next Steps:');
    console.log('   1. Check server logs for job status updates');
    console.log('   2. Query database to verify job status progression');
    console.log('   3. Check job logs in database match the output above');
    console.log();
    console.log(`   Query job in database:`);
    console.log(`   SELECT id, status, exitCode, actualDuration FROM "BuildJob" WHERE "externalId" = '${testJob.externalId}';`);
    console.log();

    process.exit(result.status === 'COMPLETED' ? 0 : 1);

  } catch (error) {
    console.error();
    console.error('❌ Test Failed');
    console.error('='.repeat(60));
    console.error(error);
    console.error();
    process.exit(1);
  }
}

// Run the test
testJobExecution();