// engine/sandbox/runner-docker.ts — Docker CI fallback sandbox runner (SPEC-742)
import { spawn } from 'node:child_process';
import { sanitizeEnv } from './env-sanitizer.js';
/** Docker image used for sandboxed execution. */
const DEFAULT_IMAGE = 'node:20-slim';
/**
 * Run a command inside a Docker container on CI hosts.
 * Restrictions:
 *   - Network disabled by default (--network=none)
 *   - Project root bind-mounted read-write
 *   - LD_PRELOAD / DYLD_* stripped from env passed to container
 *   - Container is removed after execution (--rm)
 */
export async function runWithDocker(command, args, options) {
    const { projectRoot, network } = options;
    const startMs = Date.now();
    const sanitized = sanitizeEnv(process.env);
    // Build env flags for Docker
    const envFlags = [];
    for (const [key, value] of Object.entries(sanitized)) {
        envFlags.push('-e', `${key}=${value}`);
    }
    const networkFlag = network === 'unrestricted' ? ['--network=bridge'] : ['--network=none'];
    const dockerArgs = [
        'run',
        '--rm',
        ...networkFlag,
        '-v',
        `${projectRoot}:${projectRoot}`,
        '-w',
        projectRoot,
        ...envFlags,
        DEFAULT_IMAGE,
        command,
        ...args,
    ];
    return new Promise((resolve) => {
        let stdout = '';
        let stderr = '';
        const child = spawn('docker', dockerArgs, {
            stdio: ['pipe', 'pipe', 'pipe'],
        });
        child.stdout.on('data', (chunk) => {
            stdout += chunk.toString();
        });
        child.stderr.on('data', (chunk) => {
            stderr += chunk.toString();
        });
        child.on('close', (code) => {
            resolve({
                exitCode: code ?? 1,
                stdout,
                stderr,
                durationMs: Date.now() - startMs,
                runner: 'docker',
            });
        });
        child.on('error', (err) => {
            resolve({
                exitCode: 1,
                stdout,
                stderr: stderr + '\n' + err.message,
                durationMs: Date.now() - startMs,
                runner: 'docker',
            });
        });
    });
}
//# sourceMappingURL=runner-docker.js.map