File size: 11,549 Bytes
1244914
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#!/usr/bin/env node

// Handle EPIPE errors gracefully (e.g., when piping to `head` or `jq` that closes early)
process.stdout.on("error", (error: NodeJS.ErrnoException) => {
  if (error.code === "EPIPE") {
    process.exit(0);
  }
  throw error;
});

import * as fs from "fs/promises";
import * as path from "path";
import { fileURLToPath } from "url";
import { parse as parseYaml } from "yaml";
import { exec } from "child_process";
import { promisify } from "util";
import pLimit from "p-limit";
import pino from "pino";
import { TaskStatus, type Task } from "./model.js";
import {
  getContextsFromSources,
  generateCommand,
} from "./command-generator.js";
import { parseCliArgs } from "./parse.js";
import { executeTask, type TaskExecutionResult } from "./task-executor.js";
import { processValidations, type ValidationResult } from "./verification.js";
import { createTempDir, parseCsvAsync } from "./utils.js";

const execAsync = promisify(exec);

export type TaskResult = {
  index: number;
  status: TaskStatus;
  command: string;
  duration: number;
  validationResults: ValidationResult[];
};

// ESM compatibility for __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Create logger instance
 * - Human-readable CLI output by default
 * - Set LOG_JSON=1 for machine-readable JSON output (for piping to jq, log aggregators, etc.)
 */
const logger =
  process.env.LOG_JSON === "1"
    ? pino({
        level: process.env.LOG_LEVEL || "info",
        formatters: {
          level: (label) => ({ level: label }),
        },
        timestamp: pino.stdTimeFunctions.isoTime,
      })
    : pino({
        level: process.env.LOG_LEVEL || "info",
        transport: {
          target: "pino-pretty",
          options: {
            colorize: true,
            translateTime: "HH:MM:ss",
            ignore: "pid,hostname",
            messageFormat: "{msg}",
          },
        },
        formatters: {
          level: (label) => ({ level: label }),
        },
        timestamp: pino.stdTimeFunctions.isoTime,
      });

