Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

32.6 KB
Raw Blame
// @vitest-environment node
import { afterEach, describe, expect, it, vi } from 'vitest';

import {
  FTS_SEARCH_INDEX_DEFINITIONS,
  getFtsSearchIndexSchemaFingerprint,
  getFtsSearchIndexSchemaVersion,
} from '@/database/repositories/ftsSearchDocument';

import { ElasticsearchFtsSearchHttpClient } from './elasticsearch';

const mocks = vi.hoisted(() => ({
  recordSearchRequest: vi.fn(),
}));

vi.mock('./observability', () => ({
  recordElasticsearchFtsSearchRequest: mocks.recordSearchRequest,
}));

afterEach(() => {
  vi.unstubAllGlobals();
  vi.restoreAllMocks();
  vi.clearAllMocks();
});

/** Identity response body for a physical index that implements the declared generation of `entity`. */
const identityIndex = (
  entity: 'agents' | 'topics',
  uuid: string,
  meta: Partial<Record<'reindex_run_id' | 'schema_fingerprint' | 'schema_version', unknown>> = {},
) => ({
  mappings: {
    _meta: {
      reindex_run_id: '00000000-0000-4000-8000-000000000001',
      schema_fingerprint: getFtsSearchIndexSchemaFingerprint(entity),
      schema_version: getFtsSearchIndexSchemaVersion(entity),
      ...meta,
    },
    dynamic: 'strict',
    properties: {
      id: { type: 'keyword' },
      fts_search_sync_deleted: { type: 'boolean' },
    },
  },
  settings: {
    index: {
      analysis: { analyzer: { lobehub_icu: { type: 'custom' } } },
      uuid,
    },
  },
});

