/**
 * RED-GREEN tests for the manifest push emitter.
 *
 * @connexum/ai-governance  manifest-push-emitter
 */
import { describe, it } from 'node:test';
import * as assert from 'node:assert/strict';
import { ManifestPushEmitter } from './manifest-push-emitter.js';
import { generateOrgKeyPair } from './signed-manifest.js';
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;
describe('manifest push emitter', () => {
    it('happy path: signs + posts + returns receiptId on 2xx', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = recordingTransport([{ status: 201, bodyText: '{"receipt_id":"r_1"}' }]);
        const emitter = new 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');
    });
    it('parses id field as well as receipt_id', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = recordingTransport([{ status: 200, bodyText: '{"id":"r_2"}' }]);
        const emitter = new 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');
    });
    it('4xx is NOT retried — returns immediately with status', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = recordingTransport([
            { status: 400, bodyText: '{"error":"bad signature"}' },
        ]);
        const emitter = new 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');
    });
    it('5xx is retried up to maxRetries + 1 attempts then gives up', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = recordingTransport([
            { status: 503, bodyText: '' },
            { status: 502, bodyText: '' },
            { status: 500, bodyText: '' },
            { status: 504, bodyText: '' },
        ]);
        const emitter = new 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);
    });
    it('5xx then 200 succeeds on the second attempt', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = recordingTransport([
            { status: 503, bodyText: '' },
            { status: 200, bodyText: '{"id":"r_3"}' },
        ]);
        const emitter = new 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');
    });
    it('transport throws are retried like 5xx', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = throwingTransport(2, { status: 201, bodyText: '{"id":"r_4"}' });
        const emitter = new 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);
    });
    it('all attempts throw -> structured error with retry count', async () => {
        const { privateKey } = generateOrgKeyPair();
        const emitter = new 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/);
    });
    it('missing orgId / endpoint throws on construction', () => {
        const { privateKey } = generateOrgKeyPair();
        assert.throws(() => new ManifestPushEmitter({ orgId: '', privateKey, endpoint: 'https://x' }), /orgId is required/);
        assert.throws(() => new ManifestPushEmitter({ orgId: 'org-x', privateKey, endpoint: '' }), /endpoint is required/);
    });
    it('signed body includes the canonical envelope shape', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = recordingTransport([{ status: 201, bodyText: '{}' }]);
        const emitter = new 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);
    });
    it('backoff is called between retries (not on first attempt)', async () => {
        const { privateKey } = generateOrgKeyPair();
        const t = recordingTransport([
            { status: 503, bodyText: '' },
            { status: 503, bodyText: '' },
            { status: 200, bodyText: '{}' },
        ]);
        const sleeps = [];
        const emitter = new 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