All files / agent/src enhancedJobExecutor.ts

91.22% Statements 291/319
90.16% Branches 55/61
85.71% Functions 6/7
91.22% Lines 291/319

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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 3201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 81x 81x 81x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 8x 8x 9x 9x 9x 9x 9x 9x 1x 1x 1x 7x 7x 9x 9x 9x 9x 9x 9x               9x 7x 7x 7x 5x 5x 7x 2x 2x 7x 7x 7x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 5x 5x 7x 7x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 3x 3x 3x 3x 7x 7x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 31x 31x 31x 31x 9x 13x 13x 9x 9x 9x                             7x 7x 9x 9x 3x 3x 3x 3x     3x 7x 7x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x  
/**
 * Enhanced Job Executor
 *
 * Orchestrates the full enhanced pipeline with recipe awareness:
 *   1. Acceptance check (should we accept this job?)
 *   2. Resource governance check (do we have resources?)
 *   3. Recipe detection (what kind of project is this?)
 *   4. Recipe application (merge recipe config into job)
 *   5. Executor selection (Docker vs Native)
 *   6. Cache setup (mount cache volumes)
 *   7. Lifecycle execution (setup -> build -> teardown)
 *   8. Cache save (update metadata)
 *   9. Result reporting
 *
 * This module does NOT modify the existing JobExecutor. It wraps
 * the new subsystems (RecipeRegistry, CacheManager, AcceptanceChecker,
 * ResourceGovernor, ExecutorFactory, LifecycleExecutor) into a single
 * cohesive pipeline.
 */
 
import { RecipeRegistry } from './recipes/recipeRegistry.js';
import { Recipe, RecipeCacheConfig } from './recipes/types.js';
import { CacheManager, CacheVolumeMount } from './cacheManager.js';
import { AcceptanceChecker, JobCandidate } from './acceptanceChecker.js';
import { ResourceGovernor, ResourceSnapshot } from './resourceGovernor.js';
import { ExecutorFactory } from './executors/executorFactory.js';
import { LifecycleExecutor, LifecycleResult } from './lifecycleExecutor.js';
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
export interface EnhancedJobRequest {
  id: string;
  repository: string;
  buildCommand: string;
  dockerImage?: string;
  environment?: Record<string, string>;
  workDir: string;
  artifacts?: string[];
  /** Optional recipe name override (skip auto-detection). */
  recipe?: string;
  /** Per-job execution mode override. */
  executionMode?: 'docker' | 'native' | 'auto';
}
 
export interface EnhancedJobCallbacks {
  onProgress?: (percent: number, stage: string) => void;
  onLog?: (log: string) => void;
}
 
export interface EnhancedExecutionResult {
  success: boolean;
  exitCode: number;
  logs: string;
  artifacts: string[];
  durationMs: number;
  /** Name of the recipe that was applied (if any). */
  recipe?: string;
  cacheHit: boolean;
  executionMode: 'docker' | 'native';
  lifecycleResults?: {
    setupResults: any[];
    teardownResults: any[];
  };
  /** Present when the job was rejected before execution. */
  rejection?: { reason: string };
}
 
export interface EnhancedJobExecutorConfig {
  executionMode: 'docker' | 'native' | 'auto';
  dockerAvailable: boolean;
}
 
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
 
/**
 * Collect resource snapshot. Callers may provide an override (e.g. in tests).
 * The default produces a "healthy" snapshot.
 */
export type ResourceSnapshotProvider = () => ResourceSnapshot;
 
const defaultSnapshotProvider: ResourceSnapshotProvider = () => ({
  cpuPercent: 10,
  memoryPercent: 30,
  diskFreeGB: 50,
  activeJobs: 0,
});
 
// ---------------------------------------------------------------------------
// EnhancedJobExecutor
// ---------------------------------------------------------------------------
 
export class EnhancedJobExecutor {
  private lifecycleExecutor: LifecycleExecutor;
  private snapshotProvider: ResourceSnapshotProvider;
 
