@open-mercato/ai-assistant 0.6.6-develop.6465.1.019f0fb26f → 0.6.6-develop.6471.1.9ab5bdd79a

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.
Files changed (199) hide show
  1. package/dist/frontend/hooks/useCommandPalette.js +16 -14
  2. package/dist/frontend/hooks/useCommandPalette.js.map +2 -2
  3. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js +3 -1
  4. package/dist/modules/ai_assistant/api/ai/actions/[id]/cancel/route.js.map +2 -2
  5. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js +3 -1
  6. package/dist/modules/ai_assistant/api/ai/actions/[id]/confirm/route.js.map +2 -2
  7. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js +3 -1
  8. package/dist/modules/ai_assistant/api/ai/actions/[id]/route.js.map +2 -2
  9. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.js +5 -3
  10. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.js.map +2 -2
  11. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js +4 -2
  12. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/models/route.js.map +2 -2
  13. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js +5 -3
  14. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.js.map +2 -2
  15. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js +4 -2
  16. package/dist/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.js.map +2 -2
  17. package/dist/modules/ai_assistant/api/ai/agents/route.js +3 -1
  18. package/dist/modules/ai_assistant/api/ai/agents/route.js.map +2 -2
  19. package/dist/modules/ai_assistant/api/ai/chat/route.js +6 -7
  20. package/dist/modules/ai_assistant/api/ai/chat/route.js.map +2 -2
  21. package/dist/modules/ai_assistant/api/ai/conversations/[conversationId]/route.js +5 -3
  22. package/dist/modules/ai_assistant/api/ai/conversations/[conversationId]/route.js.map +2 -2
  23. package/dist/modules/ai_assistant/api/ai/conversations/import/route.js +3 -1
  24. package/dist/modules/ai_assistant/api/ai/conversations/import/route.js.map +2 -2
  25. package/dist/modules/ai_assistant/api/ai/conversations/route.js +4 -2
  26. package/dist/modules/ai_assistant/api/ai/conversations/route.js.map +2 -2
  27. package/dist/modules/ai_assistant/api/ai/run-object/route.js +3 -1
  28. package/dist/modules/ai_assistant/api/ai/run-object/route.js.map +2 -2
  29. package/dist/modules/ai_assistant/api/chat/route.js +23 -14
  30. package/dist/modules/ai_assistant/api/chat/route.js.map +2 -2
  31. package/dist/modules/ai_assistant/api/health/route.js +3 -1
  32. package/dist/modules/ai_assistant/api/health/route.js.map +2 -2
  33. package/dist/modules/ai_assistant/api/mcp-key/route.js +3 -1
  34. package/dist/modules/ai_assistant/api/mcp-key/route.js.map +2 -2
  35. package/dist/modules/ai_assistant/api/route/route.js +11 -9
  36. package/dist/modules/ai_assistant/api/route/route.js.map +2 -2
  37. package/dist/modules/ai_assistant/api/session-key/route.js +3 -1
  38. package/dist/modules/ai_assistant/api/session-key/route.js.map +2 -2
  39. package/dist/modules/ai_assistant/api/settings/allowlist/route.js +4 -2
  40. package/dist/modules/ai_assistant/api/settings/allowlist/route.js.map +2 -2
  41. package/dist/modules/ai_assistant/api/settings/route.js +6 -4
  42. package/dist/modules/ai_assistant/api/settings/route.js.map +2 -2
  43. package/dist/modules/ai_assistant/api/tools/execute/route.js +3 -1
  44. package/dist/modules/ai_assistant/api/tools/execute/route.js.map +2 -2
  45. package/dist/modules/ai_assistant/api/tools/route.js +3 -1
  46. package/dist/modules/ai_assistant/api/tools/route.js.map +2 -2
  47. package/dist/modules/ai_assistant/api/usage/daily/route.js +3 -1
  48. package/dist/modules/ai_assistant/api/usage/daily/route.js.map +2 -2
  49. package/dist/modules/ai_assistant/api/usage/sessions/[sessionId]/route.js +3 -1
  50. package/dist/modules/ai_assistant/api/usage/sessions/[sessionId]/route.js.map +2 -2
  51. package/dist/modules/ai_assistant/api/usage/sessions/route.js +3 -1
  52. package/dist/modules/ai_assistant/api/usage/sessions/route.js.map +2 -2
  53. package/dist/modules/ai_assistant/cli.js +3 -0
  54. package/dist/modules/ai_assistant/cli.js.map +2 -2
  55. package/dist/modules/ai_assistant/lib/agent-policy.js +7 -5
  56. package/dist/modules/ai_assistant/lib/agent-policy.js.map +2 -2
  57. package/dist/modules/ai_assistant/lib/agent-registry.js +11 -13
  58. package/dist/modules/ai_assistant/lib/agent-registry.js.map +2 -2
  59. package/dist/modules/ai_assistant/lib/agent-runtime.js +21 -44
  60. package/dist/modules/ai_assistant/lib/agent-runtime.js.map +2 -2
  61. package/dist/modules/ai_assistant/lib/agent-tools.js +5 -10
  62. package/dist/modules/ai_assistant/lib/agent-tools.js.map +2 -2
  63. package/dist/modules/ai_assistant/lib/ai-overrides.js +5 -9
  64. package/dist/modules/ai_assistant/lib/ai-overrides.js.map +2 -2
  65. package/dist/modules/ai_assistant/lib/api-endpoint-index.js +22 -22
  66. package/dist/modules/ai_assistant/lib/api-endpoint-index.js.map +2 -2
  67. package/dist/modules/ai_assistant/lib/attachment-parts.js +10 -26
  68. package/dist/modules/ai_assistant/lib/attachment-parts.js.map +2 -2
  69. package/dist/modules/ai_assistant/lib/auth.js +3 -1
  70. package/dist/modules/ai_assistant/lib/auth.js.map +2 -2
  71. package/dist/modules/ai_assistant/lib/codemode-tools.js +15 -17
  72. package/dist/modules/ai_assistant/lib/codemode-tools.js.map +2 -2
  73. package/dist/modules/ai_assistant/lib/entity-index.js +7 -5
  74. package/dist/modules/ai_assistant/lib/entity-index.js.map +2 -2
  75. package/dist/modules/ai_assistant/lib/generated-registry-loader.js +3 -4
  76. package/dist/modules/ai_assistant/lib/generated-registry-loader.js.map +2 -2
  77. package/dist/modules/ai_assistant/lib/http-server.js +45 -48
  78. package/dist/modules/ai_assistant/lib/http-server.js.map +2 -2
  79. package/dist/modules/ai_assistant/lib/llm-bootstrap.js +5 -12
  80. package/dist/modules/ai_assistant/lib/llm-bootstrap.js.map +2 -2
  81. package/dist/modules/ai_assistant/lib/mcp-client.js +3 -1
  82. package/dist/modules/ai_assistant/lib/mcp-client.js.map +2 -2
  83. package/dist/modules/ai_assistant/lib/mcp-dev-key-resolution.js +3 -1
  84. package/dist/modules/ai_assistant/lib/mcp-dev-key-resolution.js.map +2 -2
  85. package/dist/modules/ai_assistant/lib/mcp-dev-server.js +3 -1
  86. package/dist/modules/ai_assistant/lib/mcp-dev-server.js.map +2 -2
  87. package/dist/modules/ai_assistant/lib/mcp-server.js +24 -19
  88. package/dist/modules/ai_assistant/lib/mcp-server.js.map +2 -2
  89. package/dist/modules/ai_assistant/lib/mcp-tool-adapter.js +3 -1
  90. package/dist/modules/ai_assistant/lib/mcp-tool-adapter.js.map +2 -2
  91. package/dist/modules/ai_assistant/lib/model-factory.js +4 -2
  92. package/dist/modules/ai_assistant/lib/model-factory.js.map +2 -2
  93. package/dist/modules/ai_assistant/lib/opencode-client.js +5 -3
  94. package/dist/modules/ai_assistant/lib/opencode-client.js.map +2 -2
  95. package/dist/modules/ai_assistant/lib/opencode-handlers.js +30 -12
  96. package/dist/modules/ai_assistant/lib/opencode-handlers.js.map +2 -2
  97. package/dist/modules/ai_assistant/lib/pending-action-cancel.js +3 -1
  98. package/dist/modules/ai_assistant/lib/pending-action-cancel.js.map +2 -2
  99. package/dist/modules/ai_assistant/lib/pending-action-executor.js +3 -1
  100. package/dist/modules/ai_assistant/lib/pending-action-executor.js.map +2 -2
  101. package/dist/modules/ai_assistant/lib/prepare-mutation.js +4 -6
  102. package/dist/modules/ai_assistant/lib/prepare-mutation.js.map +2 -2
  103. package/dist/modules/ai_assistant/lib/schema-utils.js +3 -1
  104. package/dist/modules/ai_assistant/lib/schema-utils.js.map +2 -2
  105. package/dist/modules/ai_assistant/lib/token-usage-recorder.js +4 -8
  106. package/dist/modules/ai_assistant/lib/token-usage-recorder.js.map +2 -2
  107. package/dist/modules/ai_assistant/lib/tool-executor.js +3 -1
  108. package/dist/modules/ai_assistant/lib/tool-executor.js.map +2 -2
  109. package/dist/modules/ai_assistant/lib/tool-loader.js +18 -25
  110. package/dist/modules/ai_assistant/lib/tool-loader.js.map +2 -2
  111. package/dist/modules/ai_assistant/lib/tool-registry.js +3 -1
  112. package/dist/modules/ai_assistant/lib/tool-registry.js.map +2 -2
  113. package/dist/modules/ai_assistant/lib/tool-test-runner.js +3 -1
  114. package/dist/modules/ai_assistant/lib/tool-test-runner.js.map +2 -2
  115. package/dist/modules/ai_assistant/setup.js +4 -8
  116. package/dist/modules/ai_assistant/setup.js.map +2 -2
  117. package/dist/modules/ai_assistant/subscribers/conversation-shared-notify.js +3 -1
  118. package/dist/modules/ai_assistant/subscribers/conversation-shared-notify.js.map +2 -2
  119. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js +7 -19
  120. package/dist/modules/ai_assistant/workers/ai-pending-action-cleanup.js.map +2 -2
  121. package/dist/modules/ai_assistant/workers/ai-token-usage-prune.js +5 -11
  122. package/dist/modules/ai_assistant/workers/ai-token-usage-prune.js.map +2 -2
  123. package/package.json +6 -6
  124. package/src/frontend/hooks/useCommandPalette.ts +17 -16
  125. package/src/modules/ai_assistant/__tests__/events.test.ts +23 -5
  126. package/src/modules/ai_assistant/__tests__/integration/ws-c-attachment-bridge.test.ts +21 -3
  127. package/src/modules/ai_assistant/__tests__/integration/ws-c-policy-and-tools.test.ts +22 -3
  128. package/src/modules/ai_assistant/__tests__/token-usage-recorder.test.ts +26 -5
  129. package/src/modules/ai_assistant/api/ai/actions/[id]/cancel/route.ts +4 -1
  130. package/src/modules/ai_assistant/api/ai/actions/[id]/confirm/route.ts +4 -1
  131. package/src/modules/ai_assistant/api/ai/actions/[id]/route.ts +4 -1
  132. package/src/modules/ai_assistant/api/ai/agents/[agentId]/loop-override/route.ts +6 -3
  133. package/src/modules/ai_assistant/api/ai/agents/[agentId]/models/route.ts +5 -2
  134. package/src/modules/ai_assistant/api/ai/agents/[agentId]/mutation-policy/route.ts +6 -3
  135. package/src/modules/ai_assistant/api/ai/agents/[agentId]/prompt-override/route.ts +5 -2
  136. package/src/modules/ai_assistant/api/ai/agents/route.ts +4 -1
  137. package/src/modules/ai_assistant/api/ai/chat/route.ts +7 -7
  138. package/src/modules/ai_assistant/api/ai/conversations/[conversationId]/route.ts +6 -3
  139. package/src/modules/ai_assistant/api/ai/conversations/import/route.ts +4 -1
  140. package/src/modules/ai_assistant/api/ai/conversations/route.ts +5 -2
  141. package/src/modules/ai_assistant/api/ai/run-object/route.ts +4 -1
  142. package/src/modules/ai_assistant/api/chat/route.ts +24 -15
  143. package/src/modules/ai_assistant/api/health/route.ts +4 -1
  144. package/src/modules/ai_assistant/api/mcp-key/route.ts +4 -1
  145. package/src/modules/ai_assistant/api/route/route.ts +12 -9
  146. package/src/modules/ai_assistant/api/session-key/route.ts +4 -1
  147. package/src/modules/ai_assistant/api/settings/allowlist/route.ts +5 -2
  148. package/src/modules/ai_assistant/api/settings/route.ts +7 -4
  149. package/src/modules/ai_assistant/api/tools/execute/route.ts +4 -1
  150. package/src/modules/ai_assistant/api/tools/route.ts +4 -1
  151. package/src/modules/ai_assistant/api/usage/daily/route.ts +4 -1
  152. package/src/modules/ai_assistant/api/usage/sessions/[sessionId]/route.ts +4 -1
  153. package/src/modules/ai_assistant/api/usage/sessions/route.ts +4 -1
  154. package/src/modules/ai_assistant/cli.ts +5 -0
  155. package/src/modules/ai_assistant/lib/__tests__/agent-policy.mutation-override.test.ts +20 -2
  156. package/src/modules/ai_assistant/lib/__tests__/agent-registry.test.ts +25 -5
  157. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-loop-phase0.test.ts +21 -2
  158. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-parity.test.ts +23 -3
  159. package/src/modules/ai_assistant/lib/__tests__/agent-runtime-phase4a.test.ts +20 -2
  160. package/src/modules/ai_assistant/lib/__tests__/agent-tools.test.ts +22 -3
  161. package/src/modules/ai_assistant/lib/__tests__/ai-overrides.test.ts +23 -3
  162. package/src/modules/ai_assistant/lib/__tests__/attachment-parts.test.ts +25 -7
  163. package/src/modules/ai_assistant/lib/__tests__/model-factory.test.ts +25 -5
  164. package/src/modules/ai_assistant/lib/__tests__/pending-action-cancel.test.ts +19 -1
  165. package/src/modules/ai_assistant/lib/__tests__/prepare-mutation.test.ts +22 -3
  166. package/src/modules/ai_assistant/lib/agent-policy.ts +8 -5
  167. package/src/modules/ai_assistant/lib/agent-registry.ts +12 -15
  168. package/src/modules/ai_assistant/lib/agent-runtime.ts +23 -46
  169. package/src/modules/ai_assistant/lib/agent-tools.ts +7 -11
  170. package/src/modules/ai_assistant/lib/ai-overrides.ts +6 -9
  171. package/src/modules/ai_assistant/lib/api-endpoint-index.ts +23 -22
  172. package/src/modules/ai_assistant/lib/attachment-parts.ts +14 -29
  173. package/src/modules/ai_assistant/lib/auth.ts +4 -1
  174. package/src/modules/ai_assistant/lib/codemode-tools.ts +17 -17
  175. package/src/modules/ai_assistant/lib/entity-index.ts +8 -5
  176. package/src/modules/ai_assistant/lib/generated-registry-loader.ts +4 -4
  177. package/src/modules/ai_assistant/lib/http-server.ts +46 -48
  178. package/src/modules/ai_assistant/lib/llm-bootstrap.ts +7 -13
  179. package/src/modules/ai_assistant/lib/mcp-client.ts +4 -1
  180. package/src/modules/ai_assistant/lib/mcp-dev-key-resolution.ts +4 -1
  181. package/src/modules/ai_assistant/lib/mcp-dev-server.ts +4 -1
  182. package/src/modules/ai_assistant/lib/mcp-server.ts +27 -19
  183. package/src/modules/ai_assistant/lib/mcp-tool-adapter.ts +4 -1
  184. package/src/modules/ai_assistant/lib/model-factory.ts +6 -3
  185. package/src/modules/ai_assistant/lib/opencode-client.ts +6 -3
  186. package/src/modules/ai_assistant/lib/opencode-handlers.ts +32 -12
  187. package/src/modules/ai_assistant/lib/pending-action-cancel.ts +4 -1
  188. package/src/modules/ai_assistant/lib/pending-action-executor.ts +4 -1
  189. package/src/modules/ai_assistant/lib/prepare-mutation.ts +5 -6
  190. package/src/modules/ai_assistant/lib/schema-utils.ts +4 -1
  191. package/src/modules/ai_assistant/lib/token-usage-recorder.ts +5 -8
  192. package/src/modules/ai_assistant/lib/tool-executor.ts +4 -1
  193. package/src/modules/ai_assistant/lib/tool-loader.ts +19 -25
  194. package/src/modules/ai_assistant/lib/tool-registry.ts +4 -1
  195. package/src/modules/ai_assistant/lib/tool-test-runner.ts +4 -1
  196. package/src/modules/ai_assistant/setup.ts +5 -8
  197. package/src/modules/ai_assistant/subscribers/conversation-shared-notify.ts +4 -1
  198. package/src/modules/ai_assistant/workers/ai-pending-action-cleanup.ts +8 -19
  199. package/src/modules/ai_assistant/workers/ai-token-usage-prune.ts +6 -11
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/lib/tool-test-runner.ts"],
4
- "sourcesContent": ["/**\n * In-process AI tool test runner.\n *\n * Iterates every tool registered in `ai-tools.generated.ts`, invokes the\n * handler against a super-admin tenant context, and returns a structured\n * report. Used by the `mercato ai_assistant test-tools` CLI subcommand and\n * by `.ai/qa/tests/integration/TC-INT-AI-TOOLS.spec.ts`.\n *\n * Safety posture:\n * - No HTTP exposure \u2014 runs only inside the Node process driving the CLI.\n * - Mutation tools are exercised through `prepareMutation` and we assert a\n * pending-action envelope is returned. The pending-action row is created\n * in `ai_pending_actions` but never confirmed, so no real write happens.\n * - Tools without an explicit fixture entry are skipped with reason\n * `'no fixture'` rather than failing.\n */\nimport type { AwilixContainer } from 'awilix'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { McpToolContext, AiToolDefinition } from './types'\nimport type { AiAgentDefinition, AiAgentMutationPolicy } from './ai-agent-definition'\nimport { getFixture, type ToolFixture } from './tool-test-fixtures'\nimport { prepareMutation } from './prepare-mutation'\nimport { executePendingActionConfirm } from './pending-action-executor'\nimport {\n findGeneratedFile,\n compileAndImportGenerated,\n ensureApiRouteManifestsRegistered,\n} from './generated-registry-loader'\n\nexport type ToolTestStatus = 'pass' | 'fail' | 'skip'\n\nexport interface ToolTestRecord {\n module: string\n tool: string\n isMutation: boolean\n status: ToolTestStatus\n durationMs: number\n reason?: string\n resultPreview?: unknown\n}\n\nexport interface ToolTestReport {\n tenantId: string | null\n organizationId: string | null\n total: number\n passed: number\n failed: number\n skipped: number\n records: ToolTestRecord[]\n}\n\ninterface RawAiToolsModule {\n aiToolConfigEntriesRaw?: { moduleId: string; tools: unknown[] }[]\n aiToolConfigEntries?: { moduleId: string; tools: unknown[] }[]\n}\n\nfunction isToolDefinition(value: unknown): value is AiToolDefinition {\n if (!value || typeof value !== 'object') return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.description === 'string' &&\n candidate.inputSchema !== undefined &&\n typeof candidate.handler === 'function'\n )\n}\n\nasync function loadGeneratedTools(): Promise<{ moduleId: string; tools: AiToolDefinition[] }[]> {\n const tsPath = findGeneratedFile('ai-tools.generated.ts')\n if (!tsPath) {\n throw new Error(\n 'Could not locate apps/<app>/.mercato/generated/ai-tools.generated.ts. Run `yarn generate` first.',\n )\n }\n await ensureApiRouteManifestsRegistered()\n const mod = (await compileAndImportGenerated(tsPath)) as RawAiToolsModule\n const entries = mod.aiToolConfigEntriesRaw ?? mod.aiToolConfigEntries ?? []\n const result: { moduleId: string; tools: AiToolDefinition[] }[] = []\n for (const entry of entries) {\n if (!entry || typeof entry.moduleId !== 'string') continue\n const tools = Array.isArray(entry.tools)\n ? entry.tools.filter(isToolDefinition)\n : []\n result.push({ moduleId: entry.moduleId, tools })\n }\n return result\n}\n\nexport async function pickDefaultTenant(\n container: AwilixContainer,\n): Promise<{ tenantId: string; organizationId: string | null; userId: string | null } | null> {\n try {\n const em = container.resolve<{\n getConnection: () => {\n execute: (sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n }\n }>('em') as unknown as {\n getConnection: () => {\n execute: (sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n }\n }\n const conn = em.getConnection()\n const tenantRows = await conn.execute(\n `SELECT id FROM tenants WHERE deleted_at IS NULL ORDER BY created_at ASC LIMIT 1`,\n )\n const tenantId =\n Array.isArray(tenantRows) && tenantRows[0]\n ? String((tenantRows[0] as Record<string, unknown>).id)\n : null\n if (!tenantId) return null\n const orgRows = await conn.execute(\n `SELECT id FROM organizations WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY created_at ASC LIMIT 1`,\n [tenantId],\n )\n const organizationId =\n Array.isArray(orgRows) && orgRows[0]\n ? String((orgRows[0] as Record<string, unknown>).id)\n : null\n const userRows = await conn.execute(\n `SELECT id FROM users WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY created_at ASC LIMIT 1`,\n [tenantId],\n )\n const userId =\n Array.isArray(userRows) && userRows[0]\n ? String((userRows[0] as Record<string, unknown>).id)\n : null\n return { tenantId, organizationId, userId }\n } catch (error) {\n if (process.env.OM_TOOL_TEST_DEBUG === '1') {\n console.warn('[tool-test-runner] pickDefaultTenant failed:', error)\n }\n return null\n }\n}\n\nfunction buildSuperAdminContext(\n container: AwilixContainer,\n tenantId: string | null,\n organizationId: string | null,\n userId: string | null,\n): McpToolContext {\n return {\n tenantId,\n organizationId,\n userId,\n container,\n userFeatures: ['*'],\n isSuperAdmin: true,\n }\n}\n\nfunction clipPreview(value: unknown): unknown {\n try {\n const json = JSON.stringify(value)\n if (json.length <= 400) return value\n return `${json.slice(0, 400)}\u2026(truncated, ${json.length} bytes)`\n } catch {\n return '[unserializable]'\n }\n}\n\nfunction dummyAgentForTool(tool: AiToolDefinition): AiAgentDefinition {\n // The runner never registers this agent; it's only used as input to\n // `prepareMutation` for shape compatibility. The id namespace is namespaced\n // under `__test__` so it cannot collide with real agents.\n const policy: AiAgentMutationPolicy = 'destructive-confirm-required'\n return {\n id: `__test__.${tool.name}`,\n moduleId: tool.name.split('.')[0] ?? '__test__',\n label: 'Tool Test Runner',\n description: 'Synthetic agent used by the tool test runner',\n systemPrompt: '',\n allowedTools: [tool.name],\n readOnly: false,\n mutationPolicy: policy,\n } as AiAgentDefinition\n}\n\nasync function executeReadTool(\n tool: AiToolDefinition,\n args: Record<string, unknown>,\n container: AwilixContainer,\n ctx: McpToolContext,\n): Promise<unknown> {\n // Mirror the dispatcher: resolve a fresh container per call so EM identity\n // map state is clean between tools.\n const fresh = await createRequestContainer()\n const freshCtx: McpToolContext = { ...ctx, container: fresh, tool }\n void container // keep arg for future use\n return tool.handler(args as never, freshCtx)\n}\n\nasync function executeMutationTool(\n tool: AiToolDefinition,\n args: Record<string, unknown>,\n container: AwilixContainer,\n ctx: McpToolContext,\n): Promise<unknown> {\n // Route through prepareMutation so we assert the approval contract still\n // holds \u2014 the handler must NEVER write directly. We pass a destructive\n // policy so the runtime treats the call as a confirmation candidate and\n // creates a pending-action row.\n const fresh = await createRequestContainer()\n const agent = dummyAgentForTool(tool)\n const userId = ctx.userId ?? '00000000-0000-0000-0000-000000000000'\n const { uiPart, pendingAction } = await prepareMutation(\n {\n agent,\n tool,\n toolCallArgs: args,\n conversationId: null,\n mutationPolicyOverride: null,\n },\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId,\n features: ctx.userFeatures,\n isSuperAdmin: ctx.isSuperAdmin,\n container: fresh,\n },\n )\n // Exercise the actual handler via the same path the production confirm\n // route uses. Without this, mutation tools whose handler crashes (e.g.\n // missing `ctx.tool` for the API operation runner) would be reported as\n // passing because `prepareMutation` never invokes the handler.\n // `prepareMutation` already enforced `tenantId` is non-null above; cast\n // here for the stricter `PendingActionExecuteContext` shape.\n const confirmTenantId = ctx.tenantId as string\n const confirmContainer = await createRequestContainer()\n const confirmation = await executePendingActionConfirm({\n action: pendingAction,\n agent,\n tool,\n ctx: {\n tenantId: confirmTenantId,\n organizationId: ctx.organizationId,\n userId,\n container: confirmContainer,\n userFeatures: ctx.userFeatures,\n isSuperAdmin: ctx.isSuperAdmin,\n },\n emitEvent: async () => {},\n })\n if (!confirmation.ok) {\n const error = (confirmation.executionResult as { error?: { message?: string } } | undefined)?.error\n const cause = confirmation.cause\n const causeMessage =\n cause instanceof Error\n ? cause.message\n : typeof cause === 'string'\n ? cause\n : null\n const message = error?.message ?? causeMessage ?? 'handler invocation failed'\n throw new Error(message)\n }\n return {\n status: 'pending-confirmation',\n pendingActionId: pendingAction.id,\n expiresAt: pendingAction.expiresAt.toISOString(),\n uiPartType: (uiPart as { type?: string } | undefined)?.type ?? null,\n handlerExecuted: true,\n }\n}\n\nasync function resolveFixtureInput(\n fixture: ToolFixture,\n resolved: Map<string, AiToolDefinition>,\n container: AwilixContainer,\n ctx: McpToolContext,\n): Promise<{ ok: true; input: Record<string, unknown> } | { ok: false; reason: string }> {\n if (fixture.input) return { ok: true, input: { ...fixture.input } }\n if (!fixture.idFrom) {\n return { ok: false, reason: 'fixture has neither input nor idFrom' }\n }\n const sourceTool = resolved.get(fixture.idFrom)\n if (!sourceTool) {\n return { ok: false, reason: `idFrom tool not found: ${fixture.idFrom}` }\n }\n const sourceFixture = getFixture(fixture.idFrom)\n if (!sourceFixture?.input) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} has no static input fixture`,\n }\n }\n let listResult: unknown\n try {\n listResult = await executeReadTool(\n sourceTool,\n { ...sourceFixture.input },\n container,\n ctx,\n )\n } catch (error) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} threw: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }\n }\n const records = extractRecords(listResult)\n if (!records.length) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} returned no records`,\n }\n }\n const idField = 'id'\n const id = (records[0] as Record<string, unknown>)[idField]\n if (typeof id !== 'string' || !id) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} first record has no string id`,\n }\n }\n const bindAs = fixture.bindAs ?? 'id'\n return {\n ok: true,\n input: { [bindAs]: id, ...(fixture.extra ?? {}) },\n }\n}\n\nfunction extractRecords(value: unknown): unknown[] {\n if (!value || typeof value !== 'object') return []\n const candidate = value as Record<string, unknown>\n for (const key of ['records', 'items', 'people', 'companies', 'deals', 'results', 'data']) {\n const arr = candidate[key]\n if (Array.isArray(arr)) return arr\n }\n return []\n}\n\nexport interface RunToolTestsOptions {\n tenantId?: string | null\n organizationId?: string | null\n userId?: string | null\n moduleFilter?: string | null\n includeMutations?: boolean\n}\n\nexport async function runToolTests(\n options: RunToolTestsOptions = {},\n): Promise<ToolTestReport> {\n const includeMutations = options.includeMutations ?? true\n const container = await createRequestContainer()\n let tenantId: string | null = options.tenantId ?? null\n let organizationId: string | null = options.organizationId ?? null\n let userId: string | null = options.userId ?? null\n if (!tenantId) {\n const picked = await pickDefaultTenant(container)\n if (picked) {\n tenantId = picked.tenantId\n organizationId = picked.organizationId\n userId = userId ?? picked.userId\n }\n }\n const ctx = buildSuperAdminContext(container, tenantId, organizationId, userId)\n const grouped = await loadGeneratedTools()\n\n const flat: { moduleId: string; tool: AiToolDefinition }[] = []\n for (const group of grouped) {\n if (options.moduleFilter && group.moduleId !== options.moduleFilter) continue\n for (const tool of group.tools) flat.push({ moduleId: group.moduleId, tool })\n }\n const resolved = new Map<string, AiToolDefinition>()\n for (const { tool } of flat) resolved.set(tool.name, tool)\n\n const records: ToolTestRecord[] = []\n for (const { moduleId, tool } of flat) {\n const start = Date.now()\n const isMutation = tool.isMutation === true\n const fixture = getFixture(tool.name)\n if (!fixture) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: 'no fixture',\n })\n continue\n }\n if (fixture.skip) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: fixture.note ?? 'skip-by-fixture',\n })\n continue\n }\n if (isMutation && !includeMutations) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: 'mutations excluded',\n })\n continue\n }\n const inputResult = await resolveFixtureInput(fixture, resolved, container, ctx)\n if (!inputResult.ok) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: inputResult.reason,\n })\n continue\n }\n try {\n const result = isMutation\n ? await executeMutationTool(tool, inputResult.input, container, ctx)\n : await executeReadTool(tool, inputResult.input, container, ctx)\n // Result must be JSON-serializable.\n JSON.stringify(result)\n // Mutation tools must return a pending-confirmation envelope.\n if (\n isMutation &&\n (typeof result !== 'object' ||\n result === null ||\n (result as Record<string, unknown>).status !== 'pending-confirmation')\n ) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'fail',\n durationMs: Date.now() - start,\n reason: 'mutation tool did not route through prepareMutation (no pending-confirmation envelope)',\n resultPreview: clipPreview(result),\n })\n continue\n }\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'pass',\n durationMs: Date.now() - start,\n resultPreview: clipPreview(result),\n })\n } catch (error) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'fail',\n durationMs: Date.now() - start,\n reason: error instanceof Error ? error.message : String(error),\n })\n }\n }\n const passed = records.filter((r) => r.status === 'pass').length\n const failed = records.filter((r) => r.status === 'fail').length\n const skipped = records.filter((r) => r.status === 'skip').length\n return {\n tenantId,\n organizationId,\n total: records.length,\n passed,\n failed,\n skipped,\n records,\n }\n}\n"],
5
- "mappings": "AAiBA,SAAS,8BAA8B;AAGvC,SAAS,kBAAoC;AAC7C,SAAS,uBAAuB;AAChC,SAAS,mCAAmC;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA6BP,SAAS,iBAAiB,OAA2C;AACnE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,YAAY;AAClB,SACE,OAAO,UAAU,SAAS,YAC1B,OAAO,UAAU,gBAAgB,YACjC,UAAU,gBAAgB,UAC1B,OAAO,UAAU,YAAY;AAEjC;AAEA,eAAe,qBAAiF;AAC9F,QAAM,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ACX,QAAQ;AAAA,QACR,MAAM,KAAK;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,QACR,YAAY,KAAK,IAAI,IAAI;AAAA,QACzB,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MAC/D,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,SAAS,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,EAAE;AAC1D,QAAM,SAAS,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,EAAE;AAC1D,QAAM,UAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,EAAE;AAC3D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,QAAQ;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["/**\n * In-process AI tool test runner.\n *\n * Iterates every tool registered in `ai-tools.generated.ts`, invokes the\n * handler against a super-admin tenant context, and returns a structured\n * report. Used by the `mercato ai_assistant test-tools` CLI subcommand and\n * by `.ai/qa/tests/integration/TC-INT-AI-TOOLS.spec.ts`.\n *\n * Safety posture:\n * - No HTTP exposure \u2014 runs only inside the Node process driving the CLI.\n * - Mutation tools are exercised through `prepareMutation` and we assert a\n * pending-action envelope is returned. The pending-action row is created\n * in `ai_pending_actions` but never confirmed, so no real write happens.\n * - Tools without an explicit fixture entry are skipped with reason\n * `'no fixture'` rather than failing.\n */\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { AwilixContainer } from 'awilix'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { McpToolContext, AiToolDefinition } from './types'\nimport type { AiAgentDefinition, AiAgentMutationPolicy } from './ai-agent-definition'\nimport { getFixture, type ToolFixture } from './tool-test-fixtures'\nimport { prepareMutation } from './prepare-mutation'\nimport { executePendingActionConfirm } from './pending-action-executor'\nimport {\n findGeneratedFile,\n compileAndImportGenerated,\n ensureApiRouteManifestsRegistered,\n} from './generated-registry-loader'\n\nconst logger = createLogger('ai_assistant')\n\nexport type ToolTestStatus = 'pass' | 'fail' | 'skip'\n\nexport interface ToolTestRecord {\n module: string\n tool: string\n isMutation: boolean\n status: ToolTestStatus\n durationMs: number\n reason?: string\n resultPreview?: unknown\n}\n\nexport interface ToolTestReport {\n tenantId: string | null\n organizationId: string | null\n total: number\n passed: number\n failed: number\n skipped: number\n records: ToolTestRecord[]\n}\n\ninterface RawAiToolsModule {\n aiToolConfigEntriesRaw?: { moduleId: string; tools: unknown[] }[]\n aiToolConfigEntries?: { moduleId: string; tools: unknown[] }[]\n}\n\nfunction isToolDefinition(value: unknown): value is AiToolDefinition {\n if (!value || typeof value !== 'object') return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.description === 'string' &&\n candidate.inputSchema !== undefined &&\n typeof candidate.handler === 'function'\n )\n}\n\nasync function loadGeneratedTools(): Promise<{ moduleId: string; tools: AiToolDefinition[] }[]> {\n const tsPath = findGeneratedFile('ai-tools.generated.ts')\n if (!tsPath) {\n throw new Error(\n 'Could not locate apps/<app>/.mercato/generated/ai-tools.generated.ts. Run `yarn generate` first.',\n )\n }\n await ensureApiRouteManifestsRegistered()\n const mod = (await compileAndImportGenerated(tsPath)) as RawAiToolsModule\n const entries = mod.aiToolConfigEntriesRaw ?? mod.aiToolConfigEntries ?? []\n const result: { moduleId: string; tools: AiToolDefinition[] }[] = []\n for (const entry of entries) {\n if (!entry || typeof entry.moduleId !== 'string') continue\n const tools = Array.isArray(entry.tools)\n ? entry.tools.filter(isToolDefinition)\n : []\n result.push({ moduleId: entry.moduleId, tools })\n }\n return result\n}\n\nexport async function pickDefaultTenant(\n container: AwilixContainer,\n): Promise<{ tenantId: string; organizationId: string | null; userId: string | null } | null> {\n try {\n const em = container.resolve<{\n getConnection: () => {\n execute: (sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n }\n }>('em') as unknown as {\n getConnection: () => {\n execute: (sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n }\n }\n const conn = em.getConnection()\n const tenantRows = await conn.execute(\n `SELECT id FROM tenants WHERE deleted_at IS NULL ORDER BY created_at ASC LIMIT 1`,\n )\n const tenantId =\n Array.isArray(tenantRows) && tenantRows[0]\n ? String((tenantRows[0] as Record<string, unknown>).id)\n : null\n if (!tenantId) return null\n const orgRows = await conn.execute(\n `SELECT id FROM organizations WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY created_at ASC LIMIT 1`,\n [tenantId],\n )\n const organizationId =\n Array.isArray(orgRows) && orgRows[0]\n ? String((orgRows[0] as Record<string, unknown>).id)\n : null\n const userRows = await conn.execute(\n `SELECT id FROM users WHERE tenant_id = ? AND deleted_at IS NULL ORDER BY created_at ASC LIMIT 1`,\n [tenantId],\n )\n const userId =\n Array.isArray(userRows) && userRows[0]\n ? String((userRows[0] as Record<string, unknown>).id)\n : null\n return { tenantId, organizationId, userId }\n } catch (error) {\n if (process.env.OM_TOOL_TEST_DEBUG === '1') {\n logger.warn('tool-test-runner \u2014 pickDefaultTenant failed', { err: error })\n }\n return null\n }\n}\n\nfunction buildSuperAdminContext(\n container: AwilixContainer,\n tenantId: string | null,\n organizationId: string | null,\n userId: string | null,\n): McpToolContext {\n return {\n tenantId,\n organizationId,\n userId,\n container,\n userFeatures: ['*'],\n isSuperAdmin: true,\n }\n}\n\nfunction clipPreview(value: unknown): unknown {\n try {\n const json = JSON.stringify(value)\n if (json.length <= 400) return value\n return `${json.slice(0, 400)}\u2026(truncated, ${json.length} bytes)`\n } catch {\n return '[unserializable]'\n }\n}\n\nfunction dummyAgentForTool(tool: AiToolDefinition): AiAgentDefinition {\n // The runner never registers this agent; it's only used as input to\n // `prepareMutation` for shape compatibility. The id namespace is namespaced\n // under `__test__` so it cannot collide with real agents.\n const policy: AiAgentMutationPolicy = 'destructive-confirm-required'\n return {\n id: `__test__.${tool.name}`,\n moduleId: tool.name.split('.')[0] ?? '__test__',\n label: 'Tool Test Runner',\n description: 'Synthetic agent used by the tool test runner',\n systemPrompt: '',\n allowedTools: [tool.name],\n readOnly: false,\n mutationPolicy: policy,\n } as AiAgentDefinition\n}\n\nasync function executeReadTool(\n tool: AiToolDefinition,\n args: Record<string, unknown>,\n container: AwilixContainer,\n ctx: McpToolContext,\n): Promise<unknown> {\n // Mirror the dispatcher: resolve a fresh container per call so EM identity\n // map state is clean between tools.\n const fresh = await createRequestContainer()\n const freshCtx: McpToolContext = { ...ctx, container: fresh, tool }\n void container // keep arg for future use\n return tool.handler(args as never, freshCtx)\n}\n\nasync function executeMutationTool(\n tool: AiToolDefinition,\n args: Record<string, unknown>,\n container: AwilixContainer,\n ctx: McpToolContext,\n): Promise<unknown> {\n // Route through prepareMutation so we assert the approval contract still\n // holds \u2014 the handler must NEVER write directly. We pass a destructive\n // policy so the runtime treats the call as a confirmation candidate and\n // creates a pending-action row.\n const fresh = await createRequestContainer()\n const agent = dummyAgentForTool(tool)\n const userId = ctx.userId ?? '00000000-0000-0000-0000-000000000000'\n const { uiPart, pendingAction } = await prepareMutation(\n {\n agent,\n tool,\n toolCallArgs: args,\n conversationId: null,\n mutationPolicyOverride: null,\n },\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId,\n features: ctx.userFeatures,\n isSuperAdmin: ctx.isSuperAdmin,\n container: fresh,\n },\n )\n // Exercise the actual handler via the same path the production confirm\n // route uses. Without this, mutation tools whose handler crashes (e.g.\n // missing `ctx.tool` for the API operation runner) would be reported as\n // passing because `prepareMutation` never invokes the handler.\n // `prepareMutation` already enforced `tenantId` is non-null above; cast\n // here for the stricter `PendingActionExecuteContext` shape.\n const confirmTenantId = ctx.tenantId as string\n const confirmContainer = await createRequestContainer()\n const confirmation = await executePendingActionConfirm({\n action: pendingAction,\n agent,\n tool,\n ctx: {\n tenantId: confirmTenantId,\n organizationId: ctx.organizationId,\n userId,\n container: confirmContainer,\n userFeatures: ctx.userFeatures,\n isSuperAdmin: ctx.isSuperAdmin,\n },\n emitEvent: async () => {},\n })\n if (!confirmation.ok) {\n const error = (confirmation.executionResult as { error?: { message?: string } } | undefined)?.error\n const cause = confirmation.cause\n const causeMessage =\n cause instanceof Error\n ? cause.message\n : typeof cause === 'string'\n ? cause\n : null\n const message = error?.message ?? causeMessage ?? 'handler invocation failed'\n throw new Error(message)\n }\n return {\n status: 'pending-confirmation',\n pendingActionId: pendingAction.id,\n expiresAt: pendingAction.expiresAt.toISOString(),\n uiPartType: (uiPart as { type?: string } | undefined)?.type ?? null,\n handlerExecuted: true,\n }\n}\n\nasync function resolveFixtureInput(\n fixture: ToolFixture,\n resolved: Map<string, AiToolDefinition>,\n container: AwilixContainer,\n ctx: McpToolContext,\n): Promise<{ ok: true; input: Record<string, unknown> } | { ok: false; reason: string }> {\n if (fixture.input) return { ok: true, input: { ...fixture.input } }\n if (!fixture.idFrom) {\n return { ok: false, reason: 'fixture has neither input nor idFrom' }\n }\n const sourceTool = resolved.get(fixture.idFrom)\n if (!sourceTool) {\n return { ok: false, reason: `idFrom tool not found: ${fixture.idFrom}` }\n }\n const sourceFixture = getFixture(fixture.idFrom)\n if (!sourceFixture?.input) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} has no static input fixture`,\n }\n }\n let listResult: unknown\n try {\n listResult = await executeReadTool(\n sourceTool,\n { ...sourceFixture.input },\n container,\n ctx,\n )\n } catch (error) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} threw: ${\n error instanceof Error ? error.message : String(error)\n }`,\n }\n }\n const records = extractRecords(listResult)\n if (!records.length) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} returned no records`,\n }\n }\n const idField = 'id'\n const id = (records[0] as Record<string, unknown>)[idField]\n if (typeof id !== 'string' || !id) {\n return {\n ok: false,\n reason: `idFrom source ${fixture.idFrom} first record has no string id`,\n }\n }\n const bindAs = fixture.bindAs ?? 'id'\n return {\n ok: true,\n input: { [bindAs]: id, ...(fixture.extra ?? {}) },\n }\n}\n\nfunction extractRecords(value: unknown): unknown[] {\n if (!value || typeof value !== 'object') return []\n const candidate = value as Record<string, unknown>\n for (const key of ['records', 'items', 'people', 'companies', 'deals', 'results', 'data']) {\n const arr = candidate[key]\n if (Array.isArray(arr)) return arr\n }\n return []\n}\n\nexport interface RunToolTestsOptions {\n tenantId?: string | null\n organizationId?: string | null\n userId?: string | null\n moduleFilter?: string | null\n includeMutations?: boolean\n}\n\nexport async function runToolTests(\n options: RunToolTestsOptions = {},\n): Promise<ToolTestReport> {\n const includeMutations = options.includeMutations ?? true\n const container = await createRequestContainer()\n let tenantId: string | null = options.tenantId ?? null\n let organizationId: string | null = options.organizationId ?? null\n let userId: string | null = options.userId ?? null\n if (!tenantId) {\n const picked = await pickDefaultTenant(container)\n if (picked) {\n tenantId = picked.tenantId\n organizationId = picked.organizationId\n userId = userId ?? picked.userId\n }\n }\n const ctx = buildSuperAdminContext(container, tenantId, organizationId, userId)\n const grouped = await loadGeneratedTools()\n\n const flat: { moduleId: string; tool: AiToolDefinition }[] = []\n for (const group of grouped) {\n if (options.moduleFilter && group.moduleId !== options.moduleFilter) continue\n for (const tool of group.tools) flat.push({ moduleId: group.moduleId, tool })\n }\n const resolved = new Map<string, AiToolDefinition>()\n for (const { tool } of flat) resolved.set(tool.name, tool)\n\n const records: ToolTestRecord[] = []\n for (const { moduleId, tool } of flat) {\n const start = Date.now()\n const isMutation = tool.isMutation === true\n const fixture = getFixture(tool.name)\n if (!fixture) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: 'no fixture',\n })\n continue\n }\n if (fixture.skip) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: fixture.note ?? 'skip-by-fixture',\n })\n continue\n }\n if (isMutation && !includeMutations) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: 'mutations excluded',\n })\n continue\n }\n const inputResult = await resolveFixtureInput(fixture, resolved, container, ctx)\n if (!inputResult.ok) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'skip',\n durationMs: Date.now() - start,\n reason: inputResult.reason,\n })\n continue\n }\n try {\n const result = isMutation\n ? await executeMutationTool(tool, inputResult.input, container, ctx)\n : await executeReadTool(tool, inputResult.input, container, ctx)\n // Result must be JSON-serializable.\n JSON.stringify(result)\n // Mutation tools must return a pending-confirmation envelope.\n if (\n isMutation &&\n (typeof result !== 'object' ||\n result === null ||\n (result as Record<string, unknown>).status !== 'pending-confirmation')\n ) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'fail',\n durationMs: Date.now() - start,\n reason: 'mutation tool did not route through prepareMutation (no pending-confirmation envelope)',\n resultPreview: clipPreview(result),\n })\n continue\n }\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'pass',\n durationMs: Date.now() - start,\n resultPreview: clipPreview(result),\n })\n } catch (error) {\n records.push({\n module: moduleId,\n tool: tool.name,\n isMutation,\n status: 'fail',\n durationMs: Date.now() - start,\n reason: error instanceof Error ? error.message : String(error),\n })\n }\n }\n const passed = records.filter((r) => r.status === 'pass').length\n const failed = records.filter((r) => r.status === 'fail').length\n const skipped = records.filter((r) => r.status === 'skip').length\n return {\n tenantId,\n organizationId,\n total: records.length,\n passed,\n failed,\n skipped,\n records,\n }\n}\n"],
5
+ "mappings": "AAgBA,SAAS,oBAAoB;AAE7B,SAAS,8BAA8B;AAGvC,SAAS,kBAAoC;AAC7C,SAAS,uBAAuB;AAChC,SAAS,mCAAmC;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,cAAc;AA6B1C,SAAS,iBAAiB,OAA2C;AACnE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,YAAY;AAClB,SACE,OAAO,UAAU,SAAS,YAC1B,OAAO,UAAU,gB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K,IAAI,IAAI;AAAA,QACzB,eAAe,YAAY,MAAM;AAAA,MACnC,CAAC;AAAA,IACH,SAAS,OAAO;AACd,cAAQ,KAAK;AAAA,QACX,QAAQ;AAAA,QACR,MAAM,KAAK;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,QACR,YAAY,KAAK,IAAI,IAAI;AAAA,QACzB,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MAC/D,CAAC;AAAA,IACH;AAAA,EACF;AACA,QAAM,SAAS,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,EAAE;AAC1D,QAAM,SAAS,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,EAAE;AAC1D,QAAM,UAAU,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,MAAM,EAAE;AAC3D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,QAAQ;AAAA,IACf;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,6 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
1
2
  import { createHash } from "node:crypto";
3
+ const logger = createLogger("ai_assistant");
2
4
  const PENDING_ACTION_CLEANUP_SCHEDULE_KEY = "ai_assistant:pending-action-cleanup";
3
5
  const TOKEN_USAGE_PRUNE_SCHEDULE_KEY = "ai_assistant:token-usage-prune";
4
6
  function stableScheduleUuid(stableKey) {
@@ -33,10 +35,7 @@ async function ensurePendingActionCleanupSchedule(container) {
33
35
  isEnabled: true
34
36
  });
35
37
  } catch (error) {
36
- console.warn(
37
- "[ai_assistant] Failed to register pending-action cleanup schedule:",
38
- error instanceof Error ? error.message : error
39
- );
38
+ logger.warn("Failed to register pending-action cleanup schedule", { err: error });
40
39
  }
41
40
  }
42
41
  async function ensureTokenUsagePruneSchedule(container) {
@@ -65,10 +64,7 @@ async function ensureTokenUsagePruneSchedule(container) {
65
64
  isEnabled: true
66
65
  });
67
66
  } catch (error) {
68
- console.warn(
69
- "[ai_assistant] Failed to register token-usage prune schedule:",
70
- error instanceof Error ? error.message : error
71
- );
67
+ logger.warn("Failed to register token-usage prune schedule", { err: error });
72
68
  }