describe('ElasticsearchFtsSearchHttpClient', () => {
  it('rejects remote HTTP endpoints before exposing the API key', () => {
    expect(
      () =>
        new ElasticsearchFtsSearchHttpClient({
          apiKey: 'test-api-key',
          url: 'http://search.example.com',
        }),
    ).toThrow('must use HTTPS unless it targets loopback');
  });

  it('allows loopback HTTP endpoints for local development', () => {
    expect(
      () =>
        new ElasticsearchFtsSearchHttpClient({
          apiKey: 'test-api-key',
          url: 'http://localhost:9200',
        }),
    ).not.toThrow();
  });

  it('rejects an API key over plaintext HTTP even when insecure HTTP is allowed', () => {
    expect(
      () =>
        new ElasticsearchFtsSearchHttpClient({
          allowInsecureHttp: true,
          apiKey: 'test-api-key',
          url: 'http://elasticsearch:9200',
        }),
    ).toThrow('must not be sent over plaintext HTTP');
  });

  it('requires an API key unless insecure private-network access is explicitly allowed', () => {
    expect(
      () => new ElasticsearchFtsSearchHttpClient({ url: 'https://search.example.com' }),
    ).toThrow('API key is required unless ES_ALLOW_INSECURE_HTTP=true');
  });

  it('sends unauthenticated requests to an explicitly insecure private-network endpoint', async () => {
    const fetchMock = vi.fn().mockResolvedValue(
      new Response(JSON.stringify({ hits: { hits: [] }, took: 1 }), {
        headers: { 'Content-Type': 'application/json' },
        status: 200,
      }),
    );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      allowInsecureHttp: true,
      url: 'http://elasticsearch:9200',
    });

    await client.search({
      body: { query: { match_all: {} } },
      entity: 'agents',
      executedQueryChars: 1,
      index: 'lobehub-agents',
      originalQueryChars: 1,
      pagination: 'bounded',
      queryFieldCount: 1,
      truncated: false,
    });

    expect(fetchMock).toHaveBeenCalledOnce();
    const [endpoint, init] = fetchMock.mock.calls[0];
    expect(String(endpoint)).toBe('http://elasticsearch:9200/lobehub-agents/_search');
    expect(Object.keys(init.headers)).not.toContain('Authorization');
  });

  it('returns no identities without making requests when no aliases are provided', async () => {
    const fetchMock = vi.fn();
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(client.getFtsSearchSyncIndexIdentities([])).resolves.toEqual({});
    expect(fetchMock).not.toHaveBeenCalled();
  });

  it('sends an authenticated search request and returns candidate hits', async () => {
    const fetchMock = vi.fn().mockResolvedValue(
      new Response(
        JSON.stringify({
          hits: {
            hits: [{ _id: 'agent-1', _score: 8.5, sort: [8.5, 'agent-1'] }],
            total: { value: 1 },
          },
          took: 12,
        }),
        { headers: { 'Content-Length': '120', 'Content-Type': 'application/json' }, status: 200 },
      ),
    );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      requestTimeoutMs: 5000,
      url: 'https://search.example.com',
    });

    await expect(
      client.search({
        body: { query: { match_all: {} }, size: 1 },
        entity: 'agents',
        executedQueryChars: 0,
        index: 'lobehub-dev-agents',
        originalQueryChars: 0,
        pagination: 'bounded',
        queryFieldCount: 0,
        truncated: false,
      }),
    ).resolves.toEqual({
      hits: {
        hits: [{ _id: 'agent-1', _score: 8.5, sort: [8.5, 'agent-1'] }],
        total: { value: 1 },
      },
      took: 12,
    });
    expect(fetchMock).toHaveBeenCalledWith(
      new URL('https://search.example.com/lobehub-dev-agents/_search'),
      expect.objectContaining({
        body: JSON.stringify({ query: { match_all: {} }, size: 1 }),
        headers: {
          'Authorization': 'ApiKey test-api-key',
          'Content-Type': 'application/json',
        },
        method: 'POST',
      }),
    );
    expect(mocks.recordSearchRequest).toHaveBeenCalledWith({
      contentLength: 120,
      decodedBytes: expect.any(Number),
      durationMs: expect.any(Number),
      entity: 'agents',
      errorCode: 'none',
      executedQueryChars: 0,
      hits: 1,
      originalQueryChars: 0,
      pagination: 'bounded',
      queryFieldCount: 0,
      requestBytes: expect.any(Number),
      result: 'success',
      serverTookMs: 12,
      traceContext: expect.any(String),
      truncated: false,
      usage: 'unattributed',
    });
  });

  it('classifies nested clause-limit failures without copying response payloads into the error', async () => {
    const response = new Response(
      JSON.stringify({
        error: {
          caused_by: {
            reason: 'too many nested clauses: secret-query-fragment',
            type: 'too_many_clauses',
          },
          reason: 'all shards failed',
          root_cause: [{ type: 'query_shard_exception' }],
          type: 'search_phase_execution_exception',
        },
      }),
      { status: 400 },
    );
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(
      client.search({
        body: { query: { match_all: {} } },
        entity: 'agents',
        executedQueryChars: 96,
        index: 'lobehub-dev-agents',
        originalQueryChars: 7000,
        pagination: 'bounded',
        queryFieldCount: 8,
        truncated: true,
      }),
    ).rejects.toMatchObject({
      errorCode: 'too_many_clauses',
      message: 'Elasticsearch search request failed (400, too_many_clauses)',
      status: 400,
    });
    expect(response.bodyUsed).toBe(true);
    expect(mocks.recordSearchRequest).toHaveBeenCalledWith(
      expect.objectContaining({
        entity: 'agents',
        errorCode: 'too_many_clauses',
        result: 'http_error',
      }),
    );
    expect(errorSpy).toHaveBeenCalledWith('[fts-search] Elasticsearch request failed', {
      entity: 'agents',
      errorCode: 'too_many_clauses',
      executedQueryChars: 96,
      originalQueryChars: 7000,
      queryFieldCount: 8,
      requestBytes: expect.any(Number),
      status: 400,
      traceContext: expect.any(String),
      traceId: expect.any(String),
      truncated: true,
      usage: 'unattributed',
    });
    expect(JSON.stringify(errorSpy.mock.calls)).not.toContain('secret-query-fragment');
  });

  it('classifies generic server failures without exposing the response body', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValue(
          new Response(JSON.stringify({ error: 'sensitive backend detail' }), { status: 503 }),
        ),
    );
    vi.spyOn(console, 'error').mockImplementation(() => {});
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(
      client.search({
        body: { query: { match_all: {} } },
        entity: 'agents',
        executedQueryChars: 0,
        index: 'lobehub-dev-agents',
        originalQueryChars: 0,
        pagination: 'bounded',
        queryFieldCount: 0,
        truncated: false,
      }),
    ).rejects.toMatchObject({
      errorCode: 'server_error',
      message: 'Elasticsearch search request failed (503, server_error)',
      status: 503,
    });
  });

  it('rejects malformed successful responses', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValue(
        new Response(JSON.stringify({ hits: { hits: [{ _id: 123 }] } }), {
          headers: { 'Content-Type': 'application/json' },
          status: 200,
        }),
      ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(
      client.search({
        body: { query: { match_all: {} } },
        entity: 'agents',
        executedQueryChars: 0,
        index: 'lobehub-dev-agents',
        originalQueryChars: 0,
        pagination: 'bounded',
        queryFieldCount: 0,
        truncated: false,
      }),
    ).rejects.toThrow('Elasticsearch search response has an invalid shape');
    expect(mocks.recordSearchRequest).toHaveBeenCalledWith(
      expect.objectContaining({ entity: 'agents', result: 'parse_error' }),
    );
  });

  it('classifies fetch timeouts separately from other transport failures', async () => {
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });
    const input = {
      body: { query: { match_all: {} } },
      entity: 'agents' as const,
      executedQueryChars: 0,
      index: 'lobehub-dev-agents',
      originalQueryChars: 0,
      pagination: 'bounded' as const,
      queryFieldCount: 0,
      truncated: false,
    };

    vi.stubGlobal(
      'fetch',
      vi.fn().mockRejectedValueOnce(new DOMException('The operation timed out', 'TimeoutError')),
    );
    await expect(client.search(input)).rejects.toThrow('The operation timed out');
    expect(mocks.recordSearchRequest).toHaveBeenLastCalledWith(
      expect.objectContaining({ entity: 'agents', result: 'timeout' }),
    );

    vi.stubGlobal('fetch', vi.fn().mockRejectedValueOnce(new TypeError('connection closed')));
    await expect(client.search(input)).rejects.toThrow('connection closed');
    expect(mocks.recordSearchRequest).toHaveBeenLastCalledWith(
      expect.objectContaining({ entity: 'agents', result: 'other_error' }),
    );
  });

  it('sends bulk payloads addressed to physical generation indexes', async () => {
    const fetchMock = vi.fn().mockResolvedValue(
      new Response(JSON.stringify({ errors: false, items: [{ index: { status: 201 } }] }), {
        headers: { 'Content-Type': 'application/json' },
        status: 200,
      }),
    );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      requestTimeoutMs: 5000,
      url: 'https://search.example.com',
    });
    const body = '{"index":{}}\n{"id":"agent-1"}\n';

    await expect(client.bulk(body)).resolves.toEqual({
      errors: false,
      items: [{ index: { status: 201 } }],
    });
    expect(fetchMock).toHaveBeenCalledWith(
      new URL('https://search.example.com/_bulk'),
      expect.objectContaining({
        body,
        headers: {
          'Authorization': 'ApiKey test-api-key',
          'Content-Type': 'application/x-ndjson',
        },
        method: 'POST',
      }),
    );
  });

  it('lists every live generation behind each alias, including the writable index', async () => {
    const rebuildRunId = '00000000-0000-4000-8000-000000000003';
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(
        Response.json({
          'lobehub-agents-v2': { aliases: { 'lobehub-agents': { is_write_index: true } } },
          'lobehub-agents-v1': { aliases: { 'lobehub-agents': { is_write_index: false } } },
          'custom-topics': { aliases: { 'lobehub-topics': {} } },
        }),
      )
      .mockResolvedValueOnce(
        Response.json({
          'lobehub-agents-v1': { aliases: { 'lobehub-agents': { is_write_index: false } } },
          'lobehub-agents-v2': { aliases: { 'lobehub-agents': { is_write_index: true } } },
          'lobehub-agents-v3': { aliases: {} },
          [`lobehub-agents-v3-r${rebuildRunId}`]: { aliases: {} },
          'lobehub-agents-v3-backup': { aliases: {} },
        }),
      );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(
      client.getFtsSearchSyncGenerationTargets(['lobehub-topics', 'lobehub-agents']),
    ).resolves.toEqual({
      'lobehub-agents': [
        'lobehub-agents-v1',
        'lobehub-agents-v2',
        'lobehub-agents-v3',
        `lobehub-agents-v3-r${rebuildRunId}`,
      ],
      'lobehub-topics': ['custom-topics'],
    });
    expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
      'https://search.example.com/_alias/lobehub-topics,lobehub-agents',
      'https://search.example.com/lobehub-topics-v*,lobehub-agents-v*/_alias?expand_wildcards=open&allow_no_indices=true',
    ]);
  });

  it('refuses generation targets for an alias without a unique writable index', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
            'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
          }),
        )
        .mockResolvedValueOnce(Response.json({})),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(client.getFtsSearchSyncGenerationTargets(['lobehub-agents'])).rejects.toThrow(
      'is not a writable alias: lobehub-agents',
    );
  });

  it('verifies sync readiness from one alias lookup and its complete index identity', async () => {
    const aliasResponse = () =>
      Response.json({
        'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
        'lobehub-topics-v1': {
          aliases: { 'lobehub-topics': { is_write_index: true } },
        },
      });
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(aliasResponse())
      .mockResolvedValueOnce(
        Response.json({
          'lobehub-agents-v1': identityIndex('agents', 'agents-index-uuid'),
          'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid'),
        }),
      );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(
      client.assertFtsSearchSyncAliases(['lobehub-agents', 'lobehub-topics']),
    ).resolves.toBeUndefined();
    expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
      'https://search.example.com/_alias/lobehub-agents,lobehub-topics',
      'https://search.example.com/lobehub-agents-v1,lobehub-topics-v1?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid',
    ]);
  });

  it.each(['missing', 'keyword'])(
    'rejects sync readiness with a %s tombstone mapping',
    async (type) => {
      const identity = identityIndex('agents', 'agents-index-uuid');
      const fetchMock = vi
        .fn()
        .mockResolvedValueOnce(
          Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
        )
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-agents-v1': {
              ...identity,
              mappings: {
                ...identity.mappings,
                properties: type === 'missing' ? {} : { fts_search_sync_deleted: { type } },
              },
            },
          }),
        );
      vi.stubGlobal('fetch', fetchMock);
      const client = new ElasticsearchFtsSearchHttpClient({
        apiKey: 'test-api-key',
        indexNamespace: 'lobehub',
        url: 'https://search.example.com',
      });

      await expect(client.assertFtsSearchSyncAliases(['lobehub-agents'])).rejects.toThrow(
        'Elasticsearch full-text search sync alias lacks a boolean fts_search_sync_deleted mapping: lobehub-agents',
      );
    },
  );

  it('returns stable runtime identities for indices that implement the declared generations', async () => {
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(
        Response.json({
          'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
          'lobehub-topics-v1': { aliases: { 'lobehub-topics': {} } },
        }),
      )
      .mockResolvedValueOnce(
        Response.json({
          'lobehub-agents-v1': identityIndex('agents', 'agents-index-uuid', {
            reindex_run_id: '00000000-0000-4000-8000-000000000001',
          }),
          'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid', {
            reindex_run_id: '00000000-0000-4000-8000-000000000002',
          }),
        }),
      );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    const identities = await client.getFtsSearchSyncIndexIdentities([
      'lobehub-topics',
      'lobehub-agents',
    ]);

    // Entities are rebuilt and promoted independently, so different reindex runs are expected.
    expect(identities).toEqual({
      'lobehub-agents': {
        indexUuid: 'agents-index-uuid',
        mappingSha256: expect.stringMatching(/^[\da-f]{64}$/),
        physicalIndex: 'lobehub-agents-v1',
        reindexRunId: '00000000-0000-4000-8000-000000000001',
        schemaFingerprint: getFtsSearchIndexSchemaFingerprint('agents'),
        schemaVersion: getFtsSearchIndexSchemaVersion('agents'),
        settingsSha256: expect.stringMatching(/^[\da-f]{64}$/),
      },
      'lobehub-topics': {
        indexUuid: 'topics-index-uuid',
        mappingSha256: expect.stringMatching(/^[\da-f]{64}$/),
        physicalIndex: 'lobehub-topics-v1',
        reindexRunId: '00000000-0000-4000-8000-000000000002',
        schemaFingerprint: getFtsSearchIndexSchemaFingerprint('topics'),
        schemaVersion: getFtsSearchIndexSchemaVersion('topics'),
        settingsSha256: expect.stringMatching(/^[\da-f]{64}$/),
      },
    });
    expect(Object.keys(identities)).toEqual(['lobehub-agents', 'lobehub-topics']);
    expect(identities['lobehub-agents'].settingsSha256).toBe(
      identities['lobehub-topics'].settingsSha256,
    );
    expect(fetchMock.mock.calls.map(([url]) => url.toString())).toEqual([
      'https://search.example.com/_alias/lobehub-topics,lobehub-agents',
      'https://search.example.com/lobehub-agents-v1,lobehub-topics-v1?filter_path=*.mappings,*.settings.index.analysis,*.settings.index.uuid',
    ]);
  });

  it('accepts a legacy index without a schema fingerprint on version alone', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValueOnce(
          Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
        )
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-agents-v1': identityIndex('agents', 'agents-index-uuid', {
              schema_fingerprint: undefined,
            }),
          }),
        ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-agents'])).resolves.toEqual({
      'lobehub-agents': expect.objectContaining({ schemaFingerprint: null }),
    });
  });

  it('allows sync when Serverless omits the internal index UUID', async () => {
    const index = identityIndex('agents', 'unused', { schema_fingerprint: undefined });
    const { uuid: _uuid, ...settings } = index.settings.index;
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockImplementation(async (url: URL) =>
          Response.json(
            url.pathname.startsWith('/_alias/')
              ? { 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }
              : { 'lobehub-agents-v1': { ...index, settings: { index: settings } } },
          ),
        ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(client.assertFtsSearchSyncAliases(['lobehub-agents'])).resolves.toBeUndefined();
    await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-agents'])).resolves.toMatchObject(
      {
        'lobehub-agents': { indexUuid: null, schemaFingerprint: null, schemaVersion: 1 },
      },
    );
  });

  it('rejects a runtime identity response with missing reindex metadata', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValueOnce(
          Response.json({ 'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } } }),
        )
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-agents-v1': {
              mappings: {
                properties: { fts_search_sync_deleted: { type: 'boolean' } },
                sensitive_payload: 'must-not-leak',
              },
              settings: { index: { analysis: {}, uuid: 'agents-index-uuid' } },
            },
          }),
        ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    const request = client.getFtsSearchSyncIndexIdentities(['lobehub-agents']);
    await expect(request).rejects.toThrow(
      'Elasticsearch full-text search sync index identity response has an invalid shape',
    );
    await expect(request).rejects.not.toThrow(/test-api-key|must-not-leak/);
  });

  it('accepts an alias that still serves an older generation while the upgrade is in progress', async () => {
    const liveVersion = getFtsSearchIndexSchemaVersion('topics');
    const definition = FTS_SEARCH_INDEX_DEFINITIONS.topics as unknown as { schemaVersion: number };
    // Every entity declares v1 today; pretend the deployed code moved topics one generation ahead.
    definition.schemaVersion = liveVersion + 1;
    try {
      vi.stubGlobal(
        'fetch',
        vi
          .fn()
          .mockResolvedValueOnce(
            Response.json({ 'lobehub-topics-v1': { aliases: { 'lobehub-topics': {} } } }),
          )
          .mockResolvedValueOnce(
            Response.json({
              'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid', {
                schema_fingerprint: 'older-generation',
                schema_version: liveVersion,
              }),
            }),
          ),
      );
      const client = new ElasticsearchFtsSearchHttpClient({
        apiKey: 'test-api-key',
        indexNamespace: 'lobehub',
        url: 'https://search.example.com',
      });

      await expect(
        client.getFtsSearchSyncIndexIdentities(['lobehub-topics']),
      ).resolves.toMatchObject({ 'lobehub-topics': { schemaVersion: liveVersion } });
    } finally {
      definition.schemaVersion = liveVersion;
    }
  });

  it('rejects an alias whose live index implements a newer schema version than the code', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValueOnce(
          Response.json({ 'lobehub-topics-v2': { aliases: { 'lobehub-topics': {} } } }),
        )
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-topics-v2': identityIndex('topics', 'topics-index-uuid', {
              schema_version: getFtsSearchIndexSchemaVersion('topics') + 1,
            }),
          }),
        ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-topics'])).rejects.toThrow(
      `Elasticsearch full-text search alias lobehub-topics implements schema version ${getFtsSearchIndexSchemaVersion('topics') + 1} but the deployed code declares v${getFtsSearchIndexSchemaVersion('topics')}`,
    );
  });

  it('lists the mapped fields of every generation index', async () => {
    const fetchMock = vi.fn().mockResolvedValueOnce(
      Response.json({
        'lobehub-topics-v1': {
          mappings: { properties: { id: { type: 'keyword' }, title: { type: 'text' } } },
        },
        'lobehub-topics-v2': {
          mappings: {
            properties: {
              id: { type: 'keyword' },
              content: { type: 'text' },
              title: { type: 'text' },
            },
          },
        },
      }),
    );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(
      client.getFtsSearchSyncIndexFields({
        'lobehub-topics-v1': 'topics',
        'lobehub-topics-v2': 'topics',
      }),
    ).resolves.toEqual({
      fieldsByIndex: {
        'lobehub-topics-v1': ['id', 'title'],
        'lobehub-topics-v2': ['content', 'id', 'title'],
      },
      incompatibilities: [],
    });
    expect(fetchMock.mock.calls[0][0].toString()).toBe(
      'https://search.example.com/lobehub-topics-v1,lobehub-topics-v2/_mapping?filter_path=*.mappings._meta,*.mappings.properties',
    );
  });

  it('validates the run identity of a same-schema rebuild target before syncing it', async () => {
    const runId = '00000000-0000-4000-8000-000000000003';
    const index = `lobehub-topics-v1-r${runId}`;
    const response = (reindexRunId: string) =>
      Response.json({
        [index]: {
          mappings: {
            _meta: { reindex_run_id: reindexRunId, schema_version: 1 },
            properties: { id: { type: 'keyword' }, title: { type: 'text' } },
          },
        },
      });
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(response(runId))
      .mockResolvedValueOnce(response('00000000-0000-4000-8000-000000000004'));
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(client.getFtsSearchSyncIndexFields({ [index]: 'topics' })).resolves.toMatchObject({
      fieldsByIndex: { [index]: ['id', 'title'] },
    });
    await expect(client.getFtsSearchSyncIndexFields({ [index]: 'topics' })).rejects.toThrow(
      'has incompatible reindex metadata',
    );
  });

  it('rejects a field lookup that omits a requested generation index', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValueOnce(
        Response.json({
          'lobehub-topics-v1': { mappings: { properties: { id: { type: 'keyword' } } } },
        }),
      ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(
      client.getFtsSearchSyncIndexFields({
        'lobehub-topics-v1': 'topics',
        'lobehub-topics-v2': 'topics',
      }),
    ).rejects.toThrow('field lookup is missing index lobehub-topics-v2');
  });

  it('reports a generation that requires a field missing from the current projection', async () => {
    vi.stubGlobal(
      'fetch',
      vi.fn().mockResolvedValueOnce(
        Response.json({
          'lobehub-agents-v1': {
            mappings: {
              properties: {
                id: { type: 'keyword' },
                legacy_title: { type: 'text' },
              },
            },
          },
        }),
      ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      url: 'https://search.example.com',
    });

    await expect(
      client.getFtsSearchSyncIndexFields({ 'lobehub-agents-v1': 'agents' }),
    ).resolves.toEqual({
      fieldsByIndex: {
        'lobehub-agents-v1': ['id', 'legacy_title'],
      },
      incompatibilities: [
        {
          entity: 'agents',
          index: 'lobehub-agents-v1',
          message:
            'Elasticsearch full-text search index lobehub-agents-v1 is incompatible with the current agents projection: target field legacy_title (text) is missing from the current mapping. Retain compatible source fields in FTS_SEARCH_RETAINED_SOURCE_PROPERTIES and the document builder, or retire the index before syncing agents.',
        },
      ],
    });
  });

  it('rejects an alias whose live index was built from a drifted mapping of the same version', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValueOnce(
          Response.json({ 'lobehub-topics-v1': { aliases: { 'lobehub-topics': {} } } }),
        )
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-topics-v1': identityIndex('topics', 'topics-index-uuid', {
              schema_fingerprint: 'f'.repeat(64),
            }),
          }),
        ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-topics'])).rejects.toThrow(
      'Elasticsearch full-text search alias lobehub-topics was built from a different v1 mapping than the deployed code declares',
    );
  });

  it('rejects identity validation without an index namespace or with a foreign alias', async () => {
    vi.stubGlobal('fetch', vi.fn());

    await expect(
      new ElasticsearchFtsSearchHttpClient({
        apiKey: 'test-api-key',
        url: 'https://search.example.com',
      }).getFtsSearchSyncIndexIdentities(['lobehub-topics']),
    ).rejects.toThrow('index namespace is required');
    await expect(
      new ElasticsearchFtsSearchHttpClient({
        apiKey: 'test-api-key',
        indexNamespace: 'lobehub',
        url: 'https://search.example.com',
      }).getFtsSearchSyncIndexIdentities(['other-topics']),
    ).rejects.toThrow('alias does not belong to the configured index namespace: other-topics');
  });

  it('selects the unique explicit write index for a multi-target alias', async () => {
    vi.stubGlobal(
      'fetch',
      vi
        .fn()
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-agents-v1': {
              aliases: { 'lobehub-agents': { is_write_index: false } },
            },
            'lobehub-agents-v2': {
              aliases: { 'lobehub-agents': { is_write_index: true } },
            },
          }),
        )
        .mockResolvedValueOnce(
          Response.json({
            'lobehub-agents-v2': identityIndex('agents', 'agents-index-uuid'),
          }),
        ),
    );
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(client.getFtsSearchSyncIndexIdentities(['lobehub-agents'])).resolves.toMatchObject(
      {
        'lobehub-agents': { physicalIndex: 'lobehub-agents-v2' },
      },
    );
  });

  it('rejects a multi-target alias without an explicit write index', async () => {
    const fetchMock = vi.fn().mockResolvedValueOnce(
      Response.json({
        'lobehub-agents-v1': { aliases: { 'lobehub-agents': {} } },
        'lobehub-agents-v2': { aliases: { 'lobehub-agents': {} } },
      }),
    );
    vi.stubGlobal('fetch', fetchMock);
    const client = new ElasticsearchFtsSearchHttpClient({
      apiKey: 'test-api-key',
      indexNamespace: 'lobehub',
      url: 'https://search.example.com',
    });

    await expect(client.assertFtsSearchSyncAliases(['lobehub-agents'])).rejects.toThrow(
      'Elasticsearch full-text search sync destination is not a writable alias: lobehub-agents',
    );
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });
});