@open-mercato/search 0.6.5-develop.4964.1.ae0edca575 → 0.6.5-develop.5048.1.fd82f4ae17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,8 +5,9 @@ const DEFAULT_STRATEGIES = ["fulltext", "vector", "tokens"];
5
5
  test.describe("TC-SEARCH-006: global search honors saved strategy config over URL override", () => {
6
6
  test("persisted enabledStrategies wins over the strategies URL parameter", async ({ request }) => {
7
7
  test.slow();
8
+ test.setTimeout(12e4);
8
9
  let token = null;
9
- let originalStrategies = null;
10
+ let originalStrategies = DEFAULT_STRATEGIES;
10
11
  try {
11
12
  token = await getAuthToken(request, "admin");
12
13
  const currentRes = await apiRequest(request, "GET", "/api/search/settings/global-search", { token });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-006.spec.ts"],
4
- "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\n\ntype GlobalSearchSettings = { enabledStrategies?: string[] }\ntype GlobalSearchUpdate = { ok?: boolean; enabledStrategies?: string[] }\ntype GlobalSearchResponse = { strategiesEnabled?: string[] }\n\nconst DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']\n\n/**\n * TC-SEARCH-006: global (Cmd+K) search honors the saved strategy config over a\n * URL override. Source: issue #2483.\n *\n * Routes:\n * - GET/POST /api/search/settings/global-search (POST requires search.manage)\n * - GET /api/search/search/global (ignores any `strategies` URL param)\n *\n * Saves enabledStrategies = ['tokens'], then calls global search with a\n * conflicting ?strategies=fulltext,vector and asserts the response's\n * strategiesEnabled reflects the SAVED config, not the URL. The original config\n * is restored in `finally`. `admin` holds both search.view and search.manage.\n */\ntest.describe('TC-SEARCH-006: global search honors saved strategy config over URL override', () => {\n test('persisted enabledStrategies wins over the strategies URL parameter', async ({ request }) => {\n test.slow()\n\n let token: string | null = null\n let originalStrategies: string[] | null = null\n\n try {\n token = await getAuthToken(request, 'admin')\n\n const currentRes = await apiRequest(request, 'GET', '/api/search/settings/global-search', { token })\n expect(currentRes.ok(), 'GET global-search settings should succeed').toBeTruthy()\n const current = (await readJsonSafe<GlobalSearchSettings>(currentRes)) ?? {}\n expect(Array.isArray(current.enabledStrategies), 'settings expose an enabledStrategies array').toBe(true)\n originalStrategies =\n Array.isArray(current.enabledStrategies) && current.enabledStrategies.length > 0\n ? current.enabledStrategies\n : DEFAULT_STRATEGIES\n\n const updateRes = await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: ['tokens'] },\n })\n expect(updateRes.status(), 'POST global-search settings should return 200').toBe(200)\n const updated = (await readJsonSafe<GlobalSearchUpdate>(updateRes)) ?? {}\n expect(updated.ok, 'update reports ok').toBe(true)\n expect(updated.enabledStrategies, 'update echoes the saved strategies').toEqual(['tokens'])\n\n const globalRes = await apiRequest(\n request,\n 'GET',\n `/api/search/search/global?q=qa-search-006-${Date.now()}&strategies=fulltext,vector`,\n { token },\n )\n expect(globalRes.ok(), 'GET global search should succeed').toBeTruthy()\n const globalBody = (await readJsonSafe<GlobalSearchResponse>(globalRes)) ?? {}\n expect(\n globalBody.strategiesEnabled,\n 'global search must use the saved config (tokens), ignoring the strategies URL override',\n ).toEqual(['tokens'])\n } finally {\n if (token && originalStrategies) {\n await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: originalStrategies },\n }).catch(() => undefined)\n }\n }\n })\n})\n"],
5
- "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAM7B,MAAM,qBAAqB,CAAC,YAAY,UAAU,QAAQ;AAe1D,KAAK,SAAS,+EAA+E,MAAM;AACjG,OAAK,sEAAsE,OAAO,EAAE,QAAQ,MAAM;AAChG,SAAK,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CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\n\ntype GlobalSearchSettings = { enabledStrategies?: string[] }\ntype GlobalSearchUpdate = { ok?: boolean; enabledStrategies?: string[] }\ntype GlobalSearchResponse = { strategiesEnabled?: string[] }\n\nconst DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']\n\n/**\n * TC-SEARCH-006: global (Cmd+K) search honors the saved strategy config over a\n * URL override. Source: issue #2483.\n *\n * Routes:\n * - GET/POST /api/search/settings/global-search (POST requires search.manage)\n * - GET /api/search/search/global (ignores any `strategies` URL param)\n *\n * Saves enabledStrategies = ['tokens'], then calls global search with a\n * conflicting ?strategies=fulltext,vector and asserts the response's\n * strategiesEnabled reflects the SAVED config, not the URL. The original config\n * is restored in `finally`. `admin` holds both search.view and search.manage.\n */\ntest.describe('TC-SEARCH-006: global search honors saved strategy config over URL override', () => {\n test('persisted enabledStrategies wins over the strategies URL parameter', async ({ request }) => {\n test.slow()\n test.setTimeout(120_000)\n\n let token: string | null = null\n let originalStrategies: string[] | null = DEFAULT_STRATEGIES\n\n try {\n token = await getAuthToken(request, 'admin')\n\n const currentRes = await apiRequest(request, 'GET', '/api/search/settings/global-search', { token })\n expect(currentRes.ok(), 'GET global-search settings should succeed').toBeTruthy()\n const current = (await readJsonSafe<GlobalSearchSettings>(currentRes)) ?? {}\n expect(Array.isArray(current.enabledStrategies), 'settings expose an enabledStrategies array').toBe(true)\n originalStrategies =\n Array.isArray(current.enabledStrategies) && current.enabledStrategies.length > 0\n ? current.enabledStrategies\n : DEFAULT_STRATEGIES\n\n const updateRes = await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: ['tokens'] },\n })\n expect(updateRes.status(), 'POST global-search settings should return 200').toBe(200)\n const updated = (await readJsonSafe<GlobalSearchUpdate>(updateRes)) ?? {}\n expect(updated.ok, 'update reports ok').toBe(true)\n expect(updated.enabledStrategies, 'update echoes the saved strategies').toEqual(['tokens'])\n\n const globalRes = await apiRequest(\n request,\n 'GET',\n `/api/search/search/global?q=qa-search-006-${Date.now()}&strategies=fulltext,vector`,\n { token },\n )\n expect(globalRes.ok(), 'GET global search should succeed').toBeTruthy()\n const globalBody = (await readJsonSafe<GlobalSearchResponse>(globalRes)) ?? {}\n expect(\n globalBody.strategiesEnabled,\n 'global search must use the saved config (tokens), ignoring the strategies URL override',\n ).toEqual(['tokens'])\n } finally {\n if (token && originalStrategies) {\n await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: originalStrategies },\n }).catch(() => undefined)\n }\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAM7B,MAAM,qBAAqB,CAAC,YAAY,UAAU,QAAQ;AAe1D,KAAK,SAAS,+EAA+E,MAAM;AACjG,OAAK,sEAAsE,OAAO,EAAE,QAAQ,MAAM;AAChG,SAAK,KAAK;AACV,SAAK,WAAW,IAAO;AAEvB,QAAI,QAAuB;AAC3B,QAAI,qBAAsC;AAE1C,QAAI;AACF,cAAQ,MAAM,aAAa,SAAS,OAAO;AAE3C,YAAM,aAAa,MAAM,WAAW,SAAS,OAAO,sCAAsC,EAAE,MAAM,CAAC;AACnG,aAAO,WAAW,GAAG,GAAG,2CAA2C,EAAE,WAAW;AAChF,YAAM,UAAW,MAAM,aAAmC,UAAU,KAAM,CAAC;AAC3E,aAAO,MAAM,QAAQ,QAAQ,iBAAiB,GAAG,4CAA4C,EAAE,KAAK,IAAI;AACxG,2BACE,MAAM,QAAQ,QAAQ,iBAAiB,KAAK,QAAQ,kBAAkB,SAAS,IAC3E,QAAQ,oBACR;AAEN,YAAM,YAAY,MAAM,WAAW,SAAS,QAAQ,sCAAsC;AAAA,QACxF;AAAA,QACA,MAAM,EAAE,mBAAmB,CAAC,QAAQ,EAAE;AAAA,MACxC,CAAC;AACD,aAAO,UAAU,OAAO,GAAG,+CAA+C,EAAE,KAAK,GAAG;AACpF,YAAM,UAAW,MAAM,aAAiC,SAAS,KAAM,CAAC;AACxE,aAAO,QAAQ,IAAI,mBAAmB,EAAE,KAAK,IAAI;AACjD,aAAO,QAAQ,mBAAmB,oCAAoC,EAAE,QAAQ,CAAC,QAAQ,CAAC;AAE1F,YAAM,YAAY,MAAM;AAAA,QACtB;AAAA,QACA;AAAA,QACA,6CAA6C,KAAK,IAAI,CAAC;AAAA,QACvD,EAAE,MAAM;AAAA,MACV;AACA,aAAO,UAAU,GAAG,GAAG,kCAAkC,EAAE,WAAW;AACtE,YAAM,aAAc,MAAM,aAAmC,SAAS,KAAM,CAAC;AAC7E;AAAA,QACE,WAAW;AAAA,QACX;AAAA,MACF,EAAE,QAAQ,CAAC,QAAQ,CAAC;AAAA,IACtB,UAAE;AACA,UAAI,SAAS,oBAAoB;AAC/B,cAAM,WAAW,SAAS,QAAQ,sCAAsC;AAAA,UACtE;AAAA,UACA,MAAM,EAAE,mBAAmB,mBAAmB;AAAA,QAChD,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
6
6
  "names": []
7
7
  }
@@ -1,16 +1,26 @@
1
1
  import { expect, test } from "@playwright/test";
2
2
  import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
3
  import { readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ const DEFAULT_STRATEGIES = ["fulltext", "vector", "tokens"];
4
5
  test.describe("TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info", () => {
5
6
  test("a second reindex while one is active is rejected with 409", async ({ request }) => {
6
7
  test.slow();
8
+ test.setTimeout(12e4);
7
9
  let token = null;
8
10
  try {
9
11
  token = await getAuthToken(request, "admin");
10
12
  await apiRequest(request, "POST", "/api/search/reindex/cancel", { token }).catch(() => void 0);
13
+ await apiRequest(request, "POST", "/api/search/settings/global-search", {
14
+ token,
15
+ data: { enabledStrategies: DEFAULT_STRATEGIES }
16
+ }).catch(() => void 0);
11
17
  const first = await apiRequest(request, "POST", "/api/search/reindex", { token, data: { useQueue: true } });
12
18
  expect(first.status(), "first reindex must not hit a pre-existing lock").not.toBe(409);
13
19
  expect([200, 503], "first reindex starts (200) or reports backend unavailable (503)").toContain(first.status());
20
+ const settings = await apiRequest(request, "GET", "/api/search/settings", { token });
21
+ expect(settings.ok(), "search settings should be readable after starting reindex").toBeTruthy();
22
+ const settingsBody = await readJsonSafe(settings) ?? {};
23
+ expect(settingsBody.settings?.fulltextReindexLock?.type, "first reindex should leave an observable fulltext lock").toBe("fulltext");
14
24
  const second = await apiRequest(request, "POST", "/api/search/reindex", { token, data: { useQueue: true } });
15
25
  expect(second.status(), "a concurrent reindex must be rejected with 409").toBe(409);
16
26
  const body = await readJsonSafe(second) ?? {};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-007.spec.ts"],
4
- "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\n\ntype ReindexLock = {\n type?: string\n action?: string\n startedAt?: string\n elapsedMinutes?: number\n processedCount?: number | null\n totalCount?: number | null\n}\ntype ConflictBody = { error?: string; lock?: ReindexLock }\n\n/**\n * TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info.\n * Source: issue #2483.\n *\n * Route: POST /api/search/reindex (requireFeatures ['search.reindex']). The route\n * acquires a per-tenant DB lock BEFORE any indexing work and, in queue mode\n * (useQueue:true \u2014 the default), does NOT release it in `finally` (workers and\n * the heartbeat own it). So a first call holds the lock and a second call returns\n * 409 with the lock descriptor \u2014 independent of whether a fulltext backend is\n * configured, because the lock is taken before the strategy-availability check.\n * Integration specs run serially (workers:1), so no other test contends for the\n * shared lock; it is released in `finally` via the cancel endpoint.\n */\ntest.describe('TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info', () => {\n test('a second reindex while one is active is rejected with 409', async ({ request }) => {\n test.slow()\n\n let token: string | null = null\n\n try {\n token = await getAuthToken(request, 'admin')\n\n // Start from a clean lock state.\n await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)\n\n // First reindex acquires (and, in queue mode, holds) the fulltext lock.\n const first = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })\n expect(first.status(), 'first reindex must not hit a pre-existing lock').not.toBe(409)\n expect([200, 503], 'first reindex starts (200) or reports backend unavailable (503)').toContain(first.status())\n\n // Second reindex is rejected while the first holds the lock.\n const second = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })\n expect(second.status(), 'a concurrent reindex must be rejected with 409').toBe(409)\n const body = (await readJsonSafe<ConflictBody>(second)) ?? {}\n expect(body.lock?.type, 'the 409 lock descriptor identifies the fulltext lock').toBe('fulltext')\n expect(typeof body.lock?.action, 'the lock reports its action').toBe('string')\n expect(typeof body.lock?.startedAt, 'the lock reports when it started').toBe('string')\n expect(typeof body.lock?.elapsedMinutes, 'the lock reports elapsed minutes').toBe('number')\n } finally {\n if (token) {\n await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)\n }\n }\n })\n})\n"],
5
- "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAyB7B,KAAK,SAAS,yEAAyE,MAAM;AAC3F,OAAK,6DAA6D,OAAO,EAAE,QAAQ,MAAM;AACvF,SAAK,KAAK;AAEV,QAAI,QAAuB;AAE3B,QAAI;AACF,cAAQ,MAAM,aAAa,SAAS,OAAO;AAG3C,YAAM,WAAW,SAAS,QAAQ,8BAA8B,EAAE,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AAGhG,YAAM,QAAQ,MAAM,WAAW,SAAS,QAAQ,uBAAuB,EAAE,OAAO,MAAM,EAAE,UAAU,KAAK,EAAE,CAAC;AAC1G,aAAO,MAAM,OAAO,GAAG,gDAAgD,EAAE,IAAI,KAAK,GAAG;AACrF,aAAO,CAAC,KAAK,GAAG,GAAG,iEAAiE,EAAE,UAAU,MAAM,OAAO,CAAC;AAG9G,YAAM,SAAS,MAAM,WAAW,SAAS,QAAQ,uBAAuB,EAAE,OAAO,MAAM,EAAE,UAAU,KAAK,EAAE,CAAC;AAC3G,aAAO,OAAO,OAAO,GAAG,gDAAgD,EAAE,KAAK,GAAG;AAClF,YAAM,OAAQ,MAAM,aAA2B,MAAM,KAAM,CAAC;AAC5D,aAAO,KAAK,MAAM,MAAM,sDAAsD,EAAE,KAAK,UAAU;AAC/F,aAAO,OAAO,KAAK,MAAM,QAAQ,6BAA6B,EAAE,KAAK,QAAQ;AAC7E,aAAO,OAAO,KAAK,MAAM,WAAW,kCAAkC,EAAE,KAAK,QAAQ;AACrF,aAAO,OAAO,KAAK,MAAM,gBAAgB,kCAAkC,EAAE,KAAK,QAAQ;AAAA,IAC5F,UAAE;AACA,UAAI,OAAO;AACT,cAAM,WAAW,SAAS,QAAQ,8BAA8B,EAAE,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAClG;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\n\ntype ReindexLock = {\n type?: string\n action?: string\n startedAt?: string\n elapsedMinutes?: number\n processedCount?: number | null\n totalCount?: number | null\n}\ntype ConflictBody = { error?: string; lock?: ReindexLock }\ntype SearchSettingsResponse = { settings?: { fulltextReindexLock?: ReindexLock | null } }\n\nconst DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']\n\n/**\n * TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info.\n * Source: issue #2483.\n *\n * Route: POST /api/search/reindex (requireFeatures ['search.reindex']). The route\n * acquires a per-tenant DB lock BEFORE any indexing work and, in queue mode\n * (useQueue:true \u2014 the default), does NOT release it in `finally` (workers and\n * the heartbeat own it). So a first call holds the lock and a second call returns\n * 409 with the lock descriptor \u2014 independent of whether a fulltext backend is\n * configured, because the lock is taken before the strategy-availability check.\n * Integration specs run serially (workers:1), so no other test contends for the\n * shared lock; it is released in `finally` via the cancel endpoint.\n */\ntest.describe('TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info', () => {\n test('a second reindex while one is active is rejected with 409', async ({ request }) => {\n test.slow()\n test.setTimeout(120_000)\n\n let token: string | null = null\n\n try {\n token = await getAuthToken(request, 'admin')\n\n // Start from a clean lock state.\n await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)\n await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: DEFAULT_STRATEGIES },\n }).catch(() => undefined)\n\n // First reindex acquires (and, in queue mode, holds) the fulltext lock.\n const first = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })\n expect(first.status(), 'first reindex must not hit a pre-existing lock').not.toBe(409)\n expect([200, 503], 'first reindex starts (200) or reports backend unavailable (503)').toContain(first.status())\n\n const settings = await apiRequest(request, 'GET', '/api/search/settings', { token })\n expect(settings.ok(), 'search settings should be readable after starting reindex').toBeTruthy()\n const settingsBody = (await readJsonSafe<SearchSettingsResponse>(settings)) ?? {}\n expect(settingsBody.settings?.fulltextReindexLock?.type, 'first reindex should leave an observable fulltext lock').toBe('fulltext')\n\n // Second reindex is rejected while the first holds the lock.\n const second = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })\n expect(second.status(), 'a concurrent reindex must be rejected with 409').toBe(409)\n const body = (await readJsonSafe<ConflictBody>(second)) ?? {}\n expect(body.lock?.type, 'the 409 lock descriptor identifies the fulltext lock').toBe('fulltext')\n expect(typeof body.lock?.action, 'the lock reports its action').toBe('string')\n expect(typeof body.lock?.startedAt, 'the lock reports when it started').toBe('string')\n expect(typeof body.lock?.elapsedMinutes, 'the lock reports elapsed minutes').toBe('number')\n } finally {\n if (token) {\n await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)\n }\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAa7B,MAAM,qBAAqB,CAAC,YAAY,UAAU,QAAQ;AAe1D,KAAK,SAAS,yEAAyE,MAAM;AAC3F,OAAK,6DAA6D,OAAO,EAAE,QAAQ,MAAM;AACvF,SAAK,KAAK;AACV,SAAK,WAAW,IAAO;AAEvB,QAAI,QAAuB;AAE3B,QAAI;AACF,cAAQ,MAAM,aAAa,SAAS,OAAO;AAG3C,YAAM,WAAW,SAAS,QAAQ,8BAA8B,EAAE,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AAChG,YAAM,WAAW,SAAS,QAAQ,sCAAsC;AAAA,QACtE;AAAA,QACA,MAAM,EAAE,mBAAmB,mBAAmB;AAAA,MAChD,CAAC,EAAE,MAAM,MAAM,MAAS;AAGxB,YAAM,QAAQ,MAAM,WAAW,SAAS,QAAQ,uBAAuB,EAAE,OAAO,MAAM,EAAE,UAAU,KAAK,EAAE,CAAC;AAC1G,aAAO,MAAM,OAAO,GAAG,gDAAgD,EAAE,IAAI,KAAK,GAAG;AACrF,aAAO,CAAC,KAAK,GAAG,GAAG,iEAAiE,EAAE,UAAU,MAAM,OAAO,CAAC;AAE9G,YAAM,WAAW,MAAM,WAAW,SAAS,OAAO,wBAAwB,EAAE,MAAM,CAAC;AACnF,aAAO,SAAS,GAAG,GAAG,2DAA2D,EAAE,WAAW;AAC9F,YAAM,eAAgB,MAAM,aAAqC,QAAQ,KAAM,CAAC;AAChF,aAAO,aAAa,UAAU,qBAAqB,MAAM,wDAAwD,EAAE,KAAK,UAAU;AAGlI,YAAM,SAAS,MAAM,WAAW,SAAS,QAAQ,uBAAuB,EAAE,OAAO,MAAM,EAAE,UAAU,KAAK,EAAE,CAAC;AAC3G,aAAO,OAAO,OAAO,GAAG,gDAAgD,EAAE,KAAK,GAAG;AAClF,YAAM,OAAQ,MAAM,aAA2B,MAAM,KAAM,CAAC;AAC5D,aAAO,KAAK,MAAM,MAAM,sDAAsD,EAAE,KAAK,UAAU;AAC/F,aAAO,OAAO,KAAK,MAAM,QAAQ,6BAA6B,EAAE,KAAK,QAAQ;AAC7E,aAAO,OAAO,KAAK,MAAM,WAAW,kCAAkC,EAAE,KAAK,QAAQ;AACrF,aAAO,OAAO,KAAK,MAAM,gBAAgB,kCAAkC,EAAE,KAAK,QAAQ;AAAA,IAC5F,UAAE;AACA,UAAI,OAAO;AACT,cAAM,WAAW,SAAS,QAAQ,8BAA8B,EAAE,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAClG;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,55 @@
1
1
  import { z } from "zod";
2
+ import { hasAllFeatures } from "@open-mercato/shared/security/features";
3
+ class SearchToolAuthorizationError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = "SearchToolAuthorizationError";
7
+ }
8
+ }
9
+ function authorizeEntityAccess(entityType, ctx) {
10
+ const searchIndexer = ctx.container.resolve("searchIndexer");
11
+ const config = searchIndexer.getEntityConfig(entityType);
12
+ if (!config) {
13
+ throw new SearchToolAuthorizationError(
14
+ `[internal] Entity type "${entityType}" is not configured for search`
15
+ );
16
+ }
17
+ if (ctx.isSuperAdmin) return config;
18
+ const required = config.aclFeatures;
19
+ if (!required || required.length === 0) {
20
+ throw new SearchToolAuthorizationError(
21
+ `[internal] Entity type "${entityType}" does not declare aclFeatures; access denied`
22
+ );
23
+ }
24
+ if (!hasAllFeatures(ctx.userFeatures, required)) {
25
+ throw new SearchToolAuthorizationError(
26
+ `[internal] Insufficient permissions for entity "${entityType}". Required: ${required.join(", ")}`
27
+ );
28
+ }
29
+ return config;
30
+ }
31
+ function stripSensitiveFields(record, config) {
32
+ const sensitive = /* @__PURE__ */ new Set([
33
+ ...config.fieldPolicy?.hashOnly ?? [],
34
+ ...config.fieldPolicy?.excluded ?? []
35
+ ]);
36
+ if (sensitive.size === 0) return record;
37
+ const safe = {};
38
+ for (const [key, value] of Object.entries(record)) {
39
+ if (sensitive.has(key)) continue;
40
+ safe[key] = value;
41
+ }
42
+ return safe;
43
+ }
44
+ function isGroupByAllowed(field, config) {
45
+ const sensitive = /* @__PURE__ */ new Set([
46
+ ...config.fieldPolicy?.hashOnly ?? [],
47
+ ...config.fieldPolicy?.excluded ?? []
48
+ ]);
49
+ if (sensitive.has(field)) return false;
50
+ const searchable = config.fieldPolicy?.searchable ?? [];
51
+ return searchable.includes(field);
52
+ }
2
53
  const searchQueryTool = {
3
54
  name: "search_query",
4
55
  description: `Search across all data using hybrid search. Use this FIRST for finding records.
@@ -78,6 +129,7 @@ const searchGetTool = {
78
129
  if (!ctx.tenantId) {
79
130
  throw new Error("Tenant context is required");
80
131
  }
132
+ const entityConfig = authorizeEntityAccess(input.entityType, ctx);
81
133
  const queryEngine = ctx.container.resolve("queryEngine");
82
134
  const result = await queryEngine.query(input.entityType, {
83
135
  tenantId: ctx.tenantId,
@@ -86,8 +138,8 @@ const searchGetTool = {
86
138
  includeCustomFields: true,
87
139
  page: { page: 1, pageSize: 1 }
88
140
  });
89
- const record = result.items[0];
90
- if (!record) {
141
+ const rawRecord = result.items[0];
142
+ if (!rawRecord) {
91
143
  return {
92
144
  found: false,
93
145
  entityType: input.entityType,
@@ -95,6 +147,7 @@ const searchGetTool = {
95
147
  error: "Record not found"
96
148
  };
97
149
  }
150
+ const record = stripSensitiveFields(rawRecord, entityConfig);
98
151
  const customFields = {};
99
152
  const standardFields = {};
100
153
  for (const [key, value] of Object.entries(record)) {
@@ -177,6 +230,12 @@ const searchAggregateTool = {
177
230
  if (!ctx.tenantId) {
178
231
  throw new Error("Tenant context is required");
179
232
  }
233
+ const entityConfig = authorizeEntityAccess(input.entityType, ctx);
234
+ if (!isGroupByAllowed(input.groupBy, entityConfig)) {
235
+ throw new SearchToolAuthorizationError(
236
+ `[internal] Field "${input.groupBy}" is not an allowed grouping key for "${input.entityType}"`
237
+ );
238
+ }
180
239
  const queryEngine = ctx.container.resolve("queryEngine");
181
240
  const result = await queryEngine.query(input.entityType, {
182
241
  tenantId: ctx.tenantId,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/search/ai-tools.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\nimport type { SearchResult, SearchStrategyId } from '@open-mercato/shared/modules/search'\n\n/**\n * AI Tools definitions for the Search module.\n *\n * These tool definitions are discovered by the ai-assistant module's generator\n * and registered as MCP tools. The search module does not depend on ai-assistant.\n *\n * Tool Definition Format:\n * - name: Unique tool identifier (module_action format, no dots allowed)\n * - description: Human-readable description for AI clients\n * - inputSchema: Zod schema for input validation\n * - requiredFeatures: ACL features required to execute\n * - handler: Async function that executes the tool\n */\n\n/**\n * Tool context provided by the MCP server at execution time.\n */\ntype ToolContext = {\n tenantId: string | null\n organizationId: string | null\n userId: string | null\n container: {\n resolve: <T = unknown>(name: string) => T\n }\n userFeatures: string[]\n isSuperAdmin: boolean\n}\n\n/**\n * Tool definition structure.\n */\ntype AiToolDefinition = {\n name: string\n description: string\n inputSchema: z.ZodType<any>\n requiredFeatures?: string[]\n /**\n * Optional flag \u2014 when true, the tool is treated as a write by the\n * agent runtime and routed through the pending-action approval card.\n * Mirrors the public `AiToolDefinition.isMutation` flag without taking\n * a hard dependency on `@open-mercato/ai-assistant` here.\n */\n isMutation?: boolean\n handler: (input: any, ctx: ToolContext) => Promise<unknown>\n}\n\n// =============================================================================\n// Tool Definitions\n// =============================================================================\n\nconst searchQueryTool: AiToolDefinition = {\n name: 'search_query',\n description: `Search across all data using hybrid search. Use this FIRST for finding records.\n\nReturns: title, subtitle, entityType, recordId, url for each match.\nSearches customers, products, orders, deals, and more in one call.`,\n inputSchema: z.object({\n query: z.string().min(1).describe('The search query text'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .default(20)\n .describe('Maximum number of results to return (default: 20)'),\n entityTypes: z\n .array(z.string())\n .optional()\n .describe(\n 'Filter to specific entity types (e.g., [\"customers:customer_person_profile\", \"catalog:product\"])'\n ),\n strategies: z\n .array(z.enum(['fulltext', 'vector', 'tokens']))\n .optional()\n .describe('Specific search strategies to use (default: all available)'),\n }),\n requiredFeatures: ['search.global'],\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required for search')\n }\n\n const searchService = ctx.container.resolve<{\n search: (query: string, options: any) => Promise<SearchResult[]>\n }>('searchService')\n\n const results = await searchService.search(input.query, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n entityTypes: input.entityTypes,\n strategies: input.strategies as SearchStrategyId[],\n limit: input.limit,\n })\n\n return {\n query: input.query,\n totalResults: results.length,\n results: results.map((result) => ({\n entityType: result.entityId,\n recordId: result.recordId,\n score: Math.round(result.score * 100) / 100,\n source: result.source,\n title: result.presenter?.title ?? result.recordId,\n subtitle: result.presenter?.subtitle,\n url: result.url,\n })),\n }\n },\n}\n\nconst searchStatusTool: AiToolDefinition = {\n name: 'search_status',\n description:\n 'Get the current status of the search module, including available search strategies and their availability.',\n inputSchema: z.object({}),\n requiredFeatures: ['search.view'],\n handler: async (_input, ctx) => {\n const searchService = ctx.container.resolve<{\n getStrategies: () => Array<{\n id: string\n name: string\n priority: number\n isAvailable: () => Promise<boolean>\n }>\n getDefaultStrategies: () => string[]\n }>('searchService')\n\n const strategies = searchService.getStrategies()\n const defaultStrategies = searchService.getDefaultStrategies()\n\n const strategyStatus = await Promise.all(\n strategies.map(async (strategy) => ({\n id: strategy.id,\n name: strategy.name,\n priority: strategy.priority,\n isAvailable: await strategy.isAvailable(),\n isDefault: defaultStrategies.includes(strategy.id),\n }))\n )\n\n return {\n strategiesRegistered: strategies.length,\n defaultStrategies,\n strategies: strategyStatus,\n }\n },\n}\n\n// =============================================================================\n// search.get - Retrieve full record details by entity type and ID\n// =============================================================================\n\nconst searchGetTool: AiToolDefinition = {\n name: 'search_get',\n description: `Get full record details by entityType and recordId from search_query results.`,\n inputSchema: z.object({\n entityType: z\n .string()\n .describe('The entity type (e.g., \"customers:customer_company_profile\", \"customers:customer_deal\")'),\n recordId: z.string().describe('The record ID (UUID)'),\n }),\n requiredFeatures: ['search.view'],\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required')\n }\n\n const queryEngine = ctx.container.resolve<{\n query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>\n }>('queryEngine')\n\n const result = await queryEngine.query(input.entityType, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n filters: { id: input.recordId },\n includeCustomFields: true,\n page: { page: 1, pageSize: 1 },\n })\n\n const record = result.items[0] as Record<string, unknown> | undefined\n if (!record) {\n return {\n found: false,\n entityType: input.entityType,\n recordId: input.recordId,\n error: 'Record not found',\n }\n }\n\n // Extract custom fields\n const customFields: Record<string, unknown> = {}\n const standardFields: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(record)) {\n if (key.startsWith('cf:') || key.startsWith('cf_')) {\n customFields[key.replace(/^cf[:_]/, '')] = value\n } else {\n standardFields[key] = value\n }\n }\n\n // Build URL based on entity type\n let url: string | null = null\n const id = record.id ?? record.entity_id ?? input.recordId\n if (input.entityType.includes('person')) {\n url = `/backend/customers/people/${id}`\n } else if (input.entityType.includes('company')) {\n url = `/backend/customers/companies/${id}`\n } else if (input.entityType.includes('deal')) {\n url = `/backend/customers/deals/${id}`\n } else if (input.entityType.includes('activity')) {\n const entityId = record.entity_id ?? record.entityId\n url = entityId ? `/backend/customers/companies/${entityId}#activity-${id}` : null\n }\n\n return {\n found: true,\n entityType: input.entityType,\n recordId: input.recordId,\n record: standardFields,\n customFields: Object.keys(customFields).length > 0 ? customFields : undefined,\n url,\n }\n },\n}\n\n// =============================================================================\n// search.schema - Discover searchable entities and their fields\n// =============================================================================\n\nconst searchSchemaTool: AiToolDefinition = {\n name: 'search_schema',\n description:\n 'Discover searchable entities and their fields. Use this to learn what data can be searched and what fields are available for filtering.',\n inputSchema: z.object({\n entityType: z\n .string()\n .optional()\n .describe('Optional: Get schema for a specific entity type only'),\n }),\n requiredFeatures: ['search.view'],\n handler: async (input, ctx) => {\n const searchIndexer = ctx.container.resolve<{\n getAllEntityConfigs: () => Array<{\n entityId: string\n enabled?: boolean\n priority?: number\n strategies?: string[]\n fieldPolicy?: {\n searchable?: string[]\n hashOnly?: string[]\n excluded?: string[]\n }\n }>\n }>('searchIndexer')\n\n const allConfigs = searchIndexer.getAllEntityConfigs()\n const entities: Array<{\n entityId: string\n enabled: boolean\n priority: number\n strategies?: string[]\n searchableFields?: string[]\n hashOnlyFields?: string[]\n excludedFields?: string[]\n }> = []\n\n for (const entityConfig of allConfigs) {\n if (input.entityType && entityConfig.entityId !== input.entityType) {\n continue\n }\n\n entities.push({\n entityId: entityConfig.entityId,\n enabled: entityConfig.enabled !== false,\n priority: entityConfig.priority ?? 5,\n strategies: entityConfig.strategies,\n searchableFields: entityConfig.fieldPolicy?.searchable,\n hashOnlyFields: entityConfig.fieldPolicy?.hashOnly,\n excludedFields: entityConfig.fieldPolicy?.excluded,\n })\n }\n\n if (input.entityType && entities.length === 0) {\n return {\n found: false,\n entityType: input.entityType,\n error: 'Entity type not configured for search',\n }\n }\n\n return {\n totalEntities: entities.length,\n entities: entities.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)),\n }\n },\n}\n\n// =============================================================================\n// search.aggregate - Get counts grouped by field values\n// =============================================================================\n\nconst searchAggregateTool: AiToolDefinition = {\n name: 'search_aggregate',\n description:\n 'Get record counts grouped by a field value. Useful for analytics like \"how many deals by stage?\" or \"customers by status\". Samples up to 100 records \u2014 percentages may not reflect the full dataset for large entity sets.',\n inputSchema: z.object({\n entityType: z\n .string()\n .describe('The entity type to aggregate (e.g., \"customers:customer_deal\")'),\n groupBy: z\n .string()\n .describe('The field to group by (e.g., \"status\", \"industry\", \"pipeline_stage\")'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .default(20)\n .describe('Maximum number of buckets to return (default: 20)'),\n }),\n requiredFeatures: ['search.view'],\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required')\n }\n\n const queryEngine = ctx.container.resolve<{\n query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>\n }>('queryEngine')\n\n // Fetch records and aggregate in memory\n // Note: For large datasets, this should use database GROUP BY\n const result = await queryEngine.query(input.entityType, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n page: { page: 1, pageSize: 100 },\n })\n\n const counts = new Map<string | null, number>()\n for (const item of result.items as Record<string, unknown>[]) {\n const value = item[input.groupBy]\n const key = value === null || value === undefined ? null : String(value)\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n\n const total = result.items.length\n const buckets = Array.from(counts.entries())\n .map(([value, count]) => ({\n value,\n count,\n percentage: Math.round((count / total) * 100 * 100) / 100,\n }))\n .sort((a, b) => b.count - a.count)\n .slice(0, input.limit)\n\n return {\n entityType: input.entityType,\n groupBy: input.groupBy,\n total,\n buckets,\n }\n },\n}\n\nconst searchReindexTool: AiToolDefinition = {\n name: 'search_reindex',\n description:\n 'Trigger a reindex operation for search data. This rebuilds the search index for the specified entity type or all entities.',\n inputSchema: z.object({\n entityType: z\n .string()\n .optional()\n .describe(\n 'Specific entity type to reindex (e.g., \"customers:customer_person_profile\"). If not provided, reindexes all entities.'\n ),\n strategy: z\n .enum(['fulltext', 'vector'])\n .optional()\n .default('fulltext')\n .describe('Which search strategy to reindex (default: fulltext)'),\n recreateIndex: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to recreate the index from scratch (default: false)'),\n }),\n requiredFeatures: ['search.reindex'],\n // Reindex changes server-side index state \u2014 must surface as a write so\n // any agent that whitelists it routes through the approval card.\n isMutation: true,\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required for reindex')\n }\n\n const searchIndexer = ctx.container.resolve<{\n reindexEntityToFulltext: (params: any) => Promise<any>\n reindexAllToFulltext: (params: any) => Promise<any>\n reindexEntityToVector: (params: any) => Promise<void>\n reindexAllToVector: (params: any) => Promise<void>\n }>('searchIndexer')\n\n const baseParams = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n recreateIndex: input.recreateIndex,\n useQueue: true,\n }\n\n if (input.strategy === 'vector') {\n if (input.entityType) {\n await searchIndexer.reindexEntityToVector({\n ...baseParams,\n entityId: input.entityType,\n })\n return {\n status: 'started',\n strategy: 'vector',\n entityType: input.entityType,\n message: `Vector reindex started for ${input.entityType}`,\n }\n } else {\n await searchIndexer.reindexAllToVector(baseParams)\n return {\n status: 'started',\n strategy: 'vector',\n entityType: 'all',\n message: 'Vector reindex started for all entities',\n }\n }\n } else {\n if (input.entityType) {\n const result = await searchIndexer.reindexEntityToFulltext({\n ...baseParams,\n entityId: input.entityType,\n })\n return {\n status: 'completed',\n strategy: 'fulltext',\n entityType: input.entityType,\n ...result,\n }\n } else {\n const result = await searchIndexer.reindexAllToFulltext(baseParams)\n return {\n status: 'completed',\n strategy: 'fulltext',\n entityType: 'all',\n ...result,\n }\n }\n }\n },\n}\n\n// =============================================================================\n// Export\n// =============================================================================\n\n/**\n * All AI tools exported by the search module.\n * Discovered by ai-assistant module's generator.\n */\nexport const aiTools = [\n searchQueryTool,\n searchStatusTool,\n searchGetTool,\n searchSchemaTool,\n searchAggregateTool,\n searchReindexTool,\n]\n\nexport default aiTools\n"],
5
- "mappings": "AAAA,SAAS,SAAS;A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ACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAUO,MAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAO,mBAAQ;",
4
+ "sourcesContent": ["import { z } from 'zod'\nimport type {\n SearchEntityConfig,\n SearchResult,\n SearchStrategyId,\n} from '@open-mercato/shared/modules/search'\nimport { hasAllFeatures } from '@open-mercato/shared/security/features'\n\n/**\n * AI Tools definitions for the Search module.\n *\n * These tool definitions are discovered by the ai-assistant module's generator\n * and registered as MCP tools. The search module does not depend on ai-assistant.\n *\n * Tool Definition Format:\n * - name: Unique tool identifier (module_action format, no dots allowed)\n * - description: Human-readable description for AI clients\n * - inputSchema: Zod schema for input validation\n * - requiredFeatures: ACL features required to execute\n * - handler: Async function that executes the tool\n */\n\n/**\n * Tool context provided by the MCP server at execution time.\n */\ntype ToolContext = {\n tenantId: string | null\n organizationId: string | null\n userId: string | null\n container: {\n resolve: <T = unknown>(name: string) => T\n }\n userFeatures: string[]\n isSuperAdmin: boolean\n}\n\n/**\n * Tool definition structure.\n */\ntype AiToolDefinition = {\n name: string\n description: string\n inputSchema: z.ZodType<any>\n requiredFeatures?: string[]\n /**\n * Optional flag \u2014 when true, the tool is treated as a write by the\n * agent runtime and routed through the pending-action approval card.\n * Mirrors the public `AiToolDefinition.isMutation` flag without taking\n * a hard dependency on `@open-mercato/ai-assistant` here.\n */\n isMutation?: boolean\n handler: (input: any, ctx: ToolContext) => Promise<unknown>\n}\n\n/**\n * Minimal shape of the `searchIndexer` DI service consumed by the per-entity\n * ACL / field-policy resolution below. Kept local to avoid importing the full\n * `SearchIndexer` class into the tool module.\n */\ntype SearchIndexerLike = {\n getEntityConfig: (entityId: string) => SearchEntityConfig | undefined\n}\n\nclass SearchToolAuthorizationError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SearchToolAuthorizationError'\n }\n}\n\n/**\n * Resolve the search config for an entity type and enforce the per-entity view\n * feature(s). Data-returning tools (`search_get` / `search_aggregate`) MUST NOT\n * rely on the search-administration `search.view` feature to gate record reads.\n *\n * Fails closed: when the entity is not configured for search, or has no\n * `aclFeatures` declared, access is denied so records are never exposed without\n * an explicit owning-module grant.\n */\nfunction authorizeEntityAccess(entityType: string, ctx: ToolContext): SearchEntityConfig {\n const searchIndexer = ctx.container.resolve<SearchIndexerLike>('searchIndexer')\n const config = searchIndexer.getEntityConfig(entityType)\n\n if (!config) {\n throw new SearchToolAuthorizationError(\n `[internal] Entity type \"${entityType}\" is not configured for search`\n )\n }\n\n if (ctx.isSuperAdmin) return config\n\n const required = config.aclFeatures\n if (!required || required.length === 0) {\n throw new SearchToolAuthorizationError(\n `[internal] Entity type \"${entityType}\" does not declare aclFeatures; access denied`\n )\n }\n\n if (!hasAllFeatures(ctx.userFeatures, required)) {\n throw new SearchToolAuthorizationError(\n `[internal] Insufficient permissions for entity \"${entityType}\". Required: ${required.join(', ')}`\n )\n }\n\n return config\n}\n\n/**\n * Strip fields that the entity's field policy marks as sensitive\n * (`hashOnly` exact-match PII or fully `excluded`) from a query-engine record.\n * Defense-in-depth so even an authorized caller never receives decrypted PII or\n * fields a `fieldPolicy` keeps out of search.\n */\nfunction stripSensitiveFields(\n record: Record<string, unknown>,\n config: SearchEntityConfig\n): Record<string, unknown> {\n const sensitive = new Set<string>([\n ...(config.fieldPolicy?.hashOnly ?? []),\n ...(config.fieldPolicy?.excluded ?? []),\n ])\n if (sensitive.size === 0) return record\n const safe: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(record)) {\n if (sensitive.has(key)) continue\n safe[key] = value\n }\n return safe\n}\n\n/**\n * Determine whether a field is a safe aggregation grouping key for an entity.\n * Only fields explicitly declared `searchable` are allowed; `hashOnly` and\n * `excluded` (PII / sensitive) fields can never be enumerated via group-by.\n */\nfunction isGroupByAllowed(field: string, config: SearchEntityConfig): boolean {\n const sensitive = new Set<string>([\n ...(config.fieldPolicy?.hashOnly ?? []),\n ...(config.fieldPolicy?.excluded ?? []),\n ])\n if (sensitive.has(field)) return false\n const searchable = config.fieldPolicy?.searchable ?? []\n return searchable.includes(field)\n}\n\n// =============================================================================\n// Tool Definitions\n// =============================================================================\n\nconst searchQueryTool: AiToolDefinition = {\n name: 'search_query',\n description: `Search across all data using hybrid search. Use this FIRST for finding records.\n\nReturns: title, subtitle, entityType, recordId, url for each match.\nSearches customers, products, orders, deals, and more in one call.`,\n inputSchema: z.object({\n query: z.string().min(1).describe('The search query text'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .default(20)\n .describe('Maximum number of results to return (default: 20)'),\n entityTypes: z\n .array(z.string())\n .optional()\n .describe(\n 'Filter to specific entity types (e.g., [\"customers:customer_person_profile\", \"catalog:product\"])'\n ),\n strategies: z\n .array(z.enum(['fulltext', 'vector', 'tokens']))\n .optional()\n .describe('Specific search strategies to use (default: all available)'),\n }),\n requiredFeatures: ['search.global'],\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required for search')\n }\n\n const searchService = ctx.container.resolve<{\n search: (query: string, options: any) => Promise<SearchResult[]>\n }>('searchService')\n\n const results = await searchService.search(input.query, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n entityTypes: input.entityTypes,\n strategies: input.strategies as SearchStrategyId[],\n limit: input.limit,\n })\n\n return {\n query: input.query,\n totalResults: results.length,\n results: results.map((result) => ({\n entityType: result.entityId,\n recordId: result.recordId,\n score: Math.round(result.score * 100) / 100,\n source: result.source,\n title: result.presenter?.title ?? result.recordId,\n subtitle: result.presenter?.subtitle,\n url: result.url,\n })),\n }\n },\n}\n\nconst searchStatusTool: AiToolDefinition = {\n name: 'search_status',\n description:\n 'Get the current status of the search module, including available search strategies and their availability.',\n inputSchema: z.object({}),\n requiredFeatures: ['search.view'],\n handler: async (_input, ctx) => {\n const searchService = ctx.container.resolve<{\n getStrategies: () => Array<{\n id: string\n name: string\n priority: number\n isAvailable: () => Promise<boolean>\n }>\n getDefaultStrategies: () => string[]\n }>('searchService')\n\n const strategies = searchService.getStrategies()\n const defaultStrategies = searchService.getDefaultStrategies()\n\n const strategyStatus = await Promise.all(\n strategies.map(async (strategy) => ({\n id: strategy.id,\n name: strategy.name,\n priority: strategy.priority,\n isAvailable: await strategy.isAvailable(),\n isDefault: defaultStrategies.includes(strategy.id),\n }))\n )\n\n return {\n strategiesRegistered: strategies.length,\n defaultStrategies,\n strategies: strategyStatus,\n }\n },\n}\n\n// =============================================================================\n// search.get - Retrieve full record details by entity type and ID\n// =============================================================================\n\nconst searchGetTool: AiToolDefinition = {\n name: 'search_get',\n description: `Get full record details by entityType and recordId from search_query results.`,\n inputSchema: z.object({\n entityType: z\n .string()\n .describe('The entity type (e.g., \"customers:customer_company_profile\", \"customers:customer_deal\")'),\n recordId: z.string().describe('The record ID (UUID)'),\n }),\n requiredFeatures: ['search.view'],\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required')\n }\n\n const entityConfig = authorizeEntityAccess(input.entityType, ctx)\n\n const queryEngine = ctx.container.resolve<{\n query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>\n }>('queryEngine')\n\n const result = await queryEngine.query(input.entityType, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n filters: { id: input.recordId },\n includeCustomFields: true,\n page: { page: 1, pageSize: 1 },\n })\n\n const rawRecord = result.items[0] as Record<string, unknown> | undefined\n if (!rawRecord) {\n return {\n found: false,\n entityType: input.entityType,\n recordId: input.recordId,\n error: 'Record not found',\n }\n }\n\n const record = stripSensitiveFields(rawRecord, entityConfig)\n\n // Extract custom fields\n const customFields: Record<string, unknown> = {}\n const standardFields: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(record)) {\n if (key.startsWith('cf:') || key.startsWith('cf_')) {\n customFields[key.replace(/^cf[:_]/, '')] = value\n } else {\n standardFields[key] = value\n }\n }\n\n // Build URL based on entity type\n let url: string | null = null\n const id = record.id ?? record.entity_id ?? input.recordId\n if (input.entityType.includes('person')) {\n url = `/backend/customers/people/${id}`\n } else if (input.entityType.includes('company')) {\n url = `/backend/customers/companies/${id}`\n } else if (input.entityType.includes('deal')) {\n url = `/backend/customers/deals/${id}`\n } else if (input.entityType.includes('activity')) {\n const entityId = record.entity_id ?? record.entityId\n url = entityId ? `/backend/customers/companies/${entityId}#activity-${id}` : null\n }\n\n return {\n found: true,\n entityType: input.entityType,\n recordId: input.recordId,\n record: standardFields,\n customFields: Object.keys(customFields).length > 0 ? customFields : undefined,\n url,\n }\n },\n}\n\n// =============================================================================\n// search.schema - Discover searchable entities and their fields\n// =============================================================================\n\nconst searchSchemaTool: AiToolDefinition = {\n name: 'search_schema',\n description:\n 'Discover searchable entities and their fields. Use this to learn what data can be searched and what fields are available for filtering.',\n inputSchema: z.object({\n entityType: z\n .string()\n .optional()\n .describe('Optional: Get schema for a specific entity type only'),\n }),\n requiredFeatures: ['search.view'],\n handler: async (input, ctx) => {\n const searchIndexer = ctx.container.resolve<{\n getAllEntityConfigs: () => Array<{\n entityId: string\n enabled?: boolean\n priority?: number\n strategies?: string[]\n fieldPolicy?: {\n searchable?: string[]\n hashOnly?: string[]\n excluded?: string[]\n }\n }>\n }>('searchIndexer')\n\n const allConfigs = searchIndexer.getAllEntityConfigs()\n const entities: Array<{\n entityId: string\n enabled: boolean\n priority: number\n strategies?: string[]\n searchableFields?: string[]\n hashOnlyFields?: string[]\n excludedFields?: string[]\n }> = []\n\n for (const entityConfig of allConfigs) {\n if (input.entityType && entityConfig.entityId !== input.entityType) {\n continue\n }\n\n entities.push({\n entityId: entityConfig.entityId,\n enabled: entityConfig.enabled !== false,\n priority: entityConfig.priority ?? 5,\n strategies: entityConfig.strategies,\n searchableFields: entityConfig.fieldPolicy?.searchable,\n hashOnlyFields: entityConfig.fieldPolicy?.hashOnly,\n excludedFields: entityConfig.fieldPolicy?.excluded,\n })\n }\n\n if (input.entityType && entities.length === 0) {\n return {\n found: false,\n entityType: input.entityType,\n error: 'Entity type not configured for search',\n }\n }\n\n return {\n totalEntities: entities.length,\n entities: entities.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0)),\n }\n },\n}\n\n// =============================================================================\n// search.aggregate - Get counts grouped by field values\n// =============================================================================\n\nconst searchAggregateTool: AiToolDefinition = {\n name: 'search_aggregate',\n description:\n 'Get record counts grouped by a field value. Useful for analytics like \"how many deals by stage?\" or \"customers by status\". Samples up to 100 records \u2014 percentages may not reflect the full dataset for large entity sets.',\n inputSchema: z.object({\n entityType: z\n .string()\n .describe('The entity type to aggregate (e.g., \"customers:customer_deal\")'),\n groupBy: z\n .string()\n .describe('The field to group by (e.g., \"status\", \"industry\", \"pipeline_stage\")'),\n limit: z\n .number()\n .int()\n .min(1)\n .max(100)\n .optional()\n .default(20)\n .describe('Maximum number of buckets to return (default: 20)'),\n }),\n requiredFeatures: ['search.view'],\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required')\n }\n\n const entityConfig = authorizeEntityAccess(input.entityType, ctx)\n\n if (!isGroupByAllowed(input.groupBy, entityConfig)) {\n throw new SearchToolAuthorizationError(\n `[internal] Field \"${input.groupBy}\" is not an allowed grouping key for \"${input.entityType}\"`\n )\n }\n\n const queryEngine = ctx.container.resolve<{\n query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>\n }>('queryEngine')\n\n // Fetch records and aggregate in memory\n // Note: For large datasets, this should use database GROUP BY\n const result = await queryEngine.query(input.entityType, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n page: { page: 1, pageSize: 100 },\n })\n\n const counts = new Map<string | null, number>()\n for (const item of result.items as Record<string, unknown>[]) {\n const value = item[input.groupBy]\n const key = value === null || value === undefined ? null : String(value)\n counts.set(key, (counts.get(key) ?? 0) + 1)\n }\n\n const total = result.items.length\n const buckets = Array.from(counts.entries())\n .map(([value, count]) => ({\n value,\n count,\n percentage: Math.round((count / total) * 100 * 100) / 100,\n }))\n .sort((a, b) => b.count - a.count)\n .slice(0, input.limit)\n\n return {\n entityType: input.entityType,\n groupBy: input.groupBy,\n total,\n buckets,\n }\n },\n}\n\nconst searchReindexTool: AiToolDefinition = {\n name: 'search_reindex',\n description:\n 'Trigger a reindex operation for search data. This rebuilds the search index for the specified entity type or all entities.',\n inputSchema: z.object({\n entityType: z\n .string()\n .optional()\n .describe(\n 'Specific entity type to reindex (e.g., \"customers:customer_person_profile\"). If not provided, reindexes all entities.'\n ),\n strategy: z\n .enum(['fulltext', 'vector'])\n .optional()\n .default('fulltext')\n .describe('Which search strategy to reindex (default: fulltext)'),\n recreateIndex: z\n .boolean()\n .optional()\n .default(false)\n .describe('Whether to recreate the index from scratch (default: false)'),\n }),\n requiredFeatures: ['search.reindex'],\n // Reindex changes server-side index state \u2014 must surface as a write so\n // any agent that whitelists it routes through the approval card.\n isMutation: true,\n handler: async (input, ctx) => {\n if (!ctx.tenantId) {\n throw new Error('Tenant context is required for reindex')\n }\n\n const searchIndexer = ctx.container.resolve<{\n reindexEntityToFulltext: (params: any) => Promise<any>\n reindexAllToFulltext: (params: any) => Promise<any>\n reindexEntityToVector: (params: any) => Promise<void>\n reindexAllToVector: (params: any) => Promise<void>\n }>('searchIndexer')\n\n const baseParams = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n recreateIndex: input.recreateIndex,\n useQueue: true,\n }\n\n if (input.strategy === 'vector') {\n if (input.entityType) {\n await searchIndexer.reindexEntityToVector({\n ...baseParams,\n entityId: input.entityType,\n })\n return {\n status: 'started',\n strategy: 'vector',\n entityType: input.entityType,\n message: `Vector reindex started for ${input.entityType}`,\n }\n } else {\n await searchIndexer.reindexAllToVector(baseParams)\n return {\n status: 'started',\n strategy: 'vector',\n entityType: 'all',\n message: 'Vector reindex started for all entities',\n }\n }\n } else {\n if (input.entityType) {\n const result = await searchIndexer.reindexEntityToFulltext({\n ...baseParams,\n entityId: input.entityType,\n })\n return {\n status: 'completed',\n strategy: 'fulltext',\n entityType: input.entityType,\n ...result,\n }\n } else {\n const result = await searchIndexer.reindexAllToFulltext(baseParams)\n return {\n status: 'completed',\n strategy: 'fulltext',\n entityType: 'all',\n ...result,\n }\n }\n }\n },\n}\n\n// =============================================================================\n// Export\n// =============================================================================\n\n/**\n * All AI tools exported by the search module.\n * Discovered by ai-assistant module's generator.\n */\nexport const aiTools = [\n searchQueryTool,\n searchStatusTool,\n searchGetTool,\n searchSchemaTool,\n searchAggregateTool,\n searchReindexTool,\n]\n\nexport default aiTools\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAMlB,SAAS,sBAAsB;AAyD/B,MAAM,qCAAqC,MAAM;AAAA,EAC/C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAWA,SAAS,sBAAsB,YAAoB,KAAsC;AACvF,QAAM,gBAAgB,IAAI,UAAU,QAA2B,eAAe;AAC9E,QAAM,SAAS,cAAc,gBAAgB,UAAU;AAEvD,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,2BAA2B,UAAU;AAAA,IACvC;AAAA,EACF;AAEA,MAAI,IAAI,aAAc,QAAO;AAE7B,QAAM,WAAW,OAAO;AACxB,MAAI,CAAC,YAAY,SAAS,WAAW,GAAG;AACtC,UAAM,IAAI;AAAA,MACR,2BAA2B,UAAU;AAAA,IACvC;AAAA,EACF;AAEA,MAAI,CAAC,eAAe,IAAI,cAAc,QAAQ,GAAG;AAC/C,UAAM,IAAI;AAAA,MACR,mDAAmD,UAAU,gBAAgB,SAAS,KAAK,IAAI,CAAC;AAAA,IAClG;AAAA,EACF;AAEA,SAAO;AACT;AAQA,SAAS,qBACP,QACA,QACyB;AACzB,QAAM,YAAY,oBAAI,IAAY;AAAA,IAChC,GAAI,OAAO,aAAa,YAAY,CAAC;AAAA,IACrC,GAAI,OAAO,aAAa,YAAY,CAAC;AAAA,EACvC,CAAC;AACD,MAAI,UAAU,SAAS,EAAG,QAAO;AACjC,QAAM,OAAgC,CAAC;AACvC,aAAW,C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AAA,UACH,UAAU,MAAM;AAAA,QAClB,CAAC;AACD,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,UAAU;AAAA,UACV,YAAY,MAAM;AAAA,UAClB,SAAS,8BAA8B,MAAM,UAAU;AAAA,QACzD;AAAA,MACF,OAAO;AACL,cAAM,cAAc,mBAAmB,UAAU;AACjD,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF,OAAO;AACL,UAAI,MAAM,YAAY;AACpB,cAAM,SAAS,MAAM,cAAc,wBAAwB;AAAA,UACzD,GAAG;AAAA,UACH,UAAU,MAAM;AAAA,QAClB,CAAC;AACD,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,UAAU;AAAA,UACV,YAAY,MAAM;AAAA,UAClB,GAAG;AAAA,QACL;AAAA,MACF,OAAO;AACL,cAAM,SAAS,MAAM,cAAc,qBAAqB,UAAU;AAClE,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,UAAU;AAAA,UACV,YAAY;AAAA,UACZ,GAAG;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAUO,MAAM,UAAU;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAO,mBAAQ;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/search",
3
- "version": "0.6.5-develop.4964.1.ae0edca575",
3
+ "version": "0.6.5-develop.5048.1.fd82f4ae17",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "exports": {
@@ -126,9 +126,9 @@
126
126
  "zod": "^4.4.3"
127
127
  },
128
128
  "peerDependencies": {
129
- "@open-mercato/core": "0.6.5-develop.4964.1.ae0edca575",
130
- "@open-mercato/queue": "0.6.5-develop.4964.1.ae0edca575",
131
- "@open-mercato/shared": "0.6.5-develop.4964.1.ae0edca575"
129
+ "@open-mercato/core": "0.6.5-develop.5048.1.fd82f4ae17",
130
+ "@open-mercato/queue": "0.6.5-develop.5048.1.fd82f4ae17",
131
+ "@open-mercato/shared": "0.6.5-develop.5048.1.fd82f4ae17"
132
132
  },
133
133
  "devDependencies": {
134
134
  "@types/jest": "^30.0.0",
@@ -463,7 +463,7 @@ yarn mercato search worker fulltext-indexing --concurrency=5
463
463
 
464
464
  ### Debug Logging
465
465
 
466
- Set `OM_SEARCH_DEBUG=true` to enable verbose debug logging for the search module. This outputs detailed information about indexing operations, strategy selection, and error handling. Errors are always logged regardless of this flag.
466
+ Set `OM_SEARCH_DEBUG=true` to enable verbose debug logging for the search module. This outputs information about indexing operations, strategy selection, and error handling. Debug output is redacted: it includes field names, token hashes, and counts, but never raw token text, document values, or decrypted PII. Errors are always logged regardless of this flag.
467
467
 
468
468
  ```env
469
469
  OM_SEARCH_DEBUG=true
@@ -24,9 +24,10 @@ const DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']
24
24
  test.describe('TC-SEARCH-006: global search honors saved strategy config over URL override', () => {
25
25
  test('persisted enabledStrategies wins over the strategies URL parameter', async ({ request }) => {
26
26
  test.slow()
27
+ test.setTimeout(120_000)
27
28
 
28
29
  let token: string | null = null
29
- let originalStrategies: string[] | null = null
30
+ let originalStrategies: string[] | null = DEFAULT_STRATEGIES
30
31
 
31
32
  try {
32
33
  token = await getAuthToken(request, 'admin')
@@ -11,6 +11,9 @@ type ReindexLock = {
11
11
  totalCount?: number | null
12
12
  }
13
13
  type ConflictBody = { error?: string; lock?: ReindexLock }
14
+ type SearchSettingsResponse = { settings?: { fulltextReindexLock?: ReindexLock | null } }
15
+
16
+ const DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']
14
17
 
15
18
  /**
16
19
  * TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info.
@@ -28,6 +31,7 @@ type ConflictBody = { error?: string; lock?: ReindexLock }
28
31
  test.describe('TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info', () => {
29
32
  test('a second reindex while one is active is rejected with 409', async ({ request }) => {
30
33
  test.slow()
34
+ test.setTimeout(120_000)
31
35
 
32
36
  let token: string | null = null
33
37
 
@@ -36,12 +40,21 @@ test.describe('TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock
36
40
 
37
41
  // Start from a clean lock state.
38
42
  await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)
43
+ await apiRequest(request, 'POST', '/api/search/settings/global-search', {
44
+ token,
45
+ data: { enabledStrategies: DEFAULT_STRATEGIES },
46
+ }).catch(() => undefined)
39
47
 
40
48
  // First reindex acquires (and, in queue mode, holds) the fulltext lock.
41
49
  const first = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })
42
50
  expect(first.status(), 'first reindex must not hit a pre-existing lock').not.toBe(409)
43
51
  expect([200, 503], 'first reindex starts (200) or reports backend unavailable (503)').toContain(first.status())
44
52
 
53
+ const settings = await apiRequest(request, 'GET', '/api/search/settings', { token })
54
+ expect(settings.ok(), 'search settings should be readable after starting reindex').toBeTruthy()
55
+ const settingsBody = (await readJsonSafe<SearchSettingsResponse>(settings)) ?? {}
56
+ expect(settingsBody.settings?.fulltextReindexLock?.type, 'first reindex should leave an observable fulltext lock').toBe('fulltext')
57
+
45
58
  // Second reindex is rejected while the first holds the lock.
46
59
  const second = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })
47
60
  expect(second.status(), 'a concurrent reindex must be rejected with 409').toBe(409)
@@ -3,16 +3,35 @@ import { aiTools } from '../ai-tools'
3
3
  const aggregateTool = aiTools.find((t) => t.name === 'search_aggregate')
4
4
  if (!aggregateTool) throw new Error('search_aggregate tool not found in aiTools — was it renamed?')
5
5
 
6
- function makeCtx(queryResult: { items: unknown[]; total: number }) {
6
+ const ENTITY_CONFIGS: Record<string, { aclFeatures: string[]; fieldPolicy: { searchable: string[]; hashOnly?: string[]; excluded?: string[] } }> = {
7
+ 'customers:customer_deal': {
8
+ aclFeatures: ['customers.deals.view'],
9
+ fieldPolicy: { searchable: ['title', 'status', 'pipeline_stage', 'source'], hashOnly: [], excluded: ['value_amount'] },
10
+ },
11
+ 'catalog:product': {
12
+ aclFeatures: ['catalog.products.view'],
13
+ fieldPolicy: { searchable: ['category', 'status'], hashOnly: [], excluded: [] },
14
+ },
15
+ }
16
+
17
+ const DEFAULT_FEATURES = ['search.view', 'customers.deals.view', 'catalog.products.view']
18
+
19
+ function makeCtx(
20
+ queryResult: { items: unknown[]; total: number },
21
+ overrides: { userFeatures?: string[]; isSuperAdmin?: boolean } = {},
22
+ ) {
7
23
  const mockQuery = jest.fn().mockResolvedValue(queryResult)
24
+ const searchIndexer = {
25
+ getEntityConfig: (entityId: string) => ENTITY_CONFIGS[entityId],
26
+ }
8
27
  const ctx = {
9
28
  tenantId: 'tenant-1',
10
29
  organizationId: 'org-1',
11
30
  userId: null,
12
- userFeatures: ['search.view'],
13
- isSuperAdmin: false,
31
+ userFeatures: overrides.userFeatures ?? DEFAULT_FEATURES,
32
+ isSuperAdmin: overrides.isSuperAdmin ?? false,
14
33
  container: {
15
- resolve: (_name: string) => ({ query: mockQuery }),
34
+ resolve: (name: string) => (name === 'searchIndexer' ? searchIndexer : { query: mockQuery }),
16
35
  },
17
36
  }
18
37
  return { ctx, mockQuery }
@@ -110,4 +129,70 @@ describe('search_aggregate tool', () => {
110
129
  aggregateTool.handler({ entityType: 'customers:customer_deal', groupBy: 'status', limit: 20 }, noTenantCtx),
111
130
  ).rejects.toThrow('Tenant context is required')
112
131
  })
132
+
133
+ it('denies callers holding only search.view without the per-entity view feature', async () => {
134
+ const { ctx, mockQuery } = makeCtx({ items: [{ status: 'open' }], total: 1 }, { userFeatures: ['search.view'] })
135
+
136
+ await expect(
137
+ aggregateTool.handler({ entityType: 'customers:customer_deal', groupBy: 'status', limit: 20 }, ctx),
138
+ ).rejects.toThrow(/Insufficient permissions/)
139
+ expect(mockQuery).not.toHaveBeenCalled()
140
+ })
141
+
142
+ it('allows callers holding the per-entity view feature', async () => {
143
+ const { ctx, mockQuery } = makeCtx({ items: [{ status: 'open' }], total: 1 }, { userFeatures: ['customers.deals.view'] })
144
+
145
+ const result = await aggregateTool.handler(
146
+ { entityType: 'customers:customer_deal', groupBy: 'status', limit: 20 },
147
+ ctx,
148
+ ) as { total: number }
149
+ expect(result.total).toBe(1)
150
+ expect(mockQuery).toHaveBeenCalled()
151
+ })
152
+
153
+ it('honors wildcard module grants for the per-entity view feature', async () => {
154
+ const { ctx } = makeCtx({ items: [{ status: 'open' }], total: 1 }, { userFeatures: ['customers.*'] })
155
+
156
+ const result = await aggregateTool.handler(
157
+ { entityType: 'customers:customer_deal', groupBy: 'status', limit: 20 },
158
+ ctx,
159
+ ) as { total: number }
160
+ expect(result.total).toBe(1)
161
+ })
162
+
163
+ it('allows super admins regardless of features', async () => {
164
+ const { ctx } = makeCtx({ items: [{ status: 'open' }], total: 1 }, { userFeatures: [], isSuperAdmin: true })
165
+
166
+ const result = await aggregateTool.handler(
167
+ { entityType: 'customers:customer_deal', groupBy: 'status', limit: 20 },
168
+ ctx,
169
+ ) as { total: number }
170
+ expect(result.total).toBe(1)
171
+ })
172
+
173
+ it('rejects groupBy on an excluded (sensitive) field', async () => {
174
+ const { ctx, mockQuery } = makeCtx({ items: [{ value_amount: 100 }], total: 1 })
175
+
176
+ await expect(
177
+ aggregateTool.handler({ entityType: 'customers:customer_deal', groupBy: 'value_amount', limit: 20 }, ctx),
178
+ ).rejects.toThrow(/not an allowed grouping key/)
179
+ expect(mockQuery).not.toHaveBeenCalled()
180
+ })
181
+
182
+ it('rejects groupBy on a field not in the searchable allowlist (e.g. PII enumeration)', async () => {
183
+ const { ctx, mockQuery } = makeCtx({ items: [{ email: 'a@b.c' }], total: 1 })
184
+
185
+ await expect(
186
+ aggregateTool.handler({ entityType: 'customers:customer_deal', groupBy: 'email', limit: 20 }, ctx),
187
+ ).rejects.toThrow(/not an allowed grouping key/)
188
+ expect(mockQuery).not.toHaveBeenCalled()
189
+ })
190
+
191
+ it('fails closed for entity types not configured for search', async () => {
192
+ const { ctx } = makeCtx({ items: [], total: 0 })
193
+
194
+ await expect(
195
+ aggregateTool.handler({ entityType: 'secret:unconfigured', groupBy: 'status', limit: 20 }, ctx),
196
+ ).rejects.toThrow(/not configured for search/)
197
+ })
113
198
  })
@@ -0,0 +1,118 @@
1
+ import { aiTools } from '../ai-tools'
2
+
3
+ const getTool = aiTools.find((t) => t.name === 'search_get')
4
+ if (!getTool) throw new Error('search_get tool not found in aiTools — was it renamed?')
5
+
6
+ const PERSON_CONFIG = {
7
+ aclFeatures: ['customers.people.view'],
8
+ fieldPolicy: {
9
+ searchable: ['first_name', 'last_name'],
10
+ hashOnly: ['primary_email', 'primary_phone'],
11
+ excluded: ['ssn', 'date_of_birth'],
12
+ },
13
+ }
14
+
15
+ function makeCtx(
16
+ record: Record<string, unknown> | undefined,
17
+ overrides: { userFeatures?: string[]; isSuperAdmin?: boolean } = {},
18
+ ) {
19
+ const items = record ? [record] : []
20
+ const mockQuery = jest.fn().mockResolvedValue({ items, total: items.length })
21
+ const searchIndexer = {
22
+ getEntityConfig: (entityId: string) =>
23
+ entityId === 'customers:customer_person_profile' ? PERSON_CONFIG : undefined,
24
+ }
25
+ const ctx = {
26
+ tenantId: 'tenant-1',
27
+ organizationId: 'org-1',
28
+ userId: null,
29
+ userFeatures: overrides.userFeatures ?? ['customers.people.view'],
30
+ isSuperAdmin: overrides.isSuperAdmin ?? false,
31
+ container: {
32
+ resolve: (name: string) => (name === 'searchIndexer' ? searchIndexer : { query: mockQuery }),
33
+ },
34
+ }
35
+ return { ctx, mockQuery }
36
+ }
37
+
38
+ describe('search_get tool', () => {
39
+ it('denies callers holding only search.view without the per-entity view feature', async () => {
40
+ const { ctx, mockQuery } = makeCtx(
41
+ { id: 'rec-1', first_name: 'Jane', ssn: '123-45-6789' },
42
+ { userFeatures: ['search.view'] },
43
+ )
44
+
45
+ await expect(
46
+ getTool.handler({ entityType: 'customers:customer_person_profile', recordId: 'rec-1' }, ctx),
47
+ ).rejects.toThrow(/Insufficient permissions/)
48
+ expect(mockQuery).not.toHaveBeenCalled()
49
+ })
50
+
51
+ it('returns the record for callers holding the per-entity view feature', async () => {
52
+ const { ctx, mockQuery } = makeCtx({ id: 'rec-1', first_name: 'Jane', last_name: 'Doe' })
53
+
54
+ const result = await getTool.handler(
55
+ { entityType: 'customers:customer_person_profile', recordId: 'rec-1' },
56
+ ctx,
57
+ ) as { found: boolean; record: Record<string, unknown> }
58
+ expect(result.found).toBe(true)
59
+ expect(result.record.first_name).toBe('Jane')
60
+ expect(mockQuery).toHaveBeenCalled()
61
+ })
62
+
63
+ it('strips hashOnly and excluded (PII) fields from the returned record', async () => {
64
+ const { ctx } = makeCtx({
65
+ id: 'rec-1',
66
+ first_name: 'Jane',
67
+ primary_email: 'jane@example.com',
68
+ primary_phone: '+1555',
69
+ ssn: '123-45-6789',
70
+ date_of_birth: '1990-01-01',
71
+ })
72
+
73
+ const result = await getTool.handler(
74
+ { entityType: 'customers:customer_person_profile', recordId: 'rec-1' },
75
+ ctx,
76
+ ) as { record: Record<string, unknown> }
77
+ expect(result.record.first_name).toBe('Jane')
78
+ expect(result.record.id).toBe('rec-1')
79
+ expect(result.record.primary_email).toBeUndefined()
80
+ expect(result.record.primary_phone).toBeUndefined()
81
+ expect(result.record.ssn).toBeUndefined()
82
+ expect(result.record.date_of_birth).toBeUndefined()
83
+ })
84
+
85
+ it('honors wildcard grants and super admins', async () => {
86
+ const wildcard = makeCtx({ id: 'rec-1', first_name: 'Jane' }, { userFeatures: ['*'] })
87
+ const wildcardResult = await getTool.handler(
88
+ { entityType: 'customers:customer_person_profile', recordId: 'rec-1' },
89
+ wildcard.ctx,
90
+ ) as { found: boolean }
91
+ expect(wildcardResult.found).toBe(true)
92
+
93
+ const superAdmin = makeCtx({ id: 'rec-1', first_name: 'Jane' }, { userFeatures: [], isSuperAdmin: true })
94
+ const superResult = await getTool.handler(
95
+ { entityType: 'customers:customer_person_profile', recordId: 'rec-1' },
96
+ superAdmin.ctx,
97
+ ) as { found: boolean }
98
+ expect(superResult.found).toBe(true)
99
+ })
100
+
101
+ it('fails closed for entity types not configured for search', async () => {
102
+ const { ctx, mockQuery } = makeCtx({ id: 'rec-1' })
103
+
104
+ await expect(
105
+ getTool.handler({ entityType: 'secret:unconfigured', recordId: 'rec-1' }, ctx),
106
+ ).rejects.toThrow(/not configured for search/)
107
+ expect(mockQuery).not.toHaveBeenCalled()
108
+ })
109
+
110
+ it('throws when tenantId is missing', async () => {
111
+ const { ctx } = makeCtx({ id: 'rec-1' })
112
+ const noTenantCtx = { ...ctx, tenantId: null }
113
+
114
+ await expect(
115
+ getTool.handler({ entityType: 'customers:customer_person_profile', recordId: 'rec-1' }, noTenantCtx),
116
+ ).rejects.toThrow('Tenant context is required')
117
+ })
118
+ })
@@ -1,5 +1,10 @@
1
1
  import { z } from 'zod'
2
- import type { SearchResult, SearchStrategyId } from '@open-mercato/shared/modules/search'
2
+ import type {
3
+ SearchEntityConfig,
4
+ SearchResult,
5
+ SearchStrategyId,
6
+ } from '@open-mercato/shared/modules/search'
7
+ import { hasAllFeatures } from '@open-mercato/shared/security/features'
3
8
 
4
9
  /**
5
10
  * AI Tools definitions for the Search module.
@@ -47,6 +52,97 @@ type AiToolDefinition = {
47
52
  handler: (input: any, ctx: ToolContext) => Promise<unknown>
48
53
  }
49
54
 
55
+ /**
56
+ * Minimal shape of the `searchIndexer` DI service consumed by the per-entity
57
+ * ACL / field-policy resolution below. Kept local to avoid importing the full
58
+ * `SearchIndexer` class into the tool module.
59
+ */
60
+ type SearchIndexerLike = {
61
+ getEntityConfig: (entityId: string) => SearchEntityConfig | undefined
62
+ }
63
+
64
+ class SearchToolAuthorizationError extends Error {
65
+ constructor(message: string) {
66
+ super(message)
67
+ this.name = 'SearchToolAuthorizationError'
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Resolve the search config for an entity type and enforce the per-entity view
73
+ * feature(s). Data-returning tools (`search_get` / `search_aggregate`) MUST NOT
74
+ * rely on the search-administration `search.view` feature to gate record reads.
75
+ *
76
+ * Fails closed: when the entity is not configured for search, or has no
77
+ * `aclFeatures` declared, access is denied so records are never exposed without
78
+ * an explicit owning-module grant.
79
+ */
80
+ function authorizeEntityAccess(entityType: string, ctx: ToolContext): SearchEntityConfig {
81
+ const searchIndexer = ctx.container.resolve<SearchIndexerLike>('searchIndexer')
82
+ const config = searchIndexer.getEntityConfig(entityType)
83
+
84
+ if (!config) {
85
+ throw new SearchToolAuthorizationError(
86
+ `[internal] Entity type "${entityType}" is not configured for search`
87
+ )
88
+ }
89
+
90
+ if (ctx.isSuperAdmin) return config
91
+
92
+ const required = config.aclFeatures
93
+ if (!required || required.length === 0) {
94
+ throw new SearchToolAuthorizationError(
95
+ `[internal] Entity type "${entityType}" does not declare aclFeatures; access denied`
96
+ )
97
+ }
98
+
99
+ if (!hasAllFeatures(ctx.userFeatures, required)) {
100
+ throw new SearchToolAuthorizationError(
101
+ `[internal] Insufficient permissions for entity "${entityType}". Required: ${required.join(', ')}`
102
+ )
103
+ }
104
+
105
+ return config
106
+ }
107
+
108
+ /**
109
+ * Strip fields that the entity's field policy marks as sensitive
110
+ * (`hashOnly` exact-match PII or fully `excluded`) from a query-engine record.
111
+ * Defense-in-depth so even an authorized caller never receives decrypted PII or
112
+ * fields a `fieldPolicy` keeps out of search.
113
+ */
114
+ function stripSensitiveFields(
115
+ record: Record<string, unknown>,
116
+ config: SearchEntityConfig
117
+ ): Record<string, unknown> {
118
+ const sensitive = new Set<string>([
119
+ ...(config.fieldPolicy?.hashOnly ?? []),
120
+ ...(config.fieldPolicy?.excluded ?? []),
121
+ ])
122
+ if (sensitive.size === 0) return record
123
+ const safe: Record<string, unknown> = {}
124
+ for (const [key, value] of Object.entries(record)) {
125
+ if (sensitive.has(key)) continue
126
+ safe[key] = value
127
+ }
128
+ return safe
129
+ }
130
+
131
+ /**
132
+ * Determine whether a field is a safe aggregation grouping key for an entity.
133
+ * Only fields explicitly declared `searchable` are allowed; `hashOnly` and
134
+ * `excluded` (PII / sensitive) fields can never be enumerated via group-by.
135
+ */
136
+ function isGroupByAllowed(field: string, config: SearchEntityConfig): boolean {
137
+ const sensitive = new Set<string>([
138
+ ...(config.fieldPolicy?.hashOnly ?? []),
139
+ ...(config.fieldPolicy?.excluded ?? []),
140
+ ])
141
+ if (sensitive.has(field)) return false
142
+ const searchable = config.fieldPolicy?.searchable ?? []
143
+ return searchable.includes(field)
144
+ }
145
+
50
146
  // =============================================================================
51
147
  // Tool Definitions
52
148
  // =============================================================================
@@ -169,6 +265,8 @@ const searchGetTool: AiToolDefinition = {
169
265
  throw new Error('Tenant context is required')
170
266
  }
171
267
 
268
+ const entityConfig = authorizeEntityAccess(input.entityType, ctx)
269
+
172
270
  const queryEngine = ctx.container.resolve<{
173
271
  query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>
174
272
  }>('queryEngine')
@@ -181,8 +279,8 @@ const searchGetTool: AiToolDefinition = {
181
279
  page: { page: 1, pageSize: 1 },
182
280
  })
183
281
 
184
- const record = result.items[0] as Record<string, unknown> | undefined
185
- if (!record) {
282
+ const rawRecord = result.items[0] as Record<string, unknown> | undefined
283
+ if (!rawRecord) {
186
284
  return {
187
285
  found: false,
188
286
  entityType: input.entityType,
@@ -191,6 +289,8 @@ const searchGetTool: AiToolDefinition = {
191
289
  }
192
290
  }
193
291
 
292
+ const record = stripSensitiveFields(rawRecord, entityConfig)
293
+
194
294
  // Extract custom fields
195
295
  const customFields: Record<string, unknown> = {}
196
296
  const standardFields: Record<string, unknown> = {}
@@ -329,6 +429,14 @@ const searchAggregateTool: AiToolDefinition = {
329
429
  throw new Error('Tenant context is required')
330
430
  }
331
431
 
432
+ const entityConfig = authorizeEntityAccess(input.entityType, ctx)
433
+
434
+ if (!isGroupByAllowed(input.groupBy, entityConfig)) {
435
+ throw new SearchToolAuthorizationError(
436
+ `[internal] Field "${input.groupBy}" is not an allowed grouping key for "${input.entityType}"`
437
+ )
438
+ }
439
+
332
440
  const queryEngine = ctx.container.resolve<{
333
441
  query: (entityId: string, options: any) => Promise<{ items: unknown[]; total: number }>
334
442
  }>('queryEngine')