"use strict";
/**
 * RED-GREEN tests for the manifest push emitter.
 *
 * @connexum/ai-governance  manifest-push-emitter
 */
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 manifest_push_emitter_1 = require("./manifest-push-emitter");
const signed_manifest_1 = require("./signed-manifest");
const baseManifest = () => ({
    agentId: 'agent-1',
    name: 'A',
    tools: ['Bash'],
    hooks: { preToolUse: true, postToolUse: true, postResponse: true },
});
function recordingTransport(responses) {
    let i = 0;
    const calls = [];
    return {
        calls,
        transport: async (req) => {
            calls.push(req);
            return responses[Math.min(i++, responses.length - 1)];
        },
    };
}
function throwingTransport(times, finalResponse) {
    let calls = 0;
    return {
        get calls() { return calls; },
        transport: async () => {
            calls++;
            if (calls <= times)
                throw new Error(`simulated network failure ${calls}`);
            return finalResponse;
        },
    };
}
const noopSleep = async (_ms) => undefined;
(0, node_test_1.describe)('manifest push emitter', () => {
    (0, node_test_1.it)('happy path: signs + posts + returns receiptId on 2xx', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = recordingTransport([{ status: 201, bodyText: '{"receipt_id":"r_1"}' }]);
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        const result = await emitter.push(baseManifest());
        assert.equal(result.ok, true);
        assert.equal(result.attempts, 1);
        assert.equal(result.receiptId, 'r_1');
        assert.equal(t.calls.length, 1);
        const call = t.calls[0];
        assert.equal(call.method, 'POST');
        assert.equal(call.hostname, 'proxy.my-cc.io');
        assert.equal(call.path, '/api/v1/manifests');
        assert.equal(call.headers['x-connexum-org'], 'org-x');
        assert.equal(call.headers['content-type'], 'application/json');
        const body = JSON.parse(call.body ?? '{}');
        assert.ok(body.signature.length > 0);
        assert.equal(body.payload.orgId, 'org-x');
    });
    (0, node_test_1.it)('parses id field as well as receipt_id', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = recordingTransport([{ status: 200, bodyText: '{"id":"r_2"}' }]);
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        const result = await emitter.push(baseManifest());
        assert.equal(result.receiptId, 'r_2');
    });
    (0, node_test_1.it)('4xx is NOT retried — returns immediately with status', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = recordingTransport([
            { status: 400, bodyText: '{"error":"bad signature"}' },
        ]);
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
            maxRetries: 3,
        });
        const result = await emitter.push(baseManifest());
        assert.equal(result.ok, false);
        assert.equal(result.status, 400);
        assert.equal(result.attempts, 1);
        assert.equal(t.calls.length, 1, '4xx must not be retried');
    });
    (0, node_test_1.it)('5xx is retried up to maxRetries + 1 attempts then gives up', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = recordingTransport([
            { status: 503, bodyText: '' },
            { status: 502, bodyText: '' },
            { status: 500, bodyText: '' },
            { status: 504, bodyText: '' },
        ]);
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
            maxRetries: 3,
        });
        const result = await emitter.push(baseManifest());
        assert.equal(result.ok, false);
        assert.equal(result.attempts, 4);
        assert.equal(t.calls.length, 4);
        assert.equal(result.status, 504);
    });
    (0, node_test_1.it)('5xx then 200 succeeds on the second attempt', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = recordingTransport([
            { status: 503, bodyText: '' },
            { status: 200, bodyText: '{"id":"r_3"}' },
        ]);
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        const result = await emitter.push(baseManifest());
        assert.equal(result.ok, true);
        assert.equal(result.attempts, 2);
        assert.equal(result.receiptId, 'r_3');
    });
    (0, node_test_1.it)('transport throws are retried like 5xx', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = throwingTransport(2, { status: 201, bodyText: '{"id":"r_4"}' });
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        const result = await emitter.push(baseManifest());
        assert.equal(result.ok, true);
        assert.equal(result.attempts, 3);
        assert.equal(t.calls, 3);
    });
    (0, node_test_1.it)('all attempts throw -> structured error with retry count', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: async () => { throw new Error('no network'); },
            sleep: noopSleep,
            maxRetries: 2,
        });
        const result = await emitter.push(baseManifest());
        assert.equal(result.ok, false);
        assert.equal(result.attempts, 3);
        assert.match(result.error ?? '', /no network/);
    });
    (0, node_test_1.it)('missing orgId / endpoint throws on construction', () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        assert.throws(() => new manifest_push_emitter_1.ManifestPushEmitter({ orgId: '', privateKey, endpoint: 'https://x' }), /orgId is required/);
        assert.throws(() => new manifest_push_emitter_1.ManifestPushEmitter({ orgId: 'org-x', privateKey, endpoint: '' }), /endpoint is required/);
    });
    (0, node_test_1.it)('signed body includes the canonical envelope shape', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = recordingTransport([{ status: 201, bodyText: '{}' }]);
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: noopSleep,
        });
        await emitter.push(baseManifest());
        const body = JSON.parse(t.calls[0].body ?? '{}');
        assert.ok(body.payload);
        assert.ok(body.signature);
        assert.equal(body.alg, 'ed25519');
        assert.ok(body.payload.nonce);
        assert.ok(body.payload.issuedAt);
    });
    (0, node_test_1.it)('backoff is called between retries (not on first attempt)', async () => {
        const { privateKey } = (0, signed_manifest_1.generateOrgKeyPair)();
        const t = recordingTransport([
            { status: 503, bodyText: '' },
            { status: 503, bodyText: '' },
            { status: 200, bodyText: '{}' },
        ]);
        const sleeps = [];
        const emitter = new manifest_push_emitter_1.ManifestPushEmitter({
            orgId: 'org-x',
            privateKey,
            endpoint: 'https://proxy.my-cc.io/api/v1/manifests',
            transport: t.transport,
            sleep: async (ms) => { sleeps.push(ms); },
            maxRetries: 3,
            baseBackoffMs: 100,
        });
        await emitter.push(baseManifest());
        // 2 transient failures -> 2 backoffs before the successful 3rd attempt.
        assert.equal(sleeps.length, 2);
        assert.equal(sleeps[0], 100);
        assert.equal(sleeps[1], 200);
    });
});
//# sourceMappingURL=manifest-push-emitter.test.js.map