73
69
  }
74
70
  const setup = {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/ai_assistant/setup.ts"],
4
- "sourcesContent": ["import { createHash } from 'node:crypto'\nimport type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\n\nconst PENDING_ACTION_CLEANUP_SCHEDULE_KEY = 'ai_assistant:pending-action-cleanup'\nconst TOKEN_USAGE_PRUNE_SCHEDULE_KEY = 'ai_assistant:token-usage-prune'\n\nfunction stableScheduleUuid(stableKey: string): string {\n const hex = createHash('sha256').update(stableKey).digest('hex')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n\nconst PENDING_ACTION_CLEANUP_SCHEDULE_ID = stableScheduleUuid(PENDING_ACTION_CLEANUP_SCHEDULE_KEY)\nconst TOKEN_USAGE_PRUNE_SCHEDULE_ID = stableScheduleUuid(TOKEN_USAGE_PRUNE_SCHEDULE_KEY)\n\n/**\n * System-scoped recurring schedule: every 5 minutes, enqueue a job to the\n * `ai-pending-action-cleanup` queue so the worker can sweep rows whose TTL\n * elapsed without any confirm/cancel activity (Step 5.12). The schedule id\n * is stable and `scheduler.register()` is an upsert, so calling this from\n * every tenant bootstrap stays idempotent.\n */\nasync function ensurePendingActionCleanupSchedule(\n container: import('awilix').AwilixContainer | undefined,\n): Promise<void> {\n if (!container) return\n let schedulerService:\n | {\n register: (registration: Record<string, unknown>) => Promise<void>\n }\n | undefined\n try {\n schedulerService = container.resolve('schedulerService')\n } catch {\n schedulerService = undefined\n }\n if (!schedulerService) return\n try {\n await schedulerService.register({\n id: PENDING_ACTION_CLEANUP_SCHEDULE_ID,\n name: 'AI pending-action cleanup',\n description:\n 'Sweep pending AI mutation approvals whose TTL elapsed without confirm/cancel and flip them to expired.',\n scopeType: 'system',\n scheduleType: 'interval',\n scheduleValue: '5m',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: 'ai-pending-action-cleanup',\n targetPayload: {},\n sourceType: 'module',\n sourceModule: 'ai_assistant',\n isEnabled: true,\n })\n } catch (error) {\n console.warn(\n '[ai_assistant] Failed to register pending-action cleanup schedule:',\n error instanceof Error ? error.message : error,\n )\n }\n}\n\n/**\n * System-scoped daily schedule: enqueue a job to the `ai-token-usage-prune`\n * queue to prune events older than the retention window and reconcile the\n * daily rollup session counts.\n *\n * Phase 6.4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nasync function ensureTokenUsagePruneSchedule(\n container: import('awilix').AwilixContainer | undefined,\n): Promise<void> {\n if (!container) return\n let schedulerService:\n | {\n register: (registration: Record<string, unknown>) => Promise<void>\n }\n | undefined\n try {\n schedulerService = container.resolve('schedulerService')\n } catch {\n schedulerService = undefined\n }\n if (!schedulerService) return\n try {\n await schedulerService.register({\n id: TOKEN_USAGE_PRUNE_SCHEDULE_ID,\n name: 'AI token-usage prune',\n description:\n 'Delete ai_token_usage_events rows older than AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS (default 90) and reconcile session_count on the daily rollup.',\n scopeType: 'system',\n scheduleType: 'interval',\n scheduleValue: '24h',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: 'ai-token-usage-prune',\n targetPayload: {},\n sourceType: 'module',\n sourceModule: 'ai_assistant',\n isEnabled: true,\n })\n } catch (error) {\n console.warn(\n '[ai_assistant] Failed to register token-usage prune schedule:',\n error instanceof Error ? error.message : error,\n )\n }\n}\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n admin: [\n 'ai_assistant.view',\n 'ai_assistant.settings.manage',\n 'ai_assistant.conversations.manage',\n 'ai_assistant.conversations.share',\n 'ai_assistant.mcp.serve',\n 'ai_assistant.tools.list',\n 'ai_assistant.mcp_servers.view',\n 'ai_assistant.mcp_servers.manage',\n ],\n employee: ['ai_assistant.view', 'ai_assistant.conversations.share'],\n },\n\n async seedDefaults({ container }) {\n await ensurePendingActionCleanupSchedule(container)\n await ensureTokenUsagePruneSchedule(container)\n },\n}\n\nexport default setup\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAG3B,MAAM,sCAAsC;AAC5C,MAAM,iCAAiC;AAEvC,SAAS,mBAAmB,WAA2B;AACrD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK;AAC/D,SAAO,GAAG,IAAI,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC;AAC9G;AAEA,MAAM,qCAAqC,mBAAmB,mCAAmC;AACjG,MAAM,gCAAgC,mBAAmB,8BAA8B;AASvF,eAAe,mCACb,WACe;AACf,MAAI,CAAC,UAAW;AAChB,MAAI;AAKJ,MAAI;AACF,uBAAmB,UAAU,QAAQ,kBAAkB;AAAA,EACzD,QAAQ;AACN,uBAAmB;AAAA,EACrB;AACA,MAAI,CAAC,iBAAkB;AACvB,MAAI;AACF,UAAM,iBAAiB,SAAS;AAAA,MAC9B,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,aACE;AAAA,MACF,WAAW;AAAA,MACX,cAAc;AAAA,MACd,eAAe;AAAA,MACf,UAAU;AAAA,MACV,YAAY;AAAA,MACZ,aAAa;AAAA,MACb,eAAe,CAAC;AAAA,MAChB,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,WAAW;AAAA,IACb,CAAC;AAAA,EACH,SAAS,OAAO;AACd,YAAQ;AAAA,MACN;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU;AAAA,IAC3C;AAAA,EACF;AACF;AASA,eAAe,8BACb,WACe;AACf,MAAI,CAAC,UAAW;AAChB,MAAI;AAKJ,MAAI;AACF,uBAAmB,UAAU,QAAQ,kBAAkB;AAAA,EACzD,QAAQ;AACN,uBAAmB;AAAA,EACrB;AACA,MAAI,CAAC,iBAAkB;AACvB,MAAI;AACF,UAAM,iBAAiB,SAAS;AAAA,MAC9B,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,aACE;AAAA,MACF,WAAW;AAAA,MACX,cAAc;AAAA,MACd,eAAe;AAAA,MACf,UAAU;AAAA,MACV,YAAY;AAAA,MACZ,aAAa;AAAA,MACb,eAAe,CAAC;AAAA,MAChB,YAAY;AAAA,MACZ,cAAc;AAAA,MACd,WAAW;AAAA,IACb,CAAC;AAAA,EACH,SAAS,OAAO;AACd,YAAQ;AAAA,MACN;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU;AAAA,IAC3C;AAAA,EACF;AACF;AAEO,MAAM,QAA2B;AAAA,EACtC,qBAAqB;AAAA,IACnB,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,UAAU,CAAC,qBAAqB,kCAAkC;AAAA,EACpE;AAAA,EAEA,MAAM,aAAa,EAAE,UAAU,GAAG;AAChC,UAAM,mCAAmC,SAAS;AAClD,UAAM,8BAA8B,SAAS;AAAA,EAC/C;AACF;AAEA,IAAO,gBAAQ;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { createHash } from 'node:crypto'\nimport type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\n\nconst logger = createLogger('ai_assistant')\n\nconst PENDING_ACTION_CLEANUP_SCHEDULE_KEY = 'ai_assistant:pending-action-cleanup'\nconst TOKEN_USAGE_PRUNE_SCHEDULE_KEY = 'ai_assistant:token-usage-prune'\n\nfunction stableScheduleUuid(stableKey: string): string {\n const hex = createHash('sha256').update(stableKey).digest('hex')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`\n}\n\nconst PENDING_ACTION_CLEANUP_SCHEDULE_ID = stableScheduleUuid(PENDING_ACTION_CLEANUP_SCHEDULE_KEY)\nconst TOKEN_USAGE_PRUNE_SCHEDULE_ID = stableScheduleUuid(TOKEN_USAGE_PRUNE_SCHEDULE_KEY)\n\n/**\n * System-scoped recurring schedule: every 5 minutes, enqueue a job to the\n * `ai-pending-action-cleanup` queue so the worker can sweep rows whose TTL\n * elapsed without any confirm/cancel activity (Step 5.12). The schedule id\n * is stable and `scheduler.register()` is an upsert, so calling this from\n * every tenant bootstrap stays idempotent.\n */\nasync function ensurePendingActionCleanupSchedule(\n container: import('awilix').AwilixContainer | undefined,\n): Promise<void> {\n if (!container) return\n let schedulerService:\n | {\n register: (registration: Record<string, unknown>) => Promise<void>\n }\n | undefined\n try {\n schedulerService = container.resolve('schedulerService')\n } catch {\n schedulerService = undefined\n }\n if (!schedulerService) return\n try {\n await schedulerService.register({\n id: PENDING_ACTION_CLEANUP_SCHEDULE_ID,\n name: 'AI pending-action cleanup',\n description:\n 'Sweep pending AI mutation approvals whose TTL elapsed without confirm/cancel and flip them to expired.',\n scopeType: 'system',\n scheduleType: 'interval',\n scheduleValue: '5m',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: 'ai-pending-action-cleanup',\n targetPayload: {},\n sourceType: 'module',\n sourceModule: 'ai_assistant',\n isEnabled: true,\n })\n } catch (error) {\n logger.warn('Failed to register pending-action cleanup schedule', { err: error })\n }\n}\n\n/**\n * System-scoped daily schedule: enqueue a job to the `ai-token-usage-prune`\n * queue to prune events older than the retention window and reconcile the\n * daily rollup session counts.\n *\n * Phase 6.4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nasync function ensureTokenUsagePruneSchedule(\n container: import('awilix').AwilixContainer | undefined,\n): Promise<void> {\n if (!container) return\n let schedulerService:\n | {\n register: (registration: Record<string, unknown>) => Promise<void>\n }\n | undefined\n try {\n schedulerService = container.resolve('schedulerService')\n } catch {\n schedulerService = undefined\n }\n if (!schedulerService) return\n try {\n await schedulerService.register({\n id: TOKEN_USAGE_PRUNE_SCHEDULE_ID,\n name: 'AI token-usage prune',\n description:\n 'Delete ai_token_usage_events rows older than AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS (default 90) and reconcile session_count on the daily rollup.',\n scopeType: 'system',\n scheduleType: 'interval',\n scheduleValue: '24h',\n timezone: 'UTC',\n targetType: 'queue',\n targetQueue: 'ai-token-usage-prune',\n targetPayload: {},\n sourceType: 'module',\n sourceModule: 'ai_assistant',\n isEnabled: true,\n })\n } catch (error) {\n logger.warn('Failed to register token-usage prune schedule', { err: error })\n }\n}\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n admin: [\n 'ai_assistant.view',\n 'ai_assistant.settings.manage',\n 'ai_assistant.conversations.manage',\n 'ai_assistant.conversations.share',\n 'ai_assistant.mcp.serve',\n 'ai_assistant.tools.list',\n 'ai_assistant.mcp_servers.view',\n 'ai_assistant.mcp_servers.manage',\n ],\n employee: ['ai_assistant.view', 'ai_assistant.conversations.share'],\n },\n\n async seedDefaults({ container }) {\n await ensurePendingActionCleanupSchedule(container)\n await ensureTokenUsagePruneSchedule(container)\n },\n}\n\nexport default setup\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kBAAkB;AAG3B,MAAM,SAAS,aAAa,cAAc;AAE1C,MAAM,sCAAsC;AAC5C,MAAM,iCAAiC;AAEvC,SAAS,mBAAmB,WAA2B;AACrD,QAAM,MAAM,WAAW,QAAQ,EAAE,OAAO,SAAS,EAAE,OAAO,KAAK;AAC/D,SAAO,GAAG,IAAI,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI,MAAM,GAAG,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,EAAE,CAAC,IAAI,IAAI,MAAM,IAAI,E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AAAA,IACnB,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,UAAU,CAAC,qBAAqB,kCAAkC;AAAA,EACpE;AAAA,EAEA,MAAM,aAAa,EAAE,UAAU,GAAG;AAChC,UAAM,mCAAmC,SAAS;AAClD,UAAM,8BAA8B,SAAS;AAAA,EAC/C;AACF;AAEA,IAAO,gBAAQ;",
6
6
  "names": []
7
7
  }
@@ -1,9 +1,11 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
1
2
  import { resolveNotificationService } from "@open-mercato/core/modules/notifications/lib/notificationService";
2
3
  import { buildNotificationFromType } from "@open-mercato/core/modules/notifications/lib/notificationBuilder";
3
4
  import { defaultLocale } from "@open-mercato/shared/lib/i18n/config";
4
5
  import { loadDictionary } from "@open-mercato/shared/lib/i18n/server";
5
6
  import { createTranslator } from "@open-mercato/shared/lib/i18n/translate";
6
7
  import { notificationTypes } from "../notifications.js";
8
+ const logger = createLogger("ai_assistant");
7
9
  const metadata = {
8
10
  event: "ai_assistant.conversation.shared",
9
11
  persistent: true,
@@ -49,7 +51,7 @@ async function handleConversationShared(payload, ctx) {
49
51
  organizationId: payload.organizationId ?? null
50
52
  });
51
53
  } catch (err) {
52
- console.warn("[ai_assistant.conversationSharedNotify] create failed", err);
54
+ logger.warn("ai_assistant.conversationSharedNotify \u2014 create failed", { err });
53
55
  }
