// engine/qa-gate.ts — SPEC-642
import { spawnSync } from 'node:child_process';
const TIMEOUT_MS = 120_000;
export function extractCoverageThreshold(spec) {
    const text = [spec.title, ...spec.tags].join(' ');
    const match = /coverage\s*[>=]+\s*(\d+)%/i.exec(text);
    if (!match?.[1]) {
        return null;
    }
    return parseInt(match[1], 10);
}
function runCheck(name, command, args, cwd) {
    const start = Date.now();
    const result = spawnSync(command, args, {
        cwd,
        timeout: TIMEOUT_MS,
        encoding: 'utf-8',
        maxBuffer: 2 * 1024 * 1024,
    });
    const durationMs = Date.now() - start;
    const passed = result.status === 0 && !result.error;
    const output = [result.stdout, result.stderr].join('\n').trim().slice(0, 2000);
    return { name, passed, output, durationMs };
}
export function runQaGate(spec, projectPath) {
    const coverageThreshold = extractCoverageThreshold(spec);
    const checks = [];
    checks.push(runCheck('typecheck', 'pnpm', ['typecheck'], projectPath));
    if (coverageThreshold === null) {
        checks.push(runCheck('test', 'pnpm', ['test'], projectPath));
    }
    else {
        checks.push(runCheck('test-coverage', 'pnpm', ['test:coverage'], projectPath));
    }
    const passed = checks.every((c) => c.passed);
    return Promise.resolve({
        specId: spec.id,
        passed,
        checks,
        ranAt: new Date().toISOString(),
        coverageThreshold,
    });
}
//# sourceMappingURL=qa-gate.js.map