"use strict";
/**
 * test_process_sandbox.ts — Story 15.1 (v1.5, research-track)
 *
 * Unit-tests the ProcessSandbox flag construction and Node-version
 * downgrade behaviour without actually spawning anything. The wrapper's
 * value is in the argv it builds; running real Node sub-processes is
 * left to v1.6 integration tests once the wrapper is wired into a
 * production site.
 */
Object.defineProperty(exports, "__esModule", { value: true });
const ProcessSandbox_1 = require("./orchestrator/ProcessSandbox");
function assertTrue(cond, label) {
    if (!cond)
        throw new Error(`ASSERT_FAILED[${label}]`);
}
function arrEq(a, b) {
    if (a.length !== b.length)
        return false;
    for (let i = 0; i < a.length; i++)
        if (a[i] !== b[i])
            return false;
    return true;
}
// ── Scenario 1: Node 20 → permission flags injected ────────────────────
{
    const sb = new ProcessSandbox_1.ProcessSandbox({
        nodeMajor: 20,
        allowFsRead: ['/tmp', '/repo'],
        allowFsWrite: ['/repo/.artifacts'],
    });
    assertTrue(sb.supportsEnforcement(), '[15.1] Node 20 supports enforcement');
    const flags = sb.buildPermissionFlags();
    assertTrue(arrEq(flags, ['--permission', '--allow-fs-read=/tmp', '--allow-fs-read=/repo', '--allow-fs-write=/repo/.artifacts']), `[15.1] flags ordered correctly (got ${JSON.stringify(flags)})`);
    console.log('[15.1] Node 20 enforcement flags ✓');
}
// ── Scenario 2: Node 18 → no enforcement, empty flag list ─────────────
{
    const sb = new ProcessSandbox_1.ProcessSandbox({ nodeMajor: 18, allowFsRead: ['/tmp'] });
    assertTrue(!sb.supportsEnforcement(), '[15.1] Node 18 does not support enforcement');
    assertTrue(arrEq(sb.buildPermissionFlags(), []), '[15.1] Node 18 → empty flags');
    console.log('[15.1] Node 18 downgrades gracefully ✓');
}
// ── Scenario 3: capability toggles add their flags ─────────────────────
{
    const sb = new ProcessSandbox_1.ProcessSandbox({ nodeMajor: 22, allowChildProcess: true, allowWorker: true });
    const flags = sb.buildPermissionFlags();
    assertTrue(flags.includes('--allow-child-process'), '[15.1] allowChildProcess adds flag');
    assertTrue(flags.includes('--allow-worker'), '[15.1] allowWorker adds flag');
    assertTrue(!flags.includes('--allow-wasi'), '[15.1] absent options stay absent');
    console.log('[15.1] capability toggles correct ✓');
}
// ── Scenario 4: spawn injects flags only for node binaries ────────────
async function scenarioSpawn() {
    let lastCommand = '';
    let lastArgs = [];
    const fakeSpawn = ((command, args) => {
        lastCommand = command;
        lastArgs = args;
        const stub = {
            stdout: { on: (_, _cb) => { } },
            stderr: { on: (_, _cb) => { } },
            on: (event, cb) => {
                if (event === 'close')
                    setTimeout(() => cb(0, null), 0);
            },
        };
        return stub;
    });
    const sb = new ProcessSandbox_1.ProcessSandbox({ nodeMajor: 20, allowFsRead: ['/repo'], spawnImpl: fakeSpawn });
    const r1 = await sb.spawn('node', ['build.js']);
    assertTrue(r1.enforced, '[15.1] node command is enforced');
    assertTrue(lastCommand === 'node', '[15.1] node command preserved');
    assertTrue(arrEq(lastArgs, ['--permission', '--allow-fs-read=/repo', 'build.js']), `[15.1] permission flags inserted before user argv (got ${JSON.stringify(lastArgs)})`);
    assertTrue(r1.code === 0 && r1.signal === null, '[15.1] result envelope normal');
    console.log('[15.1] spawn(node) injects permission flags ✓');
    const r2 = await sb.spawn('git', ['status']);
    assertTrue(!r2.enforced, '[15.1] non-node command not enforced');
    assertTrue(lastCommand === 'git', '[15.1] git command preserved');
    assertTrue(arrEq(lastArgs, ['status']), '[15.1] git argv unchanged');
    console.log('[15.1] spawn(git) is plain pass-through ✓');
}
scenarioSpawn()
    .then(() => { console.log('TEST_PROCESS_SANDBOX_OK'); })
    .catch((err) => {
    console.error('[process-sandbox] FAILED:', err instanceof Error ? err.message : err);
    process.exit(1);
});