54
56
  }
55
57
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/subscribers/conversation-shared-notify.ts"],
4
- "sourcesContent": ["import { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { defaultLocale } from '@open-mercato/shared/lib/i18n/config'\nimport { loadDictionary } from '@open-mercato/shared/lib/i18n/server'\nimport { createTranslator } from '@open-mercato/shared/lib/i18n/translate'\nimport { notificationTypes } from '../notifications'\nimport type { AiConversationSharedPayload } from '../events'\n\nexport const metadata = {\n event: 'ai_assistant.conversation.shared',\n persistent: true,\n id: 'ai_assistant:conversation-shared-notify',\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n container?: { resolve<T = unknown>(name: string): T }\n}\n\nasync function resolveDefaultLocaleStrings(\n titleKey: string | undefined,\n bodyKey: string | undefined,\n): Promise<{ title: string | undefined; body: string | undefined }> {\n if (!titleKey && !bodyKey) return { title: titleKey, body: bodyKey }\n try {\n const dict = await loadDictionary(defaultLocale)\n const t = createTranslator(dict)\n return {\n title: titleKey ? t(titleKey) : titleKey,\n body: bodyKey ? t(bodyKey) : bodyKey,\n }\n } catch {\n return { title: titleKey, body: bodyKey }\n }\n}\n\nexport default async function handleConversationShared(\n payload: AiConversationSharedPayload,\n ctx: ResolverContext,\n): Promise<void> {\n if (!payload?.participantUserId || !payload.tenantId) return\n\n const typeDef = notificationTypes.find((t) => t.type === 'ai_assistant.conversation_shared')\n if (!typeDef) return\n\n const container = ctx.container ?? { resolve: ctx.resolve }\n let notificationService: ReturnType<typeof resolveNotificationService> | null\n try {\n notificationService = resolveNotificationService(container)\n } catch {\n return\n }\n\n const notificationInput = buildNotificationFromType(typeDef, {\n recipientUserId: payload.participantUserId,\n bodyVariables: {},\n sourceEntityType: 'ai_assistant:ai_chat_conversation',\n sourceEntityId: payload.conversationId,\n linkHref: `/backend?openAiConversation=${payload.conversationId}`,\n })\n\n // Persist a human-readable fallback alongside the i18n keys so consumers\n // that do not run the client renderer (email digests, exports) display a\n // resolved string instead of the raw key. The client renderer continues\n // to re-translate via titleKey/bodyKey for the viewer's locale.\n const resolved = await resolveDefaultLocaleStrings(typeDef.titleKey, typeDef.bodyKey)\n if (resolved.title !== undefined) notificationInput.title = resolved.title\n if (resolved.body !== undefined) notificationInput.body = resolved.body\n\n try {\n await notificationService.create(notificationInput, {\n tenantId: payload.tenantId,\n organizationId: payload.organizationId ?? null,\n })\n } catch (err) {\n console.warn('[ai_assistant.conversationSharedNotify] create failed', err)\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,kCAAkC;AAC3C,SAAS,iCAAiC;AAC1C,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAG3B,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAOA,eAAe,4BACb,UACA,SACkE;AAClE,MAAI,CAAC,YAAY,CAAC,QAAS,QAAO,EAAE,OAAO,UAAU,MAAM,QAAQ;AACnE,MAAI;AACF,UAAM,OAAO,MAAM,eAAe,aAAa;AAC/C,UAAM,IAAI,iBAAiB,IAAI;AAC/B,WAAO;AAAA,MACL,OAAO,WAAW,EAAE,QAAQ,IAAI;AAAA,MAChC,MAAM,UAAU,EAAE,OAAO,IAAI;AAAA,IAC/B;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,OAAO,UAAU,MAAM,QAAQ;AAAA,EAC1C;AACF;AAEA,eAAO,yBACL,SACA,KACe;AACf,MAAI,CAAC,SAAS,qBAAqB,CAAC,QAAQ,SAAU;AAEtD,QAAM,UAAU,kBAAkB,KAAK,CAAC,MAAM,EAAE,SAAS,kCAAkC;AAC3F,MAAI,CAAC,QAAS;AAEd,QAAM,YAAY,IAAI,aAAa,EAAE,SAAS,IAAI,QAAQ;AAC1D,MAAI;AACJ,MAAI;AACF,0BAAsB,2BAA2B,SAAS;AAAA,EAC5D,QAAQ;AACN;AAAA,EACF;AAEA,QAAM,oBAAoB,0BAA0B,SAAS;AAAA,IAC3D,iBAAiB,QAAQ;AAAA,IACzB,eAAe,CAAC;AAAA,IAChB,kBAAkB;AAAA,IAClB,gBAAgB,QAAQ;AAAA,IACxB,UAAU,+BAA+B,QAAQ,cAAc;AAAA,EACjE,CAAC;AAMD,QAAM,WAAW,MAAM,4BAA4B,QAAQ,UAAU,QAAQ,OAAO;AACpF,MAAI,SAAS,UAAU,OAAW,mBAAkB,QAAQ,SAAS;AACrE,MAAI,SAAS,SAAS,OAAW,mBAAkB,OAAO,SAAS;AAEnE,MAAI;AACF,UAAM,oBAAoB,OAAO,mBAAmB;AAAA,MAClD,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ,kBAAkB;AAAA,IAC5C,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,YAAQ,KAAK,yDAAyD,GAAG;AAAA,EAC3E;AACF;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport { resolveNotificationService } from '@open-mercato/core/modules/notifications/lib/notificationService'\nimport { buildNotificationFromType } from '@open-mercato/core/modules/notifications/lib/notificationBuilder'\nimport { defaultLocale } from '@open-mercato/shared/lib/i18n/config'\nimport { loadDictionary } from '@open-mercato/shared/lib/i18n/server'\nimport { createTranslator } from '@open-mercato/shared/lib/i18n/translate'\nimport { notificationTypes } from '../notifications'\nimport type { AiConversationSharedPayload } from '../events'\n\nconst logger = createLogger('ai_assistant')\n\nexport const metadata = {\n event: 'ai_assistant.conversation.shared',\n persistent: true,\n id: 'ai_assistant:conversation-shared-notify',\n}\n\ntype ResolverContext = {\n resolve: <T = unknown>(name: string) => T\n container?: { resolve<T = unknown>(name: string): T }\n}\n\nasync function resolveDefaultLocaleStrings(\n titleKey: string | undefined,\n bodyKey: string | undefined,\n): Promise<{ title: string | undefined; body: string | undefined }> {\n if (!titleKey && !bodyKey) return { title: titleKey, body: bodyKey }\n try {\n const dict = await loadDictionary(defaultLocale)\n const t = createTranslator(dict)\n return {\n title: titleKey ? t(titleKey) : titleKey,\n body: bodyKey ? t(bodyKey) : bodyKey,\n }\n } catch {\n return { title: titleKey, body: bodyKey }\n }\n}\n\nexport default async function handleConversationShared(\n payload: AiConversationSharedPayload,\n ctx: ResolverContext,\n): Promise<void> {\n if (!payload?.participantUserId || !payload.tenantId) return\n\n const typeDef = notificationTypes.find((t) => t.type === 'ai_assistant.conversation_shared')\n if (!typeDef) return\n\n const container = ctx.container ?? { resolve: ctx.resolve }\n let notificationService: ReturnType<typeof resolveNotificationService> | null\n try {\n notificationService = resolveNotificationService(container)\n } catch {\n return\n }\n\n const notificationInput = buildNotificationFromType(typeDef, {\n recipientUserId: payload.participantUserId,\n bodyVariables: {},\n sourceEntityType: 'ai_assistant:ai_chat_conversation',\n sourceEntityId: payload.conversationId,\n linkHref: `/backend?openAiConversation=${payload.conversationId}`,\n })\n\n // Persist a human-readable fallback alongside the i18n keys so consumers\n // that do not run the client renderer (email digests, exports) display a\n // resolved string instead of the raw key. The client renderer continues\n // to re-translate via titleKey/bodyKey for the viewer's locale.\n const resolved = await resolveDefaultLocaleStrings(typeDef.titleKey, typeDef.bodyKey)\n if (resolved.title !== undefined) notificationInput.title = resolved.title\n if (resolved.body !== undefined) notificationInput.body = resolved.body\n\n try {\n await notificationService.create(notificationInput, {\n tenantId: payload.tenantId,\n organizationId: payload.organizationId ?? null,\n })\n } catch (err) {\n logger.warn('ai_assistant.conversationSharedNotify \u2014 create failed', { err: err })\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAC3C,SAAS,iCAAiC;AAC1C,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAGlC,MAAM,SAAS,aAAa,cAAc;AAEnC,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AAOA,eAAe,4BACb,UACA,SACkE;AAClE,MAAI,CAAC,YAAY,CAAC,QAAS,QAAO,EAAE,OAAO,UAAU,MAAM,QAAQ;AACnE,MAAI;AACF,UAAM,OAAO,MAAM,eAAe,aAAa;AAC/C,UAAM,IAAI,iBAAiB,IAAI;AAC/B,WAAO;AAAA,MACL,OAAO,WAAW,EAAE,QAAQ,IAAI;AAAA,MAChC,MAAM,UAAU,EAAE,OAAO,IAAI;AAAA,IAC/B;AAAA,EACF,QAAQ;AACN,WAAO,EAAE,OAAO,UAAU,MAAM,QAAQ;AAAA,EAC1C;AACF;AAEA,eAAO,yBACL,SACA,KACe;AACf,MAAI,CAAC,SAAS,qBAAqB,CAAC,QAAQ,SAAU;AAEtD,QAAM,UAAU,kBAAkB,KAAK,CAAC,MAAM,EAAE,SAAS,kCAAkC;AAC3F,MAAI,CAAC,QAAS;AAEd,QAAM,YAAY,IAAI,aAAa,EAAE,SAAS,IAAI,QAAQ;AAC1D,MAAI;AACJ,MAAI;AACF,0BAAsB,2BAA2B,SAAS;AAAA,EAC5D,QAAQ;AACN;AAAA,EACF;AAEA,QAAM,oBAAoB,0BAA0B,SAAS;AAAA,IAC3D,iBAAiB,QAAQ;AAAA,IACzB,eAAe,CAAC;AAAA,IAChB,kBAAkB;AAAA,IAClB,gBAAgB,QAAQ;AAAA,IACxB,UAAU,+BAA+B,QAAQ,cAAc;AAAA,EACjE,CAAC;AAMD,QAAM,WAAW,MAAM,4BAA4B,QAAQ,UAAU,QAAQ,OAAO;AACpF,MAAI,SAAS,UAAU,OAAW,mBAAkB,QAAQ,SAAS;AACrE,MAAI,SAAS,SAAS,OAAW,mBAAkB,OAAO,SAAS;AAEnE,MAAI;AACF,UAAM,oBAAoB,OAAO,mBAAmB;AAAA,MAClD,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ,kBAAkB;AAAA,IAC5C,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,WAAO,KAAK,8DAAyD,EAAE,IAAS,CAAC;AAAA,EACnF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,8 +1,10 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
1
2
  import { AiPendingActionRepository } from "../data/repositories/AiPendingActionRepository.js";
2
3
  import {
3
4
  emitAiAssistantEvent
4
5
  } from "../events.js";
5
6
  import { AiPendingActionStateError } from "../lib/pending-action-types.js";
7
+ const logger = createLogger("ai_assistant");
6
8
  const metadata = {
7
9
  queue: "ai-pending-action-cleanup",
8
10
  id: "ai_assistant:cleanup-expired-pending-actions",
@@ -77,10 +79,7 @@ async function runPendingActionCleanup(options) {
77
79
  try {
78
80
  tenants = await discoverTenants(options.em, clock);
79
81
  } catch (error) {
80
- console.error(
81
- "[ai-pending-action-cleanup] Failed to discover tenants:",
82
- error
83
- );
82
+ logger.error("Failed to discover tenants", { err: error });
84
83
  return summary;
85
84
  }
86
85
  if (!tenants.length) return summary;
@@ -99,10 +98,7 @@ async function runPendingActionCleanup(options) {
99
98
  pageSize
100
99
  );
101
100
  } catch (error) {
102
- console.error(
103
- `[ai-pending-action-cleanup] listExpired failed for tenant ${scope.tenantId}:`,
104
- error
105
- );
101
+ logger.error("listExpired failed for tenant", { tenantId: scope.tenantId, err: error });
106
102
  break;
107
103
  }
108
104
  if (!expiredRows.length) break;
@@ -124,24 +120,16 @@ async function runPendingActionCleanup(options) {
124
120
  try {
125
121
  await emitter("ai.action.expired", payload);
126
122
  } catch (emitError) {
127
- console.warn(
128
- `[ai-pending-action-cleanup] Failed to emit ai.action.expired for ${row.id}:`,
129
- emitError
130
- );
123
+ logger.warn("Failed to emit ai.action.expired", { pendingActionId: row.id, err: emitError });
131
124
  }
132
125
  } catch (error) {
133
126
  if (error instanceof AiPendingActionStateError) {
134
127
  summary.rowsSkipped += 1;
135
- console.info(
136
- `[ai-pending-action-cleanup] Skipping ${row.id}: concurrent transition ${error.from} \u2192 ${error.to} already occurred`
137
- );
128
+ logger.info("Skipping pending action: concurrent transition already occurred", { pendingActionId: row.id, from: error.from, to: error.to });
138
129
  continue;
139
130
  }
140
131
  summary.rowsErrored += 1;
141
- console.error(
142
- `[ai-pending-action-cleanup] Failed to expire ${row.id}:`,
143
- error
144
- );
132
+ logger.error("Failed to expire pending action", { pendingActionId: row.id, err: error });
145
133
  }
146
134
  }
147
135
  if (expiredRows.length < pageSize) break;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/workers/ai-pending-action-cleanup.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\nimport { AiPendingActionRepository } from '../data/repositories/AiPendingActionRepository'\nimport type { AiPendingAction } from '../data/entities'\nimport {\n emitAiAssistantEvent,\n type AiActionExpiredPayload,\n type AiAssistantEventId,\n} from '../events'\nimport { AiPendingActionStateError } from '../lib/pending-action-types'\n\n/**\n * Periodic cleanup worker for the Phase 3 WS-C mutation approval gate\n * (Step 5.12).\n *\n * Responsibilities:\n * - Sweep every tenant for rows where `status = 'pending'` AND\n * `expires_at < now`. Pending actions expire after\n * `AI_PENDING_ACTION_TTL_SECONDS` (default 15 minutes) \u2014 confirm/cancel\n * routes flip them opportunistically, but rows nobody touches again\n * would otherwise sit in `pending` forever.\n * - Atomically transition each expired row `pending \u2192 expired` via the\n * repository's state-machine guard. `resolvedByUserId` is `null`\n * because the worker (not a user) is the actor; `resolvedAt` is `now`.\n * - Emit the typed `ai.action.expired` event via\n * {@link emitAiAssistantEvent} for each successful transition so\n * downstream subscribers (UI, audit, metrics) see a single canonical\n * terminal signal.\n *\n * Race safety:\n * - `AiPendingActionRepository.setStatus` enforces the state machine\n * from `pending-action-types.ts`; the legal exits for `pending` are\n * `confirmed`, `cancelled`, `expired`. If a concurrent confirm raced\n * us and flipped the row to `confirmed` (or `executing`), the repo\n * throws {@link AiPendingActionStateError} \u2014 we catch, log, and skip,\n * WITHOUT emitting an event for that row (the confirm path already\n * emitted the canonical signal). Same behaviour if the cancel helper\n * beat us via its TTL short-circuit.\n * - Single-row failures NEVER abort the batch \u2014 the worker logs and\n * continues to the next row.\n * - Running the worker twice on an already-`expired` row is a no-op:\n * `setStatus(expired)` short-circuits on `existing.status === nextStatus`\n * (see repo), so no second emit.\n *\n * Tenant scoping:\n * - `listExpired` is tenant-scoped, so the worker first discovers the\n * distinct set of `tenant_id` values that have expired pending rows\n * via a narrow native SELECT (no row contents read). It then iterates\n * per tenant, reusing the repo and therefore the encrypted-read\n * contract. Each `setStatus` write carries the row's own tenant\n * scope \u2014 there is no cross-tenant write.\n *\n * Pagination:\n * - `listExpired` is called with a bounded page size and looped until\n * the tenant's expired queue drains. A per-tenant loop cap prevents\n * runaway behaviour if new rows keep expiring during the sweep (the\n * next scheduled tick picks up any leftovers).\n */\n\nexport const metadata: WorkerMeta = {\n queue: 'ai-pending-action-cleanup',\n id: 'ai_assistant:cleanup-expired-pending-actions',\n concurrency: 1,\n}\n\nconst DEFAULT_PAGE_SIZE = 100\nconst MAX_PAGES_PER_TENANT = 50\n\nexport type PendingActionCleanupEmitter = (\n eventId: Extract<AiAssistantEventId, 'ai.action.expired'>,\n payload: AiActionExpiredPayload,\n) => Promise<void>\n\nconst defaultEmitter: PendingActionCleanupEmitter = async (eventId, payload) => {\n await emitAiAssistantEvent(eventId, payload as unknown as Record<string, unknown>, {\n persistent: true,\n })\n}\n\nexport interface PendingActionCleanupRunOptions {\n em: EntityManager\n repo?: AiPendingActionRepository\n emitEvent?: PendingActionCleanupEmitter\n now?: Date\n pageSize?: number\n /** Injectable tenant-discovery seam for unit tests. */\n discoverTenants?: (em: EntityManager, now: Date) => Promise<TenantScope[]>\n}\n\nexport interface PendingActionCleanupSummary {\n tenantsScanned: number\n rowsProcessed: number\n rowsExpired: number\n rowsSkipped: number\n rowsErrored: number\n}\n\nexport interface TenantScope {\n tenantId: string\n organizationId: string | null\n}\n\nasync function discoverTenantsDefault(\n em: EntityManager,\n now: Date,\n): Promise<TenantScope[]> {\n const connection = em.getConnection()\n const rows = await connection.execute(\n `select distinct \"tenant_id\", \"organization_id\"\n from \"ai_pending_actions\"\n where \"status\" = 'pending'\n and \"expires_at\" < ?`,\n [now],\n 'all',\n )\n if (!Array.isArray(rows)) return []\n const out: TenantScope[] = []\n for (const row of rows as Array<Record<string, unknown>>) {\n const tenantId = typeof row.tenant_id === 'string' ? row.tenant_id : null\n if (!tenantId) continue\n const organizationId =\n typeof row.organization_id === 'string' ? row.organization_id : null\n out.push({ tenantId, organizationId })\n }\n return out\n}\n\nfunction toIso(value: Date | string | null | undefined, fallback: Date): string {\n if (value instanceof Date) return value.toISOString()\n if (typeof value === 'string') {\n const parsed = new Date(value)\n if (!Number.isNaN(parsed.getTime())) return parsed.toISOString()\n }\n return fallback.toISOString()\n}\n\nfunction buildExpiredPayload(\n row: AiPendingAction,\n scope: TenantScope,\n clock: Date,\n): AiActionExpiredPayload {\n const resolvedAtIso = toIso(row.resolvedAt ?? clock, clock)\n const expiresAtIso = toIso(row.expiresAt ?? clock, clock)\n return {\n pendingActionId: row.id,\n agentId: row.agentId,\n toolName: row.toolName,\n status: row.status,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId ?? null,\n userId: row.createdByUserId ?? null,\n resolvedByUserId: null,\n resolvedAt: resolvedAtIso,\n expiresAt: expiresAtIso,\n expiredAt: resolvedAtIso,\n }\n}\n\nexport async function runPendingActionCleanup(\n options: PendingActionCleanupRunOptions,\n): Promise<PendingActionCleanupSummary> {\n const clock = options.now ?? new Date()\n const repo = options.repo ?? new AiPendingActionRepository(options.em)\n const emitter = options.emitEvent ?? defaultEmitter\n const pageSize = Math.max(1, Math.min(500, options.pageSize ?? DEFAULT_PAGE_SIZE))\n const discoverTenants = options.discoverTenants ?? discoverTenantsDefault\n\n const summary: PendingActionCleanupSummary = {\n tenantsScanned: 0,\n rowsProcessed: 0,\n rowsExpired: 0,\n rowsSkipped: 0,\n rowsErrored: 0,\n }\n\n let tenants: TenantScope[] = []\n try {\n tenants = await discoverTenants(options.em, clock)\n } catch (error) {\n console.error(\n '[ai-pending-action-cleanup] Failed to discover tenants:',\n error,\n )\n return summary\n }\n\n if (!tenants.length) return summary\n\n for (const scope of tenants) {\n summary.tenantsScanned += 1\n for (let page = 0; page < MAX_PAGES_PER_TENANT; page += 1) {\n let expiredRows: AiPendingAction[]\n try {\n expiredRows = await repo.listExpired(\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: null,\n },\n clock,\n pageSize,\n )\n } catch (error) {\n console.error(\n `[ai-pending-action-cleanup] listExpired failed for tenant ${scope.tenantId}:`,\n error,\n )\n break\n }\n\n if (!expiredRows.length) break\n\n for (const row of expiredRows) {\n summary.rowsProcessed += 1\n try {\n const updated = await repo.setStatus(\n row.id,\n 'expired',\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: null,\n },\n { resolvedByUserId: null, now: clock },\n )\n summary.rowsExpired += 1\n const payload = buildExpiredPayload(updated, scope, clock)\n try {\n await emitter('ai.action.expired', payload)\n } catch (emitError) {\n console.warn(\n `[ai-pending-action-cleanup] Failed to emit ai.action.expired for ${row.id}:`,\n emitError,\n )\n }\n } catch (error) {\n if (error instanceof AiPendingActionStateError) {\n summary.rowsSkipped += 1\n console.info(\n `[ai-pending-action-cleanup] Skipping ${row.id}: concurrent transition ${error.from} \u2192 ${error.to} already occurred`,\n )\n continue\n }\n summary.rowsErrored += 1\n console.error(\n `[ai-pending-action-cleanup] Failed to expire ${row.id}:`,\n error,\n )\n }\n }\n\n if (expiredRows.length < pageSize) break\n }\n }\n\n return summary\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(\n _job: QueuedJob,\n ctx: HandlerContext,\n): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n await runPendingActionCleanup({ em })\n}\n"],
