Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
/**
* v0.35.0.0 — gateway.rerank() HTTP path tests.
*
* Drives the public `rerank()` function with a stubbed `_rerankTransport`
* (the canonical test seam — same pattern as `__setEmbedTransportForTests`).
*
* Pins:
* - Request URL is `${recipe.base_url_default}/rerank` — i.e.
* `https://api.voyageai.com/v1/rerank`, NOT `/v1/v1/…`
* (CDX1-F2 regression).
* - Request body shape: `{model, query, documents, top_n?}`.
* - Bearer auth header from `applyResolveAuth` ↔ VOYAGE_API_KEY.
* - Response parsing: `{results: [{index, relevance_score}]}` →
* `RerankResult[]` with `{index, relevanceScore}`.
* - Error classification: 401/403 → auth, 429 → rate_limit, 5xx → network,
* other 4xx → unknown, no HTTP response (fetch reject) → unreachable; the
* timeout path is pinned on the real wire in
* test/rerank-failure-reason.serial.test.ts.
* - Pre-flight payload guard: body over `max_payload_bytes` throws
* payload_too_large BEFORE any HTTP call (no transport invocation).
* - Empty documents → empty result, no HTTP call.
* - Model allowlist enforcement (CDX2-F11): `assertTouchpoint` doesn't
* enforce allowlists for openai-compatible recipes; rerank() does the
* check directly.
*/
import { describe, test, expect, afterEach, beforeEach } from 'bun:test';
import {
configureGateway,
resetGateway,
rerank,
RerankError,
__setRerankTransportForTests,
} from '../../src/core/ai/gateway.ts';
function configureVoyage(model: string = 'voyage:rerank-2.5'): void {
configureGateway({
reranker_model: model,
env: { VOYAGE_API_KEY: 'sk-test-zerokey' },
});
}
function mockResp(json: unknown, status = 200): Response {
return new Response(JSON.stringify(json), {
status,
headers: { 'content-type': 'application/json' },
});
}
afterEach(() => {
__setRerankTransportForTests(null);
resetGateway();
});
describe('gateway.rerank() — happy path', () => {
beforeEach(() => configureVoyage());
test('sends the right URL (CDX1-F2 — no /v1/v1/ doubling)', async () => {
let capturedUrl = '';
__setRerankTransportForTests(async (url) => {
capturedUrl = url;
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['d'] });
expect(capturedUrl).toBe('https://api.voyageai.com/v1/rerank');
expect(capturedUrl).not.toContain('/v1/v1/');
});
test('sends the right body shape', async () => {
let captured: any = null;
__setRerankTransportForTests(async (_url, init) => {
captured = JSON.parse(init.body as string);
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['d1', 'd2'], topN: 5 });
expect(captured).toEqual({
model: 'rerank-2.5',
query: 'q',
documents: ['d1', 'd2'],
top_k: 5,
});
});
test('omits top_k when not provided', async () => {
let captured: any = null;
__setRerankTransportForTests(async (_url, init) => {
captured = JSON.parse(init.body as string);
return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
});
await rerank({ query: 'q', documents: ['d'] });
expect('top_k' in captured).toBe(false);
expect('top_n' in captured).toBe(false);
});
test('uses Bearer auth from VOYAGE_API_KEY', async () => {
let authHeader = '';
__setRerankTransportForTests(async (_url, init) => {
const headers = new Headers(init.headers as HeadersInit);
authHeader = headers.get('authorization') ?? '';
return mockResp({ results: [{ index: 0, relevance_score: 1.0 }] });
});
await rerank({ query: 'q', documents: ['d'] });
expect(authHeader).toBe('Bearer sk-test-zerokey');
});
test('Content-Type: application/json', async () => {
let contentType = '';
__setRerankTransportForTests(async (_url, init) => {
const headers = new Headers(init.headers as HeadersInit);
contentType = headers.get('content-type') ?? '';
return mockResp({ results: [] });
});
await rerank({ query: 'q', documents: ['d'] });
expect(contentType).toBe('application/json');
});
test('maps response.results[].relevance_score → relevanceScore', async () => {
__setRerankTransportForTests(async () =>
mockResp({
results: [
{ index: 2, relevance_score: 0.99 },
{ index: 0, relevance_score: 0.5 },
{ index: 1, relevance_score: 0.1 },
],
}),
);
const out = await rerank({ query: 'q', documents: ['a', 'b', 'c'] });
expect(out).toEqual([
{ index: 2, relevanceScore: 0.99 },
{ index: 0, relevanceScore: 0.5 },
{ index: 1, relevanceScore: 0.1 },
]);
});
test('explicit input.model overrides gateway-configured model', async () => {
let bodyModel = '';
__setRerankTransportForTests(async (_url, init) => {
bodyModel = JSON.parse(init.body as string).model;
return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
});
await rerank({ query: 'q', documents: ['d'], model: 'voyage:rerank-2.5-lite' });
expect(bodyModel).toBe('rerank-2.5-lite');
});
test('empty documents returns [] without HTTP call', async () => {
let called = false;
__setRerankTransportForTests(async () => {
called = true;
return mockResp({ results: [] });
});
const out = await rerank({ query: 'q', documents: [] });
expect(out).toEqual([]);
expect(called).toBe(false);
});
});
describe('gateway.rerank() — error classification', () => {
beforeEach(() => configureVoyage());
test('missing required reranker API key → RerankError(no_key) before HTTP call (v0.48.2; auth = key present but rejected)', async () => {
configureGateway({
reranker_model: 'voyage:rerank-2.5',
env: {},
});
let called = false;
__setRerankTransportForTests(async () => {
called = true;
return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
});
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect(err).toBeInstanceOf(RerankError);
expect((err as RerankError).reason).toBe('no_key');
expect((err as Error).message).toContain('VOYAGE_API_KEY');
expect(called).toBe(false);
}
});
test('401 → auth', async () => {
__setRerankTransportForTests(async () => new Response('Unauthorized', { status: 401 }));
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect(err).toBeInstanceOf(RerankError);
expect((err as RerankError).reason).toBe('auth');
expect((err as RerankError).status).toBe(401);
}
});
test('403 → auth', async () => {
__setRerankTransportForTests(async () => new Response('Forbidden', { status: 403 }));
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect((err as RerankError).reason).toBe('auth');
}
});
test('429 → rate_limit', async () => {
__setRerankTransportForTests(async () => new Response('Rate limited', { status: 429 }));
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect((err as RerankError).reason).toBe('rate_limit');
}
});
test('500 → network', async () => {
__setRerankTransportForTests(async () => new Response('Server error', { status: 500 }));
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect((err as RerankError).reason).toBe('network');
}
});
test('400 (non-classified) → unknown', async () => {
__setRerankTransportForTests(async () => new Response('Bad request', { status: 400 }));
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect((err as RerankError).reason).toBe('unknown');
}
});
test('network exception (fetch reject) → unreachable', async () => {
__setRerankTransportForTests(async () => {
throw new Error('ECONNREFUSED');
});
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect((err as RerankError).reason).toBe('unreachable');
}
});
test('malformed response (no results array) → unknown', async () => {
__setRerankTransportForTests(async () => mockResp({ wrong_shape: true }));
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect((err as RerankError).reason).toBe('unknown');
}
});
});
describe('gateway.rerank() — payload-too-large pre-flight (no HTTP call)', () => {
beforeEach(() => configureVoyage());
test('body over max_payload_bytes throws payload_too_large WITHOUT transport call', async () => {
let called = false;
__setRerankTransportForTests(async () => {
called = true;
return mockResp({ results: [] });
});
// Voyage's max_payload_bytes is 5MB. 6MB body easily exceeds.
const huge = 'x'.repeat(6 * 1024 * 1024);
try {
await rerank({ query: 'q', documents: [huge] });
throw new Error('should have thrown');
} catch (err) {
expect(err).toBeInstanceOf(RerankError);
expect((err as RerankError).reason).toBe('payload_too_large');
// CRITICAL: the guard must fire BEFORE the transport is called.
// Otherwise applyReranker's fail-open would burn an HTTP round-trip.
expect(called).toBe(false);
}
});
test('body under cap proceeds normally', async () => {
let called = false;
__setRerankTransportForTests(async () => {
called = true;
return mockResp({ results: [{ index: 0, relevance_score: 0.5 }] });
});
const normal = 'doc'.repeat(100);
await rerank({ query: 'q', documents: [normal] });
expect(called).toBe(true);
});
});
describe('gateway.rerank() — allowlist enforcement (CDX2-F11)', () => {
test('rejects model not in recipe touchpoint.models[]', async () => {
configureVoyage();
let called = false;
__setRerankTransportForTests(async () => {
called = true;
return mockResp({ results: [] });
});
try {
await rerank({
query: 'q',
documents: ['d'],
model: 'voyage:rerank-fake-99',
});
throw new Error('should have thrown');
} catch (err) {
expect(err).toBeInstanceOf(RerankError);
expect((err as RerankError).message).toContain('not listed');
expect(called).toBe(false);
}
});
test('accepts rerank-3-lite (legacy allowlist member)', async () => {
configureVoyage();
__setRerankTransportForTests(async () => mockResp({ results: [{ index: 0, relevance_score: 1 }] }));
const out = await rerank({
query: 'q',
documents: ['d'],
model: 'voyage:rerank-3-lite',
});
expect(out.length).toBe(1);
});
test('rejects provider that does not declare reranker touchpoint', async () => {
configureGateway({
reranker_model: 'openai:gpt-fake',
env: { OPENAI_API_KEY: 'sk-fake' },
});
try {
await rerank({ query: 'q', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect(err).toBeInstanceOf(RerankError);
expect((err as RerankError).message).toContain('does not declare a reranker touchpoint');
}
});
});
describe('gateway.rerank() — guard rails', () => {
beforeEach(() => configureVoyage());
test('empty query throws RerankError(unknown)', async () => {
try {
await rerank({ query: '', documents: ['d'] });
throw new Error('should have thrown');
} catch (err) {
expect(err).toBeInstanceOf(RerankError);
expect((err as RerankError).reason).toBe('unknown');
}
});
});
describe('gateway.rerank() — v0.40.6.1 RerankerTouchpoint.path override', () => {
test('honors tp.path when recipe declares one (llama-server-reranker → /v1/rerank)', async () => {
configureGateway({
reranker_model: 'llama-server-reranker:qwen3-reranker-4b',
env: {},
});
let capturedUrl = '';
__setRerankTransportForTests(async (url) => {
capturedUrl = url;
return mockResp({ results: [{ index: 0, relevance_score: 0.8 }] });
});
await rerank({ query: 'q', documents: ['d'] });
// Recipe `base_url_default` is `http://localhost:8081/v1` and the
// touchpoint `path` is the LEAF `/rerank` — gateway must concatenate
// them to `http://localhost:8081/v1/rerank` exactly. The codex
// diff-review caught a /v1 path-doubling bug here that the prior
// `endsWith('/v1/rerank')` assertion silently passed through; the
// exact-equality assertion below is the regression guard.
expect(capturedUrl).toBe('http://localhost:8081/v1/rerank');
expect(capturedUrl).not.toContain('/v1/v1/');
expect(capturedUrl).not.toContain('/models/rerank');
});
});
describe('gateway.rerank() — v0.40.6.1 user-provided models (empty allowlist)', () => {
test('empty models[] on the recipe accepts any model id', async () => {
// llama-server-reranker declares `models: []` — anything goes.
configureGateway({
reranker_model: 'llama-server-reranker:some-custom-model-id',
env: {},
});
let called = false;
__setRerankTransportForTests(async () => {
called = true;
return mockResp({ results: [{ index: 0, relevance_score: 0.7 }] });
});
const out = await rerank({ query: 'q', documents: ['d'] });
expect(called).toBe(true);
expect(out.length).toBe(1);
});
test('still rejects empty models[] on a different model resolved via input.model', async () => {
// Even when caller overrides via input.model, the resolved recipe still
// governs the allowlist. Empty allowlist = no restriction.
configureGateway({
reranker_model: 'voyage:rerank-2.5',
env: { VOYAGE_API_KEY: 'sk-test' },
});
__setRerankTransportForTests(async () =>
mockResp({ results: [{ index: 0, relevance_score: 0.6 }] }),
);
const out = await rerank({
query: 'q',
documents: ['d'],
model: 'llama-server-reranker:whatever-id', // recipe with empty allowlist
});
expect(out.length).toBe(1);
});
});
describe('gateway.rerank() — v0.46.3 Voyage wire dialect', () => {
function configureVoyage(model: string = 'voyage:rerank-2.5'): void {
configureGateway({
reranker_model: model,
env: { VOYAGE_API_KEY: 'pa-test-voyagekey' },
});
}
test('posts to https://api.voyageai.com/v1/rerank (path override, no /v1/v1)', async () => {
configureVoyage();
let capturedUrl = '';
__setRerankTransportForTests(async (url) => {
capturedUrl = url;
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['d'] });
expect(capturedUrl).toBe('https://api.voyageai.com/v1/rerank');
});
test('request carries top_k (NOT top_n) — the only wire difference', async () => {
configureVoyage();
let body: any = null;
__setRerankTransportForTests(async (_url, init) => {
body = JSON.parse(String(init?.body ?? '{}'));
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['a', 'b'], topN: 1 });
expect(body.top_k).toBe(1);
expect(body.top_n).toBeUndefined();
expect(body.model).toBe('rerank-2.5');
});
test('local dialect sends top_n when top_param is absent', async () => {
configureGateway({ reranker_model: 'llama-server-reranker:fixture-reranker', env: {} });
let body: any = null;
__setRerankTransportForTests(async (_url, init) => {
body = JSON.parse(String(init?.body ?? '{}'));
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['a', 'b'], topN: 1 });
expect(body.top_n).toBe(1);
expect(body.top_k).toBeUndefined();
});
test("voyage's REST data[] response parses (live-wire shape, 2026-08-15)", async () => {
configureVoyage();
__setRerankTransportForTests(async () =>
mockResp({
object: 'list',
data: [{ index: 1, relevance_score: 0.8 }, { index: 0, relevance_score: 0.3 }],
model: 'rerank-2.5',
usage: { total_tokens: 12 },
}),
);
const out = await rerank({ query: 'q', documents: ['a', 'b'] });
expect(out).toEqual([
{ index: 1, relevanceScore: 0.8 },
{ index: 0, relevanceScore: 0.3 },
]);
});
test('the legacy results[] shape still parses too (local-server dialect)', async () => {
configureVoyage();
__setRerankTransportForTests(async () =>
mockResp({ results: [{ index: 0, relevance_score: 0.9 }] }),
);
const out = await rerank({ query: 'q', documents: ['a'] });
expect(out).toEqual([{ index: 0, relevanceScore: 0.9 }]);
});
test('malformed response (neither results[] nor data[]) → RerankError', async () => {
configureVoyage();
__setRerankTransportForTests(async () => mockResp({ items: [{ index: 0 }] }));
await expect(rerank({ query: 'q', documents: ['a'] })).rejects.toThrow(RerankError);
});
test('missing VOYAGE_API_KEY → RerankError no_key (fail-open skip class)', async () => {
resetGateway();
configureGateway({ reranker_model: 'voyage:rerank-2.5', env: {} });
__setRerankTransportForTests(async () =>
mockResp({ results: [{ index: 0, relevance_score: 0.9 }] }),
);
try {
await rerank({ query: 'q', documents: ['a'] });
expect.unreachable('should have thrown');
} catch (e) {
expect(e).toBeInstanceOf(RerankError);
expect((e as RerankError).reason).toBe('no_key');
expect((e as Error).message).toContain('VOYAGE_API_KEY');
}
});
test('rerank-2.5-lite passes the allowlist', async () => {
configureVoyage('voyage:rerank-2.5-lite');
let body: any = null;
__setRerankTransportForTests(async (_url, init) => {
body = JSON.parse(String(init?.body ?? '{}'));
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['a'] });
expect(body.model).toBe('rerank-2.5-lite');
});
// #4938: pre-fix the recipe allowlisted only the rerank-2.5 pair, so
// gateway.rerank() threw `Model "rerank-3" is not listed for Voyage AI
// reranker` before the request ever reached the transport — an operator
// could not opt into Voyage's current generation at all.
test('rerank-3 passes the allowlist and reaches the wire (#4938)', async () => {
configureVoyage('voyage:rerank-3');
let capturedUrl = '';
let body: any = null;
__setRerankTransportForTests(async (url, init) => {
capturedUrl = url;
body = JSON.parse(String(init?.body ?? '{}'));
return mockResp({
object: 'list',
data: [{ index: 0, relevance_score: 0.91 }],
model: 'rerank-3',
});
});
const out = await rerank({ query: 'q', documents: ['a'], topN: 1 });
// Same endpoint + same top-N key as the 2.5 pair: the wire is unchanged.
expect(capturedUrl).toBe('https://api.voyageai.com/v1/rerank');
expect(body.model).toBe('rerank-3');
expect(body.top_k).toBe(1);
expect(out).toEqual([{ index: 0, relevanceScore: 0.91 }]);
});
test('rerank-3-lite passes the allowlist (#4938)', async () => {
configureVoyage('voyage:rerank-3-lite');
let body: any = null;
__setRerankTransportForTests(async (_url, init) => {
body = JSON.parse(String(init?.body ?? '{}'));
return mockResp({ results: [{ index: 0, relevance_score: 0.9 }] });
});
await rerank({ query: 'q', documents: ['a'] });
expect(body.model).toBe('rerank-3-lite');
});
test('the allowlist still rejects an unlisted Voyage reranker (#4938)', async () => {
// The fix widens the allowlist; it must not disable it. A typo'd or
// retired model still fails locally instead of burning a wire call.
configureVoyage('voyage:rerank-9000');
let called = false;
__setRerankTransportForTests(async () => {
called = true;
return mockResp({ results: [] });
});
await expect(rerank({ query: 'q', documents: ['a'] })).rejects.toThrow(
/rerank-9000.*not listed/s,
);
expect(called).toBe(false);
});
});