"use strict";
/**
 * End-to-end tests for the `ai-governance discover` subcommand.
 *
 * Exercises the binary the way a customer would — by spawning a real
 * node/tsx process and asserting on exit code + stdout/stderr. This is
 * the customer-code-path probe that satisfies Evidence-First Protocol
 * Rule 3 (real running service, not mocks).
 *
 * @connexum/ai-governance  CLI integration tests
 */
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 node_test_1 = require("node:test");
const assert = __importStar(require("node:assert/strict"));
const node_child_process_1 = require("node:child_process");
const fs = __importStar(require("node:fs"));
const os = __importStar(require("node:os"));
const path = __importStar(require("node:path"));
const crypto = __importStar(require("node:crypto"));
const CLI = path.join(__dirname, 'index.ts');
// `__dirname` is undefined in ESM but the test runner here is CJS-mode tsx.
// Fall back to a resolved path against the repo root if needed.
const RESOLVED_CLI = fs.existsSync(CLI)
    ? CLI
    : path.resolve(process.cwd(), 'src/cli/index.ts');
function runCli(args) {
    const res = (0, node_child_process_1.spawnSync)('npx', ['-y', 'tsx', RESOLVED_CLI, ...args], {
        encoding: 'utf8',
        env: { ...process.env, NODE_OPTIONS: '' },
    });
    return {
        code: res.status ?? -1,
        stdout: res.stdout ?? '',
        stderr: res.stderr ?? '',
    };
}
function makeProject(files) {
    const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-disc-'));
    for (const [rel, content] of Object.entries(files)) {
        const full = path.join(dir, rel);
        fs.mkdirSync(path.dirname(full), { recursive: true });
        fs.writeFileSync(full, content);
    }
    return dir;
}
function writeKeyPem(dir) {
    const { privateKey } = crypto.generateKeyPairSync('ed25519');
    const pem = privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();
    const keyPath = path.join(dir, 'org-private.pem');
    fs.writeFileSync(keyPath, pem);
    return keyPath;
}
(0, node_test_1.describe)('ai-governance discover (real CLI invocation)', () => {
    (0, node_test_1.it)('--help prints usage and exits 0', () => {
        const r = runCli(['discover', '--help']);
        assert.equal(r.code, 0);
        assert.match(r.stdout, /Scan a project for agents/i);
        assert.match(r.stdout, /--root/);
        assert.match(r.stdout, /--org-id/);
        assert.match(r.stdout, /--key/);
    });
    (0, node_test_1.it)('missing --root prints error and exits 2', () => {
        const r = runCli(['discover', '--org-id', 'org-x']);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--root is required/);
    });
    (0, node_test_1.it)('missing --org-id prints error and exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const r = runCli(['discover', '--root', root]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--org-id is required/);
    });
    (0, node_test_1.it)('unknown flag exits 2', () => {
        const r = runCli(['discover', '--root', '/tmp', '--bogus-flag']);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /unknown flag/);
    });
    (0, node_test_1.it)('dry-run with two agents prints a report and exits 0', () => {
        const root = makeProject({
            '.claude/agents/a.md': `---\nname: a\ntools: Bash, Read\n---`,
            '.claude/agents/b.md': `---\nname: b\ntools: WebFetch\n---`,
        });
        const r = runCli(['discover', '--root', root, '--org-id', 'org-x', '--dry-run']);
        assert.equal(r.code, 0, `expected exit 0, got ${r.code}. stderr=${r.stderr}`);
        assert.match(r.stdout, /Found 2 agents/);
        assert.match(r.stdout, /\[DRY-RUN\]/);
        assert.match(r.stdout, /claude-code:a/);
        assert.match(r.stdout, /claude-code:b/);
    });
    (0, node_test_1.it)('non-dry-run without --key exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x',
            '--endpoint', 'https://example.test/api/v1/manifests',
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--key is required/);
    });
    (0, node_test_1.it)('non-dry-run without --endpoint exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const keyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cli-key-'));
        const keyPath = writeKeyPem(keyDir);
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x', '--key', keyPath,
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /--endpoint is required/);
    });
    (0, node_test_1.it)('invalid PEM file exits 2 with structured error', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const badKey = path.join(root, 'bad.pem');
        fs.writeFileSync(badKey, 'not a real PEM');
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x',
            '--key', badKey, '--endpoint', 'https://example.test/api/v1/manifests',
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /invalid PEM private key/);
    });
    (0, node_test_1.it)('missing --key file exits 2', () => {
        const root = makeProject({ '.claude/agents/a.md': `---\nname: a\ntools: Bash\n---` });
        const r = runCli([
            'discover', '--root', root, '--org-id', 'org-x',
            '--key', '/tmp/does-not-exist-' + Date.now(), '--endpoint', 'https://example.test/api/v1/manifests',
        ]);
        assert.equal(r.code, 2);
        assert.match(r.stderr, /cannot read --key/);
    });
    (0, node_test_1.it)('empty project + dry-run prints "Found 0 agents" and exits 0', () => {
        const root = makeProject({ 'README.md': '# empty' });
        const r = runCli(['discover', '--root', root, '--org-id', 'org-x', '--dry-run']);
        assert.equal(r.code, 0);
        assert.match(r.stdout, /Found 0 agents/);
    });
    (0, node_test_1.it)('--max-depth=2 hides deeper agents', () => {
        const root = makeProject({
            'a/b/c/d/agent.md': `---\nname: deep\ntools: Bash\n---`,
        });
        const shallow = runCli([
            'discover', '--root', root, '--org-id', 'org-x', '--dry-run',
            '--max-depth', '2',
        ]);
        assert.equal(shallow.code, 0);
        assert.match(shallow.stdout, /Found 0 agents/);
        const deep = runCli([
            'discover', '--root', root, '--org-id', 'org-x', '--dry-run',
            '--max-depth', '10',
        ]);
        assert.equal(deep.code, 0);
        assert.match(deep.stdout, /Found 1 agent/);
    });
    (0, node_test_1.it)('integrates with existing CLI dispatch (`--help` still works at root)', () => {
        const r = runCli(['--help']);
        assert.equal(r.code, 0);
        assert.match(r.stdout, /ai-governance discover/);
        assert.match(r.stdout, /Scan project \+ push signed manifests/);
    });
});
//# sourceMappingURL=discover.test.js.map