5
- "mappings": "AAEA,SAAS,iCAAiC;AAE1C;AAAA,EACE;AAAA,OAGK;AACP,SAAS,iCAAiC;AAkDnC,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAEA,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAO7B,MAAM,iBAA8C,OAAO,SAAS,YAAY;AAC9E,QAAM,qBAAqB,SAAS,SAA+C;AAAA,IACjF,YAAY;AAAA,EACd,CAAC;AACH;AAyBA,eAAe,uBACb,IACA,KACwB;AAC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UAAU,oBAAoB,SAAS,OAAO,KAAK;AACzD,cAAI;AACF,kBAAM,QAAQ,qBAAqB,OAAO;AAAA,UAC5C,SAAS,WAAW;AAClB,oBAAQ;AAAA,cACN,oEAAoE,IAAI,EAAE;AAAA,cAC1E;AAAA,YACF;AAAA,UACF;AAAA,QACF,SAAS,OAAO;AACd,cAAI,iBAAiB,2BAA2B;AAC9C,oBAAQ,eAAe;AACvB,oBAAQ;AAAA,cACN,wCAAwC,IAAI,EAAE,2BAA2B,MAAM,IAAI,WAAM,MAAM,EAAE;AAAA,YACnG;AACA;AAAA,UACF;AACA,kBAAQ,eAAe;AACvB,kBAAQ;AAAA,YACN,gDAAgD,IAAI,EAAE;AAAA,YACtD;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAEA,UAAI,YAAY,SAAS,SAAU;AAAA,IACrC;AAAA,EACF;AAEA,SAAO;AACT;AAMA,eAAO,OACL,MACA,KACe;AACf,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,wBAAwB,EAAE,GAAG,CAAC;AACtC;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\nimport { AiPendingActionRepository } from '../data/repositories/AiPendingActionRepository'\nimport type { AiPendingAction } from '../data/entities'\nimport {\n emitAiAssistantEvent,\n type AiActionExpiredPayload,\n type AiAssistantEventId,\n} from '../events'\nimport { AiPendingActionStateError } from '../lib/pending-action-types'\n\nconst logger = createLogger('ai_assistant')\n\n/**\n * Periodic cleanup worker for the Phase 3 WS-C mutation approval gate\n * (Step 5.12).\n *\n * Responsibilities:\n * - Sweep every tenant for rows where `status = 'pending'` AND\n * `expires_at < now`. Pending actions expire after\n * `AI_PENDING_ACTION_TTL_SECONDS` (default 15 minutes) \u2014 confirm/cancel\n * routes flip them opportunistically, but rows nobody touches again\n * would otherwise sit in `pending` forever.\n * - Atomically transition each expired row `pending \u2192 expired` via the\n * repository's state-machine guard. `resolvedByUserId` is `null`\n * because the worker (not a user) is the actor; `resolvedAt` is `now`.\n * - Emit the typed `ai.action.expired` event via\n * {@link emitAiAssistantEvent} for each successful transition so\n * downstream subscribers (UI, audit, metrics) see a single canonical\n * terminal signal.\n *\n * Race safety:\n * - `AiPendingActionRepository.setStatus` enforces the state machine\n * from `pending-action-types.ts`; the legal exits for `pending` are\n * `confirmed`, `cancelled`, `expired`. If a concurrent confirm raced\n * us and flipped the row to `confirmed` (or `executing`), the repo\n * throws {@link AiPendingActionStateError} \u2014 we catch, log, and skip,\n * WITHOUT emitting an event for that row (the confirm path already\n * emitted the canonical signal). Same behaviour if the cancel helper\n * beat us via its TTL short-circuit.\n * - Single-row failures NEVER abort the batch \u2014 the worker logs and\n * continues to the next row.\n * - Running the worker twice on an already-`expired` row is a no-op:\n * `setStatus(expired)` short-circuits on `existing.status === nextStatus`\n * (see repo), so no second emit.\n *\n * Tenant scoping:\n * - `listExpired` is tenant-scoped, so the worker first discovers the\n * distinct set of `tenant_id` values that have expired pending rows\n * via a narrow native SELECT (no row contents read). It then iterates\n * per tenant, reusing the repo and therefore the encrypted-read\n * contract. Each `setStatus` write carries the row's own tenant\n * scope \u2014 there is no cross-tenant write.\n *\n * Pagination:\n * - `listExpired` is called with a bounded page size and looped until\n * the tenant's expired queue drains. A per-tenant loop cap prevents\n * runaway behaviour if new rows keep expiring during the sweep (the\n * next scheduled tick picks up any leftovers).\n */\n\nexport const metadata: WorkerMeta = {\n queue: 'ai-pending-action-cleanup',\n id: 'ai_assistant:cleanup-expired-pending-actions',\n concurrency: 1,\n}\n\nconst DEFAULT_PAGE_SIZE = 100\nconst MAX_PAGES_PER_TENANT = 50\n\nexport type PendingActionCleanupEmitter = (\n eventId: Extract<AiAssistantEventId, 'ai.action.expired'>,\n payload: AiActionExpiredPayload,\n) => Promise<void>\n\nconst defaultEmitter: PendingActionCleanupEmitter = async (eventId, payload) => {\n await emitAiAssistantEvent(eventId, payload as unknown as Record<string, unknown>, {\n persistent: true,\n })\n}\n\nexport interface PendingActionCleanupRunOptions {\n em: EntityManager\n repo?: AiPendingActionRepository\n emitEvent?: PendingActionCleanupEmitter\n now?: Date\n pageSize?: number\n /** Injectable tenant-discovery seam for unit tests. */\n discoverTenants?: (em: EntityManager, now: Date) => Promise<TenantScope[]>\n}\n\nexport interface PendingActionCleanupSummary {\n tenantsScanned: number\n rowsProcessed: number\n rowsExpired: number\n rowsSkipped: number\n rowsErrored: number\n}\n\nexport interface TenantScope {\n tenantId: string\n organizationId: string | null\n}\n\nasync function discoverTenantsDefault(\n em: EntityManager,\n now: Date,\n): Promise<TenantScope[]> {\n const connection = em.getConnection()\n const rows = await connection.execute(\n `select distinct \"tenant_id\", \"organization_id\"\n from \"ai_pending_actions\"\n where \"status\" = 'pending'\n and \"expires_at\" < ?`,\n [now],\n 'all',\n )\n if (!Array.isArray(rows)) return []\n const out: TenantScope[] = []\n for (const row of rows as Array<Record<string, unknown>>) {\n const tenantId = typeof row.tenant_id === 'string' ? row.tenant_id : null\n if (!tenantId) continue\n const organizationId =\n typeof row.organization_id === 'string' ? row.organization_id : null\n out.push({ tenantId, organizationId })\n }\n return out\n}\n\nfunction toIso(value: Date | string | null | undefined, fallback: Date): string {\n if (value instanceof Date) return value.toISOString()\n if (typeof value === 'string') {\n const parsed = new Date(value)\n if (!Number.isNaN(parsed.getTime())) return parsed.toISOString()\n }\n return fallback.toISOString()\n}\n\nfunction buildExpiredPayload(\n row: AiPendingAction,\n scope: TenantScope,\n clock: Date,\n): AiActionExpiredPayload {\n const resolvedAtIso = toIso(row.resolvedAt ?? clock, clock)\n const expiresAtIso = toIso(row.expiresAt ?? clock, clock)\n return {\n pendingActionId: row.id,\n agentId: row.agentId,\n toolName: row.toolName,\n status: row.status,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId ?? null,\n userId: row.createdByUserId ?? null,\n resolvedByUserId: null,\n resolvedAt: resolvedAtIso,\n expiresAt: expiresAtIso,\n expiredAt: resolvedAtIso,\n }\n}\n\nexport async function runPendingActionCleanup(\n options: PendingActionCleanupRunOptions,\n): Promise<PendingActionCleanupSummary> {\n const clock = options.now ?? new Date()\n const repo = options.repo ?? new AiPendingActionRepository(options.em)\n const emitter = options.emitEvent ?? defaultEmitter\n const pageSize = Math.max(1, Math.min(500, options.pageSize ?? DEFAULT_PAGE_SIZE))\n const discoverTenants = options.discoverTenants ?? discoverTenantsDefault\n\n const summary: PendingActionCleanupSummary = {\n tenantsScanned: 0,\n rowsProcessed: 0,\n rowsExpired: 0,\n rowsSkipped: 0,\n rowsErrored: 0,\n }\n\n let tenants: TenantScope[] = []\n try {\n tenants = await discoverTenants(options.em, clock)\n } catch (error) {\n logger.error('Failed to discover tenants', { err: error })\n return summary\n }\n\n if (!tenants.length) return summary\n\n for (const scope of tenants) {\n summary.tenantsScanned += 1\n for (let page = 0; page < MAX_PAGES_PER_TENANT; page += 1) {\n let expiredRows: AiPendingAction[]\n try {\n expiredRows = await repo.listExpired(\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: null,\n },\n clock,\n pageSize,\n )\n } catch (error) {\n logger.error('listExpired failed for tenant', { tenantId: scope.tenantId, err: error })\n break\n }\n\n if (!expiredRows.length) break\n\n for (const row of expiredRows) {\n summary.rowsProcessed += 1\n try {\n const updated = await repo.setStatus(\n row.id,\n 'expired',\n {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: null,\n },\n { resolvedByUserId: null, now: clock },\n )\n summary.rowsExpired += 1\n const payload = buildExpiredPayload(updated, scope, clock)\n try {\n await emitter('ai.action.expired', payload)\n } catch (emitError) {\n logger.warn('Failed to emit ai.action.expired', { pendingActionId: row.id, err: emitError })\n }\n } catch (error) {\n if (error instanceof AiPendingActionStateError) {\n summary.rowsSkipped += 1\n logger.info('Skipping pending action: concurrent transition already occurred', { pendingActionId: row.id, from: error.from, to: error.to })\n continue\n }\n summary.rowsErrored += 1\n logger.error('Failed to expire pending action', { pendingActionId: row.id, err: error })\n }\n }\n\n if (expiredRows.length < pageSize) break\n }\n }\n\n return summary\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(\n _job: QueuedJob,\n ctx: HandlerContext,\n): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n await runPendingActionCleanup({ em })\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAG7B,SAAS,iCAAiC;AAE1C;AAAA,EACE;AAAA,OAGK;AACP,SAAS,iCAAiC;AAE1C,MAAM,SAAS,aAAa,cAAc;AAkDnC,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAEA,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAO7B,MAAM,iBAA8C,OAAO,SAAS,YAAY;AAC9E,QAAM,qBAAqB,SAAS,SAA+C;AAAA,IACjF,YAAY;AAAA,EACd,CAAC;AACH;AAyBA,eAAe,uBACb,IACA,KACwB;AACxB,QAAM,aAAa,GAAG,cAAc;AACpC,QAAM,OAAO,MAAM,WAAW;AAAA,IAC5B;AAAA;AAAA;AAAA;AAAA,IAIA,CAAC,GAAG;AAAA,IACJ;AAAA,EACF;AACA,MAAI,CAAC,MAAM,QAAQ,IAAI,EAAG,QAAO,CAAC;AAClC,QAAM,MAAqB,CAAC;AAC5B,aAAW,OAAO,MAAwC;AACxD,UAAM,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,YAAY;AACrE,QAAI,CAAC,SAAU;AACf,UAAM,iBACJ,OAAO,IAAI,oBAAoB,WAAW,IAAI,kBAAkB;AAClE,QAAI,KAAK,EAAE,UAAU,eAAe,CAAC;AAAA,EACvC;AACA,SAAO;AACT;AAEA,SAAS,MAAM,OAAyC,UAAwB;AAC9E,MAAI,iBAAiB,KAAM,QAAO,MAAM,YAAY;AACpD,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,SAAS,IAAI,KAAK,KAAK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f,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,wBAAwB,EAAE,GAAG,CAAC;AACtC;",
6
6
  "names": []