  constructor(
    private recipeRegistry: RecipeRegistry,
    private cacheManager: CacheManager,
    private acceptanceChecker: AcceptanceChecker,
    private resourceGovernor: ResourceGovernor,
    private config: EnhancedJobExecutorConfig,
    snapshotProvider?: ResourceSnapshotProvider,
  ) {
    this.lifecycleExecutor = new LifecycleExecutor();
    this.snapshotProvider = snapshotProvider ?? defaultSnapshotProvider;
  }
 
  // -----------------------------------------------------------------------
  // Public API
  // -----------------------------------------------------------------------
 
  async executeJob(
    job: EnhancedJobRequest,
    callbacks?: EnhancedJobCallbacks,
  ): Promise<EnhancedExecutionResult> {
    const startTime = Date.now();
    const allLogs: string[] = [];
 
    const log = (msg: string) => {
      allLogs.push(msg);
      callbacks?.onLog?.(msg);
    };
 
    // ---- Step 1: Acceptance check ----
    callbacks?.onProgress?.(5, 'acceptance-check');
    log('[enhanced] Checking acceptance rules...');
 
    const recipeName = job.recipe ?? undefined;
    const candidate: JobCandidate = {
      recipe: recipeName,
      repository: job.repository,
      requiresDocker: (job.executionMode ?? this.config.executionMode) === 'docker',
    };
 
    const acceptance = this.acceptanceChecker.shouldAccept(candidate);
    if (!acceptance.accepted) {
      log(`[enhanced] Job rejected by acceptance checker: ${acceptance.reason}`);
      return this.rejectionResult(acceptance.reason!, startTime, allLogs);
    }
 
    // ---- Step 2: Resource governance check ----
    callbacks?.onProgress?.(10, 'resource-check');
    log('[enhanced] Checking resource availability...');
 
    const snapshot = this.snapshotProvider();
    const resourceDecision = this.resourceGovernor.canAcceptJob(snapshot);
    if (!resourceDecision.allowed) {
      log(`[enhanced] Job rejected by resource governor: ${resourceDecision.reason}`);
      return this.rejectionResult(resourceDecision.reason!, startTime, allLogs);
    }
 
    // ---- Step 3: Recipe detection ----
    callbacks?.onProgress?.(15, 'recipe-detection');
    log('[enhanced] Detecting recipe...');
 
    let recipe: Recipe | undefined;
 
    if (job.recipe) {
      // Explicit recipe override
      recipe = this.recipeRegistry.get(job.recipe);
      if (recipe) {
        log(`[enhanced] Using explicit recipe: ${recipe.name}`);
      } else {
        log(`[enhanced] Explicit recipe "${job.recipe}" not found, proceeding without recipe`);
      }
    } else {
      // Auto-detect
      const matches = await this.recipeRegistry.detectRecipe(job.workDir);
      if (matches.length > 0) {
        recipe = matches[0].recipe;
        log(`[enhanced] Auto-detected recipe: ${recipe.name} (confidence: ${matches[0].confidence})`);
      } else {
        log('[enhanced] No recipe detected, using job defaults');
      }
    }
 
    // ---- Step 4: Apply recipe overrides ----
    callbacks?.onProgress?.(20, 'recipe-apply');
 
    const effectiveDockerImage = recipe?.dockerImage ?? job.dockerImage;
    const effectiveEnv: Record<string, string> = {
      ...(recipe?.environment ?? {}),
      ...(job.environment ?? {}),
    };
    const effectiveBuildCommand = job.buildCommand || recipe?.defaultBuildCommand || 'echo "No build command"';
    const setupSteps = recipe?.setup ?? [];
    const teardownSteps = recipe?.teardown ?? [];
    const effectiveArtifacts = job.artifacts ?? recipe?.artifacts?.paths ?? [];
    const effectiveMode = job.executionMode ?? recipe?.executionMode ?? this.config.executionMode;
 
    if (recipe) {
      log(`[enhanced] Recipe applied: dockerImage=${effectiveDockerImage}, env keys=[${Object.keys(effectiveEnv).join(',')}]`);
    }
 
    // ---- Step 5: Executor selection ----
    callbacks?.onProgress?.(25, 'executor-selection');
 
    const executor = ExecutorFactory.create({
      mode: effectiveMode,
      dockerAvailable: this.config.dockerAvailable,
      jobRequirements: {
        requiredOS: recipe?.requiredOS,
        executionMode: effectiveMode,
      },
    });
    const executionMode = executor.type;
 
    log(`[enhanced] Selected executor: ${executionMode}`);
 
    // ---- Step 6: Cache setup ----
    callbacks?.onProgress?.(30, 'cache-setup');
    let cacheMounts: CacheVolumeMount[] = [];
    let cacheHit = false;
 
    if (recipe?.cache) {
      log('[enhanced] Setting up cache volumes...');
      cacheMounts = this.cacheManager.generateVolumeMounts(recipe.cache);
      // A cache "hit" means we already have entries for these paths
      cacheHit = cacheMounts.length > 0;
      log(`[enhanced] Generated ${cacheMounts.length} cache volume mounts`);
    }
 
    // ---- Step 7: Lifecycle execution ----
    callbacks?.onProgress?.(35, 'lifecycle-execution');
    log('[enhanced] Starting lifecycle execution...');
 
    let lifecycleResult: LifecycleResult;
 
    try {
      lifecycleResult = await this.lifecycleExecutor.execute(
        setupSteps,
        effectiveBuildCommand,
        teardownSteps,
        {
          workDir: job.workDir,
          environment: effectiveEnv,
          onProgress: (phase, step, progress) => {
            // Map lifecycle progress (0-100) into the 35-95 range
            const mappedProgress = 35 + Math.round(progress * 0.6);
            callbacks?.onProgress?.(mappedProgress, `${phase}:${step}`);
          },
          onLog: (_phase, _step, logLine) => {
            log(logLine);
          },
        },
      );
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error);
      log(`[enhanced] Lifecycle execution error: ${errorMsg}`);
      return {
        success: false,
        exitCode: 1,
        logs: allLogs.join('\n'),
        artifacts: [],
        durationMs: Date.now() - startTime,
        recipe: recipe?.name,
        cacheHit,
        executionMode,
        rejection: undefined,
      };
    }
 
