"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const path = __importStar(require("path"));
// Read-only diagnostics that should work without external creds.
// CLI-02 + CLI-03 + CLI-04 consolidated.
const SPECS = [
    // CLI-04 — phase1-check (KNOWN BUG: hangs >35s; see Phase 5 finding P2-BUG-01)
    { args: ['phase1-check'], label: 'phase1-check', classify: 'gap', reason: 'KNOWN BUG: hangs; needs Phase 5 fix' },
    // Catalog
    { args: ['catalog', 'list'], label: 'catalog list', classify: 'pass' },
    { args: ['catalog', 'doctor'], label: 'catalog doctor', classify: 'graceful', reason: 'may report stale test entries (P3 known)' },
    // Listings (no external deps — pure file reads)
    { args: ['agents', 'list'], label: 'agents list', classify: 'pass' },
    { args: ['squads', 'list'], label: 'squads list', classify: 'pass' },
    { args: ['skills', 'list'], label: 'skills list', classify: 'pass' },
    // Status surfaces
    { args: ['models', 'status'], label: 'models status', classify: 'pass' },
    { args: ['memory', 'status'], label: 'memory status', classify: 'pass' },
    { args: ['memory', 'provider-list'], label: 'memory provider-list', classify: 'pass' },
    { args: ['governance', 'status'], label: 'governance status', classify: 'pass' },
    { args: ['governance', 'audit'], label: 'governance audit', classify: 'pass' },
    { args: ['mcp', 'status'], label: 'mcp status', classify: 'pass' },
    // Aggregate doctors
    { args: ['system', 'doctor'], label: 'system doctor', classify: 'graceful', reason: 'may warn about optional CLIs (codex/gemini)' },
    { args: ['system', 'status'], label: 'system status', classify: 'graceful' },
    { args: ['media', 'doctor'], label: 'media doctor', classify: 'graceful' },
    { args: ['media', 'route-status'], label: 'media route-status', classify: 'pass' },
    { args: ['enterprise'], label: 'enterprise', classify: 'graceful', reason: 'aggregate doctor; degrades gracefully on missing state' },
    // Orchestration
    { args: ['orchestration', 'contract'], label: 'orchestration contract', classify: 'pass' },
    { args: ['orchestration', 'snapshot'], label: 'orchestration snapshot', classify: 'pass' },
    // Swarm — consensus-test does not call LLM (uses deterministic stubs)
    { args: ['swarm', 'consensus-test'], label: 'swarm consensus-test', classify: 'graceful' },
    // Live commands — recorded as GAP (Phase 4)
    { args: ['system', 'doctor-world'], label: 'system doctor-world', classify: 'gap', reason: 'requires LLM' },
    { args: ['benchmark', 'report'], label: 'benchmark report', classify: 'gap', reason: 'requires prior benchmark runs' }
];
function run(args, timeoutMs) {
    return new Promise((resolve) => {
        const t0 = Date.now();
        const cliPath = path.join(process.cwd(), 'dist', 'index.js');
        const child = (0, child_process_1.spawn)('node', [cliPath, ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
        let stdout = '';
        let stderr = '';
        child.stdout?.on('data', (d) => { stdout += d.toString(); });
        child.stderr?.on('data', (d) => { stderr += d.toString(); });
        const killer = setTimeout(() => child.kill('SIGKILL'), timeoutMs);
        child.on('exit', (code) => {
            clearTimeout(killer);
            resolve({ code, elapsed: Date.now() - t0, stdout: stdout.slice(0, 500), stderr: stderr.slice(0, 300) });
        });
    });
}
async function main() {
    const results = [];
    for (const spec of SPECS) {
        // Short timeout for gap commands (already known broken/deferred) — saves test:all budget.
        // Non-gap commands return in ~2-4s standalone, but under the full test:all run the box
        // is loaded by lingering daemons/queue-runners from prior tests (esp. on WSL), so cold
        // node starts can transiently blow a tight budget. 30s margin + one retry on SIGKILL
        // (code===null) absorbs that contention without masking a genuinely broken command —
        // a real failure trips both attempts.
        const timeoutMs = spec.classify === 'gap' ? 2000 : 30000;
        let r = await run(spec.args, timeoutMs);
        if (r.code === null && spec.classify !== 'gap') {
            r = await run(spec.args, timeoutMs);
        }
        results.push({ spec, ...r });
    }
    const failures = [];
    const passCount = { pass: 0, graceful: 0, gap: 0 };
    for (const r of results) {
        const { spec, code, elapsed, stderr } = r;
        if (spec.classify === 'pass') {
            if (code !== 0) {
                failures.push(`${spec.label} → exit=${code} (expected 0)${stderr ? ` stderr=${stderr.slice(0, 120)}` : ''}`);
            }
            else {
                passCount.pass++;
            }
        }
        else if (spec.classify === 'graceful') {
            // Accept 0 or 1; flag if it crashed (null code = killed; -1/2+ = abnormal)
            if (code === 0 || code === 1) {
                passCount.graceful++;
            }
            else {
                failures.push(`${spec.label} → crash exit=${code}${stderr ? ` stderr=${stderr.slice(0, 120)}` : ''}`);
            }
        }
        else {
            // gap: don't assert, just log
            passCount.gap++;
        }
        void elapsed;
    }
    if (failures.length > 0) {
        throw new Error(`DIAGNOSTICS_FAILURES (${failures.length}):\n${failures.join('\n')}`);
    }
    console.log(`TEST_CLI_DIAGNOSTICS_OK (pass=${passCount.pass}, graceful=${passCount.graceful}, gap=${passCount.gap}, total=${results.length})`);
}
main().catch((err) => {
    console.error('TEST_CLI_DIAGNOSTICS_FAIL:', err?.message || err);
    process.exit(1);
});