async function main() {
  // Parse command line arguments
  let args;
  try {
    args = await parseCliArgs(__dirname);
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    logger.error({ error: message }, "Failed to parse CLI arguments");
    process.exit(1);
  }

  const { evalName, evalDir, taskFile } = args;

  // Check if eval directory and task file exist
  try {
    await fs.access(evalDir);
  } catch {
    logger.error({ evalDir }, "Eval directory not found");
    process.exit(1);
  }

  try {
    await fs.access(taskFile);
  } catch {
    logger.error({ evalDir }, "task.yml not found");
    process.exit(1);
  }

  // Read and parse task.yml
  const taskContent = await fs.readFile(taskFile, "utf-8");
  const task: Task = parseYaml(taskContent);

  // Display header
  const displayName = path.relative(__dirname, evalDir) || evalName;

  // Create debug directory with timestamp
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
  const debugDir = path.join(evalDir, "debug", timestamp);
  await fs.mkdir(debugDir, { recursive: true });

  // Create a temp directory for setup commands
  const setupTmpDir = await createTempDir("forge-setup-");

  // Execute before_run commands
  if (task.before_run && task.before_run.length > 0) {
    for (const cmd of task.before_run) {
      try {
        logger.info(
          { dir: setupTmpDir.name, command: cmd },
          "Running setup command",
        );
        // Small delay to allow logger to flush before command output
        await new Promise((resolve) => setTimeout(resolve, 0));
        await execAsync(cmd, {
          cwd: setupTmpDir.name,
        });
      } catch (error) {
        logger.error({ command: cmd }, "Setup command failed");
        process.exit(1);
      }
    }
  }

  // Load data from sources and create cross product
  const sourcesData: Record<string, string>[][] = [];

  for (const source of task.sources) {
    if ("csv" in source) {
      const csvPath = path.join(evalDir, source.csv);
      try {
        await fs.access(csvPath);
      } catch {
        logger.error({ csvPath }, "CSV file not found");
        process.exit(1);
      }

      const csvContent = await fs.readFile(csvPath, "utf-8");
      const csvData = await parseCsvAsync(csvContent, {
        columns: true,
        skip_empty_lines: true,
      });
      sourcesData.push(csvData);
    } else if ("cmd" in source) {
      logger.error("cmd source type not yet implemented");
      process.exit(1);
    } else if ("value" in source) {
      sourcesData.push(source.value);
    }
  }

  // Create cross product of all sources
  if (sourcesData.length === 0) {
    logger.error("No sources configured");
    process.exit(1);
  }

  // Get contexts from sources using pure function
  const data = getContextsFromSources(sourcesData);

  const results: TaskResult[] = [];

  // Get parallelism setting (default to 1 for sequential execution)
  const parallelism = task.parallelism ?? 1;
  const limit = pLimit(parallelism);

  // Execute run command for each data row
  // Create promises for all tasks
  const taskPromises = data.map((row, i) => {
    return limit(async () => {
      // Create a unique temp directory for this task
      const taskTmpDir = await createTempDir(`forge-task-${i + 1}-`);

      // Create a 'task' subdirectory for running commands
      const taskWorkDir = path.join(taskTmpDir.name, 'task');
      await fs.mkdir(taskWorkDir, { recursive: true });

      const logFile = path.join(taskTmpDir.name, `task.log`);

      // Context for command interpolation and validations
      const context = { ...row, dir: taskTmpDir.name };

      // Support both single command and multiple commands
      const commands = Array.isArray(task.run) ? task.run : [task.run];

      // Filter out empty or non-string commands
      const validCommands = commands.filter(cmd => typeof cmd === 'string' && cmd.trim().length > 0);

      // If no valid commands, skip this task
      if (validCommands.length === 0) {
        logger.warn({ task_id: i + 1 }, "No valid commands found, skipping task");
        return {
          index: i + 1,
          status: TaskStatus.Failed,
          command: "No valid commands",
          duration: 0,
          validationResults: [],
        };
      }

      let combinedOutput = "";
      let totalDuration = 0;
      let lastError: string | undefined;
      let hasTimeout = false;
      let hasEarlyExit = false;

      // Log task launch once before executing commands
      logger.info(
        {
          task_id: i + 1,
          total_commands: validCommands.length,
          log: logFile,
          dir: taskTmpDir.name,
          work_dir: taskWorkDir,
          parameters: context,
        },
        "Launching task",
      );

      // Execute commands sequentially
      for (let cmdIdx = 0; cmdIdx < validCommands.length; cmdIdx++) {
        const commandTemplate = validCommands[cmdIdx]!; // Non-null assertion safe after filter

        const command = generateCommand(commandTemplate, context);

        logger.info(
          {
            command,
            task_id: i + 1,
            command_id: cmdIdx + 1,
            total_commands: validCommands.length,
          },
          "Executing command",
        );

        const executionResult = await executeTask(
          command,
          i + 1,
          logFile,
          taskWorkDir, // Use taskWorkDir instead of taskTmpDir.name
          task,
          context,
          cmdIdx > 0, // append if this is not the first command
        );

        totalDuration += executionResult.duration;

        if (executionResult.output) {
          combinedOutput += executionResult.output;
        }

        if (executionResult.earlyExit) {
          hasEarlyExit = true;
        }

        // If execution failed or timed out, stop executing remaining commands
        if (executionResult.error) {
          lastError = executionResult.error;
          hasTimeout = executionResult.isTimeout;

          logger.warn(
            {
              task_id: executionResult.index,
              command: executionResult.command,
              command_id: cmdIdx + 1,
              duration: executionResult.duration,
              error: executionResult.error,
              is_timeout: executionResult.isTimeout,
            },
            executionResult.isTimeout ? "Task timed out" : "Task failed",
          );
          break;
        }
      }

      // If any command failed, return failure result
      if (lastError) {
        const { validationResults } = await processValidations(
          combinedOutput,
          task,
          logger,
          i + 1,
          totalDuration,
          logFile,
          context,
        );

        return {
          index: i + 1,
          status: hasTimeout ? TaskStatus.Timeout : TaskStatus.Failed,
          command: validCommands.length === 1 ? validCommands[0]! : `${validCommands.length} commands`,
          duration: totalDuration,
          validationResults,
        };
      }

      // Run validations on the combined output
      const { validationResults, status: validationStatus } =
        await processValidations(
          combinedOutput,
          task,
          logger,
          i + 1,
          totalDuration,
          logFile,
          context,
        );

      return {
        index: i + 1,
        status:
          validationStatus === "passed"
            ? TaskStatus.Passed
            : TaskStatus.ValidationFailed,
        command: validCommands.length === 1 ? validCommands[0]! : `${validCommands.length} commands`,
        duration: totalDuration,
        validationResults,
      };
    });
  });

  // Wait for all tasks to complete
  const taskResults = await Promise.all(taskPromises);
  results.push(...taskResults);

  // Calculate summary statistics
  const successCount = results.filter(
    (r) => r.status === TaskStatus.Passed,
  ).length;
  const warningCount = results.filter(
    (r) => r.status === TaskStatus.ValidationFailed,
  ).length;
  const timeoutCount = results.filter(
    (r) => r.status === TaskStatus.Timeout,
  ).length;
  const failCount = results.filter(
    (r) => r.status === TaskStatus.Failed,
  ).length;
  const totalDuration = results.reduce((sum, r) => sum + r.duration, 0);

  // Calculate validation statistics
  const totalValidations = results.reduce(
    (sum, r) => sum + r.validationResults.length,
    0,
  );
  const passedValidations = results.reduce(
    (sum, r) => sum + r.validationResults.filter((v) => v.passed).length,
    0,
  );

  // Print summary
  logger.info(
    {
      total: results.length,
      passed: successCount,
      validation_failed: warningCount,
      timeout: timeoutCount,
      failed: failCount,
      total_duration: totalDuration,
      validations: {
        total: totalValidations,
        passed: passedValidations,
        failed: totalValidations - passedValidations,
      },
      dir: setupTmpDir.name,
    },
    "Evaluation completed",
  );

  // Exit with error code if any task failed (excluding timeouts and validation failures)
  if (failCount > 0) {
    process.exit(1);
  }
  
  // Exit successfully - ensures process terminates even with open handles
  process.exit(0);
}

main().catch((error) => {
  logger.error({ error: error.message }, "Fatal error");
  process.exit(1);
});