7
7
  }
@@ -1,3 +1,5 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ const logger = createLogger("ai_assistant");
1
3
  const DEFAULT_RETENTION_DAYS = 90;
2
4
  const DELETE_BATCH_SIZE = 5e3;
3
5
  const RECONCILE_TRAILING_DAYS = 7;
@@ -83,23 +85,15 @@ async function runTokenUsagePrune(options) {
83
85
  try {
84
86
  eventsDeleted = await pruneOldEvents(connection, cutoff, batchSize);
85
87
  } catch (error) {
86
- console.error(
87
- "[ai-token-usage-prune] Failed to prune old events:",
88
- error instanceof Error ? error.message : error
89
- );
88
+ logger.error("Failed to prune old events", { err: error });
90
89
  }
91
90
  let dailyRowsReconciled = 0;
92
91
  try {
93
92
  dailyRowsReconciled = await reconcileSessionCounts(connection, now, RECONCILE_TRAILING_DAYS);
94
93
  } catch (error) {
95
- console.error(
96
- "[ai-token-usage-prune] Failed to reconcile session counts:",
97
- error instanceof Error ? error.message : error
98
- );
94
+ logger.error("Failed to reconcile session counts", { err: error });
99
95
  }
100
- console.info(
101
- `[ai-token-usage-prune] Done. eventsDeleted=${eventsDeleted}, dailyRowsReconciled=${dailyRowsReconciled}, retentionDays=${retentionDays}.`
102
- );
96
+ logger.info("Token-usage prune done", { eventsDeleted, dailyRowsReconciled, retentionDays });
103
97
  return { eventsDeleted, dailyRowsReconciled };
104
98
  }
105
99
  async function handle(_job, ctx) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/workers/ai-token-usage-prune.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\n\n/** Default retention window for the ai_token_usage_events table (days). */\nconst DEFAULT_RETENTION_DAYS = 90\n/** Batch size for delete operations to avoid long locks. */\nconst DELETE_BATCH_SIZE = 5_000\n/** Number of trailing days to reconcile session_count against events table. */\nconst RECONCILE_TRAILING_DAYS = 7\n\nexport const metadata: WorkerMeta = {\n queue: 'ai-token-usage-prune',\n id: 'ai_assistant:token-usage-prune',\n concurrency: 1,\n}\n\nexport interface TokenUsagePruneRunOptions {\n em: EntityManager\n /** Override for deterministic tests. Defaults to `new Date()`. */\n now?: Date\n /** Override retention days (default from env). */\n retentionDays?: number\n /** Override batch size (default 5000). */\n batchSize?: number\n}\n\nexport interface TokenUsagePruneSummary {\n eventsDeleted: number\n dailyRowsReconciled: number\n}\n\n/**\n * Reads `AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS` env var (default 90).\n */\nfunction resolveRetentionDays(): number {\n const raw = process.env.AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS\n if (!raw) return DEFAULT_RETENTION_DAYS\n const parsed = parseInt(raw.trim(), 10)\n return !isNaN(parsed) && parsed > 0 ? parsed : DEFAULT_RETENTION_DAYS\n}\n\n/**\n * Deletes events older than the retention cutoff in batches of `batchSize` to\n * avoid long table locks. Returns total rows deleted.\n */\nasync function pruneOldEvents(\n connection: ReturnType<EntityManager['getConnection']>,\n cutoff: Date,\n batchSize: number,\n): Promise<number> {\n let totalDeleted = 0\n for (;;) {\n const result = await connection.execute(\n `\n delete from ai_token_usage_events\n where id in (\n select id from ai_token_usage_events\n where created_at < ?\n limit ?\n )\n `,\n [cutoff, batchSize],\n 'run',\n ) as { affectedRows?: number; rowCount?: number } | undefined\n const deleted = result?.affectedRows ?? result?.rowCount ?? 0\n totalDeleted += deleted\n if (deleted < batchSize) break\n }\n return totalDeleted\n}\n\n/**\n * Reconciles `session_count` on daily rollup rows for the trailing N days by\n * recomputing it directly from the events table. This corrects any drift caused\n * by out-of-order event delivery, retention pruning, or failed incremental\n * writes.\n */\nasync function reconcileSessionCounts(\n connection: ReturnType<EntityManager['getConnection']>,\n now: Date,\n trailingDays: number,\n): Promise<number> {\n const trailingStart = new Date(now)\n trailingStart.setUTCDate(trailingStart.getUTCDate() - trailingDays)\n const from = trailingStart.toISOString().slice(0, 10)\n\n // Recompute session_count for each (tenant_id, day, agent_id, model_id, org)\n // combination by counting distinct session_ids from the events table.\n const rows = await connection.execute(\n `\n select\n d.id,\n count(distinct e.session_id)::bigint as computed_session_count\n from ai_token_usage_daily d\n left join ai_token_usage_events e\n on e.tenant_id = d.tenant_id\n and e.agent_id = d.agent_id\n and e.model_id = d.model_id\n and date_trunc('day', e.created_at)::date = d.day\n and (\n (d.organization_id is null and e.organization_id is null)\n or (d.organization_id is not null and e.organization_id = d.organization_id)\n )\n where d.day >= ?::date\n group by d.id\n `,\n [from],\n 'all',\n )\n\n if (!Array.isArray(rows) || rows.length === 0) return 0\n\n let reconciled = 0\n for (const row of rows as Array<Record<string, unknown>>) {\n const rowId = row.id as string\n const computed = typeof row.computed_session_count === 'string'\n ? parseInt(row.computed_session_count, 10)\n : (row.computed_session_count as number) ?? 0\n await connection.execute(\n `update ai_token_usage_daily set session_count = ?, updated_at = now() where id = ?`,\n [computed, rowId],\n 'run',\n )\n reconciled += 1\n }\n\n return reconciled\n}\n\n/**\n * Core logic for the token-usage prune worker. Exported for unit testing.\n *\n * 1. Resolves the retention cutoff from `AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS`.\n * 2. Deletes events older than the cutoff in batches of 5_000.\n * 3. Reconciles `session_count` on the daily rollup for trailing 7 days.\n *\n * Phase 6.4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport async function runTokenUsagePrune(\n options: TokenUsagePruneRunOptions,\n): Promise<TokenUsagePruneSummary> {\n const now = options.now ?? new Date()\n const retentionDays = options.retentionDays ?? resolveRetentionDays()\n const batchSize = options.batchSize ?? DELETE_BATCH_SIZE\n\n const cutoff = new Date(now)\n cutoff.setUTCDate(cutoff.getUTCDate() - retentionDays)\n\n const connection = options.em.getConnection()\n\n let eventsDeleted = 0\n try {\n eventsDeleted = await pruneOldEvents(connection, cutoff, batchSize)\n } catch (error) {\n console.error(\n '[ai-token-usage-prune] Failed to prune old events:',\n error instanceof Error ? error.message : error,\n )\n }\n\n let dailyRowsReconciled = 0\n try {\n dailyRowsReconciled = await reconcileSessionCounts(connection, now, RECONCILE_TRAILING_DAYS)\n } catch (error) {\n console.error(\n '[ai-token-usage-prune] Failed to reconcile session counts:',\n error instanceof Error ? error.message : error,\n )\n }\n\n console.info(\n `[ai-token-usage-prune] Done. eventsDeleted=${eventsDeleted}, dailyRowsReconciled=${dailyRowsReconciled}, retentionDays=${retentionDays}.`,\n )\n\n return { eventsDeleted, dailyRowsReconciled }\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(\n _job: QueuedJob,\n ctx: HandlerContext,\n): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n await runTokenUsagePrune({ em })\n}\n"],
5
- "mappings": "AAIA,MAAM,yBAAyB;AAE/B,MAAM,oBAAoB;AAE1B,MAAM,0BAA0B;AAEzB,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAoBA,SAAS,uBAA+B;AACtC,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,CAAC,IAAK,QAAO;AACjB,QAAM,SAAS,SAAS,IAAI,KAAK,GAAG,EAAE;AACtC,SAAO,CAAC,MAAM,MAAM,KAAK,SAAS,IAAI,SAAS;AACjD;AAMA,eAAe,eACb,YACA,QACA,WACiB;AACjB,MAAI,eAAe;AACnB,aAAS;AACP,UAAM,SAAS,MAAM,WAAW;AAAA,MAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAQA,CAAC,QAAQ,SAAS;AAAA,MAClB;AAAA,IACF;AACA,UAAM,UAAU,QAAQ,gBAAgB,QAAQ,YAAY;AAC5D,oBAAgB;AAChB,QAAI,UAAU,UAAW;AAAA,EAC3B;AACA,SAAO;AACT;AAQA,eAAe,uBACb,YACA,KACA,cACi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AAO;AACd,YAAQ;AAAA,MACN;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU;AAAA,IAC3C;AAAA,EACF;AAEA,UAAQ;AAAA,IACN,8CAA8C,aAAa,yBAAyB,mBAAmB,mBAAmB,aAAa;AAAA,EACzI;AAEA,SAAO,EAAE,eAAe,oBAAoB;AAC9C;AAMA,eAAO,OACL,MACA,KACe;AACf,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,mBAAmB,EAAE,GAAG,CAAC;AACjC;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { JobContext, QueuedJob, WorkerMeta } from '@open-mercato/queue'\n\nconst logger = createLogger('ai_assistant')\n\n/** Default retention window for the ai_token_usage_events table (days). */\nconst DEFAULT_RETENTION_DAYS = 90\n/** Batch size for delete operations to avoid long locks. */\nconst DELETE_BATCH_SIZE = 5_000\n/** Number of trailing days to reconcile session_count against events table. */\nconst RECONCILE_TRAILING_DAYS = 7\n\nexport const metadata: WorkerMeta = {\n queue: 'ai-token-usage-prune',\n id: 'ai_assistant:token-usage-prune',\n concurrency: 1,\n}\n\nexport interface TokenUsagePruneRunOptions {\n em: EntityManager\n /** Override for deterministic tests. Defaults to `new Date()`. */\n now?: Date\n /** Override retention days (default from env). */\n retentionDays?: number\n /** Override batch size (default 5000). */\n batchSize?: number\n}\n\nexport interface TokenUsagePruneSummary {\n eventsDeleted: number\n dailyRowsReconciled: number\n}\n\n/**\n * Reads `AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS` env var (default 90).\n */\nfunction resolveRetentionDays(): number {\n const raw = process.env.AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS\n if (!raw) return DEFAULT_RETENTION_DAYS\n const parsed = parseInt(raw.trim(), 10)\n return !isNaN(parsed) && parsed > 0 ? parsed : DEFAULT_RETENTION_DAYS\n}\n\n/**\n * Deletes events older than the retention cutoff in batches of `batchSize` to\n * avoid long table locks. Returns total rows deleted.\n */\nasync function pruneOldEvents(\n connection: ReturnType<EntityManager['getConnection']>,\n cutoff: Date,\n batchSize: number,\n): Promise<number> {\n let totalDeleted = 0\n for (;;) {\n const result = await connection.execute(\n `\n delete from ai_token_usage_events\n where id in (\n select id from ai_token_usage_events\n where created_at < ?\n limit ?\n )\n `,\n [cutoff, batchSize],\n 'run',\n ) as { affectedRows?: number; rowCount?: number } | undefined\n const deleted = result?.affectedRows ?? result?.rowCount ?? 0\n totalDeleted += deleted\n if (deleted < batchSize) break\n }\n return totalDeleted\n}\n\n/**\n * Reconciles `session_count` on daily rollup rows for the trailing N days by\n * recomputing it directly from the events table. This corrects any drift caused\n * by out-of-order event delivery, retention pruning, or failed incremental\n * writes.\n */\nasync function reconcileSessionCounts(\n connection: ReturnType<EntityManager['getConnection']>,\n now: Date,\n trailingDays: number,\n): Promise<number> {\n const trailingStart = new Date(now)\n trailingStart.setUTCDate(trailingStart.getUTCDate() - trailingDays)\n const from = trailingStart.toISOString().slice(0, 10)\n\n // Recompute session_count for each (tenant_id, day, agent_id, model_id, org)\n // combination by counting distinct session_ids from the events table.\n const rows = await connection.execute(\n `\n select\n d.id,\n count(distinct e.session_id)::bigint as computed_session_count\n from ai_token_usage_daily d\n left join ai_token_usage_events e\n on e.tenant_id = d.tenant_id\n and e.agent_id = d.agent_id\n and e.model_id = d.model_id\n and date_trunc('day', e.created_at)::date = d.day\n and (\n (d.organization_id is null and e.organization_id is null)\n or (d.organization_id is not null and e.organization_id = d.organization_id)\n )\n where d.day >= ?::date\n group by d.id\n `,\n [from],\n 'all',\n )\n\n if (!Array.isArray(rows) || rows.length === 0) return 0\n\n let reconciled = 0\n for (const row of rows as Array<Record<string, unknown>>) {\n const rowId = row.id as string\n const computed = typeof row.computed_session_count === 'string'\n ? parseInt(row.computed_session_count, 10)\n : (row.computed_session_count as number) ?? 0\n await connection.execute(\n `update ai_token_usage_daily set session_count = ?, updated_at = now() where id = ?`,\n [computed, rowId],\n 'run',\n )\n reconciled += 1\n }\n\n return reconciled\n}\n\n/**\n * Core logic for the token-usage prune worker. Exported for unit testing.\n *\n * 1. Resolves the retention cutoff from `AI_TOKEN_USAGE_EVENTS_RETENTION_DAYS`.\n * 2. Deletes events older than the cutoff in batches of 5_000.\n * 3. Reconciles `session_count` on the daily rollup for trailing 7 days.\n *\n * Phase 6.4 of spec `2026-04-28-ai-agents-agentic-loop-controls`.\n */\nexport async function runTokenUsagePrune(\n options: TokenUsagePruneRunOptions,\n): Promise<TokenUsagePruneSummary> {\n const now = options.now ?? new Date()\n const retentionDays = options.retentionDays ?? resolveRetentionDays()\n const batchSize = options.batchSize ?? DELETE_BATCH_SIZE\n\n const cutoff = new Date(now)\n cutoff.setUTCDate(cutoff.getUTCDate() - retentionDays)\n\n const connection = options.em.getConnection()\n\n let eventsDeleted = 0\n try {\n eventsDeleted = await pruneOldEvents(connection, cutoff, batchSize)\n } catch (error) {\n logger.error('Failed to prune old events', { err: error })\n }\n\n let dailyRowsReconciled = 0\n try {\n dailyRowsReconciled = await reconcileSessionCounts(connection, now, RECONCILE_TRAILING_DAYS)\n } catch (error) {\n logger.error('Failed to reconcile session counts', { err: error })\n }\n\n logger.info('Token-usage prune done', { eventsDeleted, dailyRowsReconciled, retentionDays })\n\n return { eventsDeleted, dailyRowsReconciled }\n}\n\ntype HandlerContext = JobContext & {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(\n _job: QueuedJob,\n ctx: HandlerContext,\n): Promise<void> {\n const em = ctx.resolve<EntityManager>('em')\n await runTokenUsagePrune({ em })\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAI7B,MAAM,SAAS,aAAa,cAAc;AAG1C,MAAM,yBAAyB;AAE/B,MAAM,oBAAoB;AAE1B,MAAM,0BAA0B;AAEzB,MAAM,WAAuB;AAAA,EAClC,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,aAAa;AACf;AAoBA,SAAS,uBAA+B;AACtC,QAAM,MAAM,QAA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AAI,KAAK;AACpC,QAAM,gBAAgB,QAAQ,iBAAiB,qBAAqB;AACpE,QAAM,YAAY,QAAQ,aAAa;AAEvC,QAAM,SAAS,IAAI,KAAK,GAAG;AAC3B,SAAO,WAAW,OAAO,WAAW,IAAI,aAAa;AAErD,QAAM,aAAa,QAAQ,GAAG,cAAc;AAE5C,MAAI,gBAAgB;AACpB,MAAI;AACF,oBAAgB,MAAM,eAAe,YAAY,QAAQ,SAAS;AAAA,EACpE,SAAS,OAAO;AACd,WAAO,MAAM,8BAA8B,EAAE,KAAK,MAAM,CAAC;AAAA,EAC3D;AAEA,MAAI,sBAAsB;AAC1B,MAAI;AACF,0BAAsB,MAAM,uBAAuB,YAAY,KAAK,uBAAuB;AAAA,EAC7F,SAAS,OAAO;AACd,WAAO,MAAM,sCAAsC,EAAE,KAAK,MAAM,CAAC;AAAA,EACnE;AAEA,SAAO,KAAK,0BAA0B,EAAE,eAAe,qBAAqB,cAAc,CAAC;AAE3F,SAAO,EAAE,eAAe,oBAAoB;AAC9C;AAMA,eAAO,OACL,MACA,KACe;AACf,QAAM,KAAK,IAAI,QAAuB,IAAI;AAC1C,QAAM,mBAAmB,EAAE,GAAG,CAAC;AACjC;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/ai-assistant",
3
- "version": "0.6.6-develop.6465.1.019f0fb26f",
3
+ "version": "0.6.6-develop.6471.1.9ab5bdd79a",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -99,16 +99,16 @@
99
99
  "zod-to-json-schema": "^3.25.2"
100
100
  },
101
101
  "peerDependencies": {
102
- "@open-mercato/shared": "0.6.6-develop.6465.1.019f0fb26f",
103
- "@open-mercato/ui": "0.6.6-develop.6465.1.019f0fb26f",
102
+ "@open-mercato/shared": "0.6.6-develop.6471.1.9ab5bdd79a",
103
+ "@open-mercato/ui": "0.6.6-develop.6471.1.9ab5bdd79a",
104
104
  "react": "^19.0.0",
105
105
  "react-dom": "^19.0.0",
106
106
  "zod": ">=3.23.0"
107
107
  },
108
108
  "devDependencies": {
109
- "@open-mercato/cli": "0.6.6-develop.6465.1.019f0fb26f",
110
- "@open-mercato/shared": "0.6.6-develop.6465.1.019f0fb26f",
111
- "@open-mercato/ui": "0.6.6-develop.6465.1.019f0fb26f",
109
+ "@open-mercato/cli": "0.6.6-develop.6471.1.9ab5bdd79a",
110
+ "@open-mercato/shared": "0.6.6-develop.6471.1.9ab5bdd79a",
111
+ "@open-mercato/ui": "0.6.6-develop.6471.1.9ab5bdd79a",
112
112
  "@types/react": "^19.2.17",
113
113
  "@types/react-dom": "^19.2.3",
114
114
  "react": "19.2.7",