    // ---- Step 8: Cache save ----
    callbacks?.onProgress?.(96, 'cache-save');
    if (recipe?.cache) {
      log('[enhanced] Saving cache metadata...');
      try {
        await this.cacheManager.saveMetadata();
      } catch (error) {
        log(`[enhanced] Cache save warning: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
 
    // ---- Step 9: Result reporting ----
    callbacks?.onProgress?.(100, 'complete');
    const success = lifecycleResult.overallSuccess;
    log(`[enhanced] Job ${job.id} ${success ? 'completed successfully' : 'failed'} (duration: ${lifecycleResult.totalDurationMs}ms)`);
 
    return {
      success,
      exitCode: lifecycleResult.executeResult.exitCode,
      logs: allLogs.join('\n'),
      artifacts: effectiveArtifacts,
      durationMs: Date.now() - startTime,
      recipe: recipe?.name,
      cacheHit,
      executionMode,
      lifecycleResults: {
        setupResults: lifecycleResult.setupResults,
        teardownResults: lifecycleResult.teardownResults,
      },
    };
  }
 
  // -----------------------------------------------------------------------
  // Private helpers
  // -----------------------------------------------------------------------
 
  private rejectionResult(
    reason: string,
    startTime: number,
    logs: string[],
  ): EnhancedExecutionResult {
    return {
      success: false,
      exitCode: -1,
      logs: logs.join('\n'),
      artifacts: [],
      durationMs: Date.now() - startTime,
      cacheHit: false,
      executionMode: 'docker',
      rejection: { reason },
    };
  }
}