@open-mercato/ai-assistant 0.10.1-develop.8116.1.25333cebaa → 0.10.1-develop.8123.1.acf6ca6db8

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.
@@ -1,2 +1,2 @@
1
- [build:ai-assistant] found 250 entry points
1
+ [build:ai-assistant] found 251 entry points
2
2
  [build:ai-assistant] built successfully
@@ -0,0 +1,53 @@
1
+ import { test, expect } from "@playwright/test";
2
+ import { randomUUID } from "node:crypto";
3
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
4
+ import { createCompanyFixture, deleteEntityIfExists } from "@open-mercato/core/helpers/integration/crmFixtures";
5
+ import { getTokenScope, readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
6
+ import { seedPendingActionInDb, deletePendingActionInDb } from "./helpers/aiAssistantFixtures.js";
7
+ const actionsPath = "/api/ai_assistant/ai/actions";
8
+ test("TC-AI-ACTIONS-CLAIM-011: concurrent confirmation creates exactly one comment", async ({ request }) => {
9
+ const token = await getAuthToken(request, "admin");
10
+ const { tenantId, organizationId, userId } = getTokenScope(token);
11
+ const marker = `IT exclusive approval ${randomUUID()}`;
12
+ const companyId = await createCompanyFixture(request, token, marker);
13
+ let pendingActionId = null;
14
+ try {
15
+ const action = await seedPendingActionInDb({
16
+ tenantId,
17
+ organizationId,
18
+ createdByUserId: userId,
19
+ agentId: "customers.account_assistant",
20
+ toolName: "customers.manage_record_comment",
21
+ normalizedInput: { operation: "create", companyId, body: marker }
22
+ });
23
+ pendingActionId = action.id;
24
+ const confirmations = await Promise.all(Array.from({ length: 20 }, () => apiRequest(
25
+ request,
26
+ "POST",
27
+ `${actionsPath}/${action.id}/confirm`,
28
+ { token, data: {} }
29
+ )));
30
+ const bodies = await Promise.all(confirmations.map((response) => readJsonSafe(response)));
31
+ for (const [index, response] of confirmations.entries()) {
32
+ expect([200, 409], JSON.stringify(bodies[index])).toContain(response.status());
33
+ if (response.status() === 409) expect(bodies[index]?.code).toBe("invalid_status");
34
+ }
35
+ expect(bodies.some((body) => body?.ok === true)).toBe(true);
36
+ const replay = await apiRequest(request, "POST", `${actionsPath}/${action.id}/confirm`, { token, data: {} });
37
+ expect(replay.status()).toBe(200);
38
+ expect(await readJsonSafe(replay)).toMatchObject({ ok: true, pendingAction: { status: "confirmed" } });
39
+ const comments = await apiRequest(request, "GET", `/api/customers/comments?entityId=${companyId}`, { token });
40
+ expect(comments.status()).toBe(200);
41
+ const list = await readJsonSafe(comments);
42
+ expect(list?.items.filter((comment) => comment.body === marker)).toHaveLength(1);
43
+ } finally {
44
+ const response = await apiRequest(request, "GET", `/api/customers/comments?entityId=${companyId}`, { token });
45
+ const comments = await readJsonSafe(response);
46
+ for (const comment of comments?.items ?? []) {
47
+ await deleteEntityIfExists(request, token, "/api/customers/comments", comment.id);
48
+ }
49
+ if (pendingActionId) await deletePendingActionInDb(pendingActionId);
50
+ await deleteEntityIfExists(request, token, "/api/customers/companies", companyId);
51
+ }
52
+ });
53
+ //# sourceMappingURL=TC-AI-ACTIONS-CLAIM-011-concurrent-confirmation.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/ai_assistant/__integration__/TC-AI-ACTIONS-CLAIM-011-concurrent-confirmation.spec.ts"],
4
+ "sourcesContent": ["import { test, expect } from '@playwright/test'\nimport { randomUUID } from 'node:crypto'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { createCompanyFixture, deleteEntityIfExists } from '@open-mercato/core/helpers/integration/crmFixtures'\nimport { getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { seedPendingActionInDb, deletePendingActionInDb } from './helpers/aiAssistantFixtures'\n\ntype CommentList = { items: Array<{ id: string; body: string }> }\ntype Confirmation = { ok?: boolean; pendingAction?: { status: string }; code?: string }\n\nconst actionsPath = '/api/ai_assistant/ai/actions'\n\ntest('TC-AI-ACTIONS-CLAIM-011: concurrent confirmation creates exactly one comment', async ({ request }) => {\n const token = await getAuthToken(request, 'admin')\n const { tenantId, organizationId, userId } = getTokenScope(token)\n const marker = `IT exclusive approval ${randomUUID()}`\n const companyId = await createCompanyFixture(request, token, marker)\n let pendingActionId: string | null = null\n try {\n const action = await seedPendingActionInDb({\n tenantId,\n organizationId,\n createdByUserId: userId,\n agentId: 'customers.account_assistant',\n toolName: 'customers.manage_record_comment',\n normalizedInput: { operation: 'create', companyId, body: marker },\n })\n pendingActionId = action.id\n const confirmations = await Promise.all(Array.from({ length: 20 }, () => apiRequest(\n request, 'POST', `${actionsPath}/${action.id}/confirm`, { token, data: {} },\n )))\n const bodies = await Promise.all(confirmations.map((response) => readJsonSafe<Confirmation>(response)))\n for (const [index, response] of confirmations.entries()) {\n expect([200, 409], JSON.stringify(bodies[index])).toContain(response.status())\n if (response.status() === 409) expect(bodies[index]?.code).toBe('invalid_status')\n }\n expect(bodies.some((body) => body?.ok === true)).toBe(true)\n const replay = await apiRequest(request, 'POST', `${actionsPath}/${action.id}/confirm`, { token, data: {} })\n expect(replay.status()).toBe(200)\n expect(await readJsonSafe<Confirmation>(replay)).toMatchObject({ ok: true, pendingAction: { status: 'confirmed' } })\n const comments = await apiRequest(request, 'GET', `/api/customers/comments?entityId=${companyId}`, { token })\n expect(comments.status()).toBe(200)\n const list = await readJsonSafe<CommentList>(comments)\n expect(list?.items.filter((comment) => comment.body === marker)).toHaveLength(1)\n } finally {\n const response = await apiRequest(request, 'GET', `/api/customers/comments?entityId=${companyId}`, { token })\n const comments = await readJsonSafe<CommentList>(response)\n for (const comment of comments?.items ?? []) {\n await deleteEntityIfExists(request, token, '/api/customers/comments', comment.id)\n }\n if (pendingActionId) await deletePendingActionInDb(pendingActionId)\n await deleteEntityIfExists(request, token, '/api/customers/companies', companyId)\n }\n})\n"],
5
+ "mappings": "AAAA,SAAS,MAAM,cAAc;AAC7B,SAAS,kBAAkB;AAC3B,SAAS,YAAY,oBAAoB;AACzC,S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M,WAAW,SAAS,QAAQ,GAAG,WAAW,IAAI,OAAO,EAAE,YAAY,EAAE,OAAO,MAAM,CAAC,EAAE,CAAC;AAC3G,WAAO,OAAO,OAAO,CAAC,EAAE,KAAK,GAAG;AAChC,WAAO,MAAM,aAA2B,MAAM,CAAC,EAAE,cAAc,EAAE,IAAI,MAAM,eAAe,EAAE,QAAQ,YAAY,EAAE,CAAC;AACnH,UAAM,WAAW,MAAM,WAAW,SAAS,OAAO,oCAAoC,SAAS,IAAI,EAAE,MAAM,CAAC;AAC5G,WAAO,SAAS,OAAO,CAAC,EAAE,KAAK,GAAG;AAClC,UAAM,OAAO,MAAM,aAA0B,QAAQ;AACrD,WAAO,MAAM,MAAM,OAAO,CAAC,YAAY,QAAQ,SAAS,MAAM,CAAC,EAAE,aAAa,CAAC;AAAA,EACjF,UAAE;AACA,UAAM,WAAW,MAAM,WAAW,SAAS,OAAO,oCAAoC,SAAS,IAAI,EAAE,MAAM,CAAC;AAC5G,UAAM,WAAW,MAAM,aAA0B,QAAQ;AACzD,eAAW,WAAW,UAAU,SAAS,CAAC,GAAG;AAC3C,YAAM,qBAAqB,SAAS,OAAO,2BAA2B,QAAQ,EAAE;AAAA,IAClF;AACA,QAAI,gBAAiB,OAAM,wBAAwB,eAAe;AAClE,UAAM,qBAAqB,SAAS,OAAO,4BAA4B,SAAS;AAAA,EAClF;AACF,CAAC;",
6
+ "names": []
7
+ }
@@ -1,3 +1,4 @@
1
+ import { LockMode } from "@mikro-orm/core";
1
2
  import {
2
3
  findOneWithDecryption,
3
4
  findWithDecryption
@@ -107,7 +108,7 @@ class AiPendingActionRepository {
107
108
  organizationId: ctx.organizationId ?? null,
108
109
  ...owner
109
110
  },
110
- {},
111
+ { refresh: true },
111
112
  {
112
113
  tenantId: ctx.tenantId ?? null,
113
114
  organizationId: ctx.organizationId ?? null
@@ -159,7 +160,7 @@ class AiPendingActionRepository {
159
160
  organizationId: ctx.organizationId ?? null,
160
161
  ...owner
161
162
  },
162
- {},
163
+ { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },
163
164
  {
164
165
  tenantId: ctx.tenantId ?? null,
165
166
  organizationId: ctx.organizationId ?? null
@@ -168,6 +169,9 @@ class AiPendingActionRepository {
168
169
  if (!existing) {
169
170
  throw new Error(`AiPendingAction not found: ${id}`);
170
171
  }
172
+ if (extra?.expectedStatus && existing.status !== extra.expectedStatus) {
173
+ throw new AiPendingActionStateError(existing.status, nextStatus);
174
+ }
171
175
  if (existing.status === nextStatus) {
172
176
  return existing;
173
177
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/ai_assistant/data/repositories/AiPendingActionRepository.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { AiPendingAction } from '../entities'\nimport {\n AI_PENDING_ACTION_ALLOWED_TRANSITIONS,\n AiPendingActionStateError,\n resolveAiPendingActionTtlSeconds,\n type AiPendingActionExecutionResult,\n type AiPendingActionFailedRecord,\n type AiPendingActionFieldDiff,\n type AiPendingActionQueueMode,\n type AiPendingActionRecordDiff,\n type AiPendingActionStatus,\n} from '../../lib/pending-action-types'\n\nexport interface AiPendingActionContext {\n tenantId: string\n organizationId?: string | null\n userId?: string | null\n}\n\nexport interface AiPendingActionCreateInput {\n agentId: string\n toolName: string\n idempotencyKey: string\n createdByUserId: string\n normalizedInput: Record<string, unknown>\n conversationId?: string | null\n targetEntityType?: string | null\n targetRecordId?: string | null\n fieldDiff?: AiPendingActionFieldDiff[]\n records?: AiPendingActionRecordDiff[] | null\n sideEffectsSummary?: string | null\n recordVersion?: string | null\n attachmentIds?: string[]\n queueMode?: AiPendingActionQueueMode\n /** Optional explicit TTL in seconds; overrides the env/default TTL. */\n ttlSeconds?: number\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiPendingActionCreateResult {\n row: AiPendingAction\n /**\n * True when `row` is an existing row returned as-is (a still-`pending`\n * row, or a `confirmed`/`executing` row whose mutation already ran) \u2014\n * i.e. no new row was inserted.\n */\n reused: boolean\n}\n\nexport interface AiPendingActionSetStatusExtra {\n resolvedByUserId?: string | null\n executionResult?: AiPendingActionExecutionResult | null\n failedRecords?: AiPendingActionFailedRecord[] | null\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\n/**\n * Persistent store for the Phase 3 WS-C mutation approval gate (Step 5.5).\n *\n * Responsibilities:\n * - Create new pending rows with a TTL-derived `expiresAt`, honoring\n * idempotency within the window (same `idempotencyKey` returns the same\n * row as long as it is still `pending`; any terminal state mints a new row).\n * - Tenant-scoped lookups for the confirm/cancel/reconnect routes and the\n * in-app UI's \"open actions\" list. `getById`, `listPendingForAgent` and\n * `setStatus` are also owner-scoped: they match the row's\n * `createdByUserId` against `ctx.userId`, so only the proposing user can\n * read or resolve it. System callers (the expiry sweeper) pass\n * `userId: null` to skip the owner filter; a missing or non-UUID\n * `userId` (for example an API-key subject) matches no row.\n * - State-machine enforcement: `setStatus` rejects illegal transitions via\n * {@link AiPendingActionStateError}. The runtime callers translate this\n * to a 409 Conflict response.\n * - `listExpired` for the cleanup worker (Step 5.12).\n *\n * Every read goes through `findOneWithDecryption` / `findWithDecryption`\n * because `normalized_input`, `field_diff` and `records` are declared in the\n * module's `encryption.ts` and are encrypted at rest when tenant data\n * encryption is enabled.\n */\nexport class AiPendingActionRepository {\n constructor(private readonly em: EntityManager) {}\n\n async create(\n input: AiPendingActionCreateInput,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingActionCreateResult> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.create requires tenantId')\n }\n if (!input?.agentId) {\n throw new Error('AiPendingActionRepository.create requires agentId')\n }\n if (!input?.toolName) {\n throw new Error('AiPendingActionRepository.create requires toolName')\n }\n if (!input?.idempotencyKey) {\n throw new Error(\n 'AiPendingActionRepository.create requires idempotencyKey',\n )\n }\n if (!input?.createdByUserId) {\n throw new Error(\n 'AiPendingActionRepository.create requires createdByUserId',\n )\n }\n\n const now = input.now ?? new Date()\n const ttlSeconds = Math.max(\n 1,\n Math.floor(\n typeof input.ttlSeconds === 'number' && Number.isFinite(input.ttlSeconds)\n ? input.ttlSeconds\n : resolveAiPendingActionTtlSeconds(),\n ),\n )\n const expiresAt = new Date(now.getTime() + ttlSeconds * 1000)\n\n return this.em.transactional(async (tx) => {\n const existing = await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n idempotencyKey: input.idempotencyKey,\n } as any,\n { orderBy: { createdAt: 'desc' } as any },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (existing && existing.status === 'pending') {\n return { row: existing, reused: true }\n }\n // A `confirmed`/`executing` row represents a mutation that already\n // ran (or is running). Inserting a fresh row with the same key would\n // collide with the unique `(tenantId, organizationId,\n // idempotencyKey)` index \u2014 this happens whenever the model repeats\n // the same tool call with the same arguments after it already\n // succeeded. Return the existing row instead of inserting; the\n // caller (`prepareMutation`) uses `reused` to tell the model the\n // operation already ran rather than re-queuing it.\n //\n // This only holds within the row's own dedupe/TTL window\n // (`now < expiresAt`, per the spec's \"within the TTL\" dedupe\n // promise). Outside it, treat the row as stale: a legitimate repeat\n // of the same arguments later on would otherwise be refused forever,\n // and a process that died mid-execution would leave every retry\n // stuck reading a dead `executing` row.\n if (\n existing &&\n (existing.status === 'confirmed' || existing.status === 'executing') &&\n now.getTime() < existing.expiresAt.getTime()\n ) {\n return { row: existing, reused: true }\n }\n // A terminal (`failed`/`cancelled`/`expired`) row, or a stale\n // `confirmed`/`executing` row past its dedupe window, would also\n // collide on the same unique index when we insert a fresh one with\n // the same key \u2014 which happens whenever the operator clicks \"Fix\n // with AI\" and the model retries the SAME tool with the SAME args,\n // or simply repeats the same arguments later. Re-key the stale row\n // (instead of deleting it) so a retry can always proceed: the stale\n // row's own card keeps resolving to its terminal/prior state via a\n // GET by id, rather than 404ing.\n if (\n existing &&\n (existing.status === 'failed' ||\n existing.status === 'cancelled' ||\n existing.status === 'expired' ||\n existing.status === 'confirmed' ||\n existing.status === 'executing')\n ) {\n existing.idempotencyKey = `${existing.idempotencyKey}:superseded:${existing.id}`\n await tx.persist(existing).flush()\n }\n const row = tx.create(AiPendingAction, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId: input.agentId,\n toolName: input.toolName,\n conversationId: input.conversationId ?? null,\n targetEntityType: input.targetEntityType ?? null,\n targetRecordId: input.targetRecordId ?? null,\n normalizedInput: input.normalizedInput ?? {},\n fieldDiff: Array.isArray(input.fieldDiff) ? input.fieldDiff : [],\n records: normalizeRecords(input.records),\n failedRecords: null,\n sideEffectsSummary: input.sideEffectsSummary ?? null,\n recordVersion: input.recordVersion ?? null,\n attachmentIds: Array.isArray(input.attachmentIds)\n ? input.attachmentIds\n : [],\n idempotencyKey: input.idempotencyKey,\n createdByUserId: input.createdByUserId,\n status: 'pending' as AiPendingActionStatus,\n queueMode: (input.queueMode ?? 'inline') as AiPendingActionQueueMode,\n executionResult: null,\n createdAt: now,\n expiresAt,\n resolvedAt: null,\n resolvedByUserId: null,\n } as unknown as AiPendingAction)\n await tx.persist(row).flush()\n return { row, reused: false }\n })\n }\n\n async getById(\n id: string,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingAction | null> {\n if (!id || !ctx?.tenantId) return null\n const owner = resolveOwnerScope(ctx)\n if (!owner) return null\n const row = await findOneWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n ...owner,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return row ?? null\n }\n\n async listPendingForAgent(\n agentId: string,\n ctx: AiPendingActionContext,\n limit: number = 50,\n ): Promise<AiPendingAction[]> {\n if (!agentId || !ctx?.tenantId) return []\n const owner = resolveOwnerScope(ctx)\n if (!owner) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 200))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId,\n status: 'pending',\n ...owner,\n } as any,\n {\n orderBy: { createdAt: 'desc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n\n async setStatus(\n id: string,\n nextStatus: AiPendingActionStatus,\n ctx: AiPendingActionContext,\n extra?: AiPendingActionSetStatusExtra,\n ): Promise<AiPendingAction> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.setStatus requires tenantId')\n }\n if (!id) {\n throw new Error('AiPendingActionRepository.setStatus requires id')\n }\n const owner = resolveOwnerScope(ctx)\n return this.em.transactional(async (tx) => {\n const existing = owner\n ? await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n ...owner,\n } as any,\n {},\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n : null\n if (!existing) {\n throw new Error(`AiPendingAction not found: ${id}`)\n }\n if (existing.status === nextStatus) {\n return existing\n }\n const allowed = AI_PENDING_ACTION_ALLOWED_TRANSITIONS[existing.status] ?? []\n if (!allowed.includes(nextStatus)) {\n throw new AiPendingActionStateError(existing.status, nextStatus)\n }\n const now = extra?.now ?? new Date()\n existing.status = nextStatus\n if (\n nextStatus === 'confirmed' ||\n nextStatus === 'cancelled' ||\n nextStatus === 'expired' ||\n nextStatus === 'failed'\n ) {\n existing.resolvedAt = existing.resolvedAt ?? now\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'resolvedByUserId')) {\n existing.resolvedByUserId = extra.resolvedByUserId ?? null\n } else if (nextStatus === 'expired') {\n existing.resolvedByUserId = null\n }\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'executionResult')) {\n existing.executionResult = extra.executionResult ?? null\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'failedRecords')) {\n existing.failedRecords = normalizeFailedRecords(extra.failedRecords)\n }\n await tx.persist(existing).flush()\n return existing\n })\n }\n\n async listExpired(\n ctx: AiPendingActionContext,\n now: Date,\n limit: number = 100,\n ): Promise<AiPendingAction[]> {\n if (!ctx?.tenantId) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 500))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n status: 'pending',\n expiresAt: { $lt: now } as any,\n } as any,\n {\n orderBy: { expiresAt: 'asc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n}\n\nconst OWNER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction resolveOwnerScope(ctx: AiPendingActionContext): { createdByUserId?: string } | null {\n if (ctx.userId === null) return {}\n if (typeof ctx.userId === 'string' && OWNER_ID_PATTERN.test(ctx.userId)) {\n return { createdByUserId: ctx.userId }\n }\n return null\n}\n\nfunction normalizeRecords(\n records: AiPendingActionRecordDiff[] | null | undefined,\n): AiPendingActionRecordDiff[] | null {\n if (!Array.isArray(records) || records.length === 0) return null\n return records\n}\n\nfunction normalizeFailedRecords(\n failed: AiPendingActionFailedRecord[] | null | undefined,\n): AiPendingActionFailedRecord[] | null {\n if (!Array.isArray(failed) || failed.length === 0) return null\n return failed\n}\n\nexport default AiPendingActionRepository\n"],
5
- "mappings": "AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC;AAAA,EAC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AAM,GAAG,QAAQ,QAAQ,EAAE,MAAM;AACjC,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,YACJ,KACA,KACA,QAAgB,KACY;AAC5B,QAAI,CAAC,KAAK,SAAU,QAAO,CAAC;AAC5B,UAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,MAAM,KAAK,GAAG,GAAG,CAAC;AAC3D,UAAM,OAAO,MAAM;AAAA,MACjB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,UAAU,IAAI;AAAA,QACd,gBAAgB,IAAI,kBAAkB;AAAA,QACtC,QAAQ;AAAA,QACR,WAAW,EAAE,KAAK,IAAI;AAAA,MACxB;AAAA,MACA;AAAA,QACE,SAAS,EAAE,WAAW,MAAM;AAAA,QAC5B,OAAO;AAAA,MACT;AAAA,MACA;AAAA,QACE,UAAU,IAAI,YAAY;AAAA,QAC1B,gBAAgB,IAAI,kBAAkB;AAAA,MACxC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAEA,MAAM,mBAAmB;AAEzB,SAAS,kBAAkB,KAAkE;AAC3F,MAAI,IAAI,WAAW,KAAM,QAAO,CAAC;AACjC,MAAI,OAAO,IAAI,WAAW,YAAY,iBAAiB,KAAK,IAAI,MAAM,GAAG;AACvE,WAAO,EAAE,iBAAiB,IAAI,OAAO;AAAA,EACvC;AACA,SAAO;AACT;AAEA,SAAS,iBACP,SACoC;AACpC,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,EAAG,QAAO;AAC5D,SAAO;AACT;AAEA,SAAS,uBACP,QACsC;AACtC,MAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,OAAO,WAAW,EAAG,QAAO;AAC1D,SAAO;AACT;AAEA,IAAO,oCAAQ;",
4
+ "sourcesContent": ["import { LockMode } from '@mikro-orm/core'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n findOneWithDecryption,\n findWithDecryption,\n} from '@open-mercato/shared/lib/encryption/find'\nimport { AiPendingAction } from '../entities'\nimport {\n AI_PENDING_ACTION_ALLOWED_TRANSITIONS,\n AiPendingActionStateError,\n resolveAiPendingActionTtlSeconds,\n type AiPendingActionExecutionResult,\n type AiPendingActionFailedRecord,\n type AiPendingActionFieldDiff,\n type AiPendingActionQueueMode,\n type AiPendingActionRecordDiff,\n type AiPendingActionStatus,\n} from '../../lib/pending-action-types'\n\nexport interface AiPendingActionContext {\n tenantId: string\n organizationId?: string | null\n userId?: string | null\n}\n\nexport interface AiPendingActionCreateInput {\n agentId: string\n toolName: string\n idempotencyKey: string\n createdByUserId: string\n normalizedInput: Record<string, unknown>\n conversationId?: string | null\n targetEntityType?: string | null\n targetRecordId?: string | null\n fieldDiff?: AiPendingActionFieldDiff[]\n records?: AiPendingActionRecordDiff[] | null\n sideEffectsSummary?: string | null\n recordVersion?: string | null\n attachmentIds?: string[]\n queueMode?: AiPendingActionQueueMode\n /** Optional explicit TTL in seconds; overrides the env/default TTL. */\n ttlSeconds?: number\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\nexport interface AiPendingActionCreateResult {\n row: AiPendingAction\n /**\n * True when `row` is an existing row returned as-is (a still-`pending`\n * row, or a `confirmed`/`executing` row whose mutation already ran) \u2014\n * i.e. no new row was inserted.\n */\n reused: boolean\n}\n\nexport interface AiPendingActionSetStatusExtra {\n expectedStatus?: AiPendingActionStatus\n resolvedByUserId?: string | null\n executionResult?: AiPendingActionExecutionResult | null\n failedRecords?: AiPendingActionFailedRecord[] | null\n /** Optional explicit `now` for deterministic tests. */\n now?: Date\n}\n\n/**\n * Persistent store for the Phase 3 WS-C mutation approval gate (Step 5.5).\n *\n * Responsibilities:\n * - Create new pending rows with a TTL-derived `expiresAt`, honoring\n * idempotency within the window (same `idempotencyKey` returns the same\n * row as long as it is still `pending`; any terminal state mints a new row).\n * - Tenant-scoped lookups for the confirm/cancel/reconnect routes and the\n * in-app UI's \"open actions\" list. `getById`, `listPendingForAgent` and\n * `setStatus` are also owner-scoped: they match the row's\n * `createdByUserId` against `ctx.userId`, so only the proposing user can\n * read or resolve it. System callers (the expiry sweeper) pass\n * `userId: null` to skip the owner filter; a missing or non-UUID\n * `userId` (for example an API-key subject) matches no row.\n * - State-machine enforcement: `setStatus` rejects illegal transitions via\n * {@link AiPendingActionStateError}. The runtime callers translate this\n * to a 409 Conflict response.\n * - `listExpired` for the cleanup worker (Step 5.12).\n *\n * Every read goes through `findOneWithDecryption` / `findWithDecryption`\n * because `normalized_input`, `field_diff` and `records` are declared in the\n * module's `encryption.ts` and are encrypted at rest when tenant data\n * encryption is enabled.\n */\nexport class AiPendingActionRepository {\n constructor(private readonly em: EntityManager) {}\n\n async create(\n input: AiPendingActionCreateInput,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingActionCreateResult> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.create requires tenantId')\n }\n if (!input?.agentId) {\n throw new Error('AiPendingActionRepository.create requires agentId')\n }\n if (!input?.toolName) {\n throw new Error('AiPendingActionRepository.create requires toolName')\n }\n if (!input?.idempotencyKey) {\n throw new Error(\n 'AiPendingActionRepository.create requires idempotencyKey',\n )\n }\n if (!input?.createdByUserId) {\n throw new Error(\n 'AiPendingActionRepository.create requires createdByUserId',\n )\n }\n\n const now = input.now ?? new Date()\n const ttlSeconds = Math.max(\n 1,\n Math.floor(\n typeof input.ttlSeconds === 'number' && Number.isFinite(input.ttlSeconds)\n ? input.ttlSeconds\n : resolveAiPendingActionTtlSeconds(),\n ),\n )\n const expiresAt = new Date(now.getTime() + ttlSeconds * 1000)\n\n return this.em.transactional(async (tx) => {\n const existing = await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n idempotencyKey: input.idempotencyKey,\n } as any,\n { orderBy: { createdAt: 'desc' } as any },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n if (existing && existing.status === 'pending') {\n return { row: existing, reused: true }\n }\n // A `confirmed`/`executing` row represents a mutation that already\n // ran (or is running). Inserting a fresh row with the same key would\n // collide with the unique `(tenantId, organizationId,\n // idempotencyKey)` index \u2014 this happens whenever the model repeats\n // the same tool call with the same arguments after it already\n // succeeded. Return the existing row instead of inserting; the\n // caller (`prepareMutation`) uses `reused` to tell the model the\n // operation already ran rather than re-queuing it.\n //\n // This only holds within the row's own dedupe/TTL window\n // (`now < expiresAt`, per the spec's \"within the TTL\" dedupe\n // promise). Outside it, treat the row as stale: a legitimate repeat\n // of the same arguments later on would otherwise be refused forever,\n // and a process that died mid-execution would leave every retry\n // stuck reading a dead `executing` row.\n if (\n existing &&\n (existing.status === 'confirmed' || existing.status === 'executing') &&\n now.getTime() < existing.expiresAt.getTime()\n ) {\n return { row: existing, reused: true }\n }\n // A terminal (`failed`/`cancelled`/`expired`) row, or a stale\n // `confirmed`/`executing` row past its dedupe window, would also\n // collide on the same unique index when we insert a fresh one with\n // the same key \u2014 which happens whenever the operator clicks \"Fix\n // with AI\" and the model retries the SAME tool with the SAME args,\n // or simply repeats the same arguments later. Re-key the stale row\n // (instead of deleting it) so a retry can always proceed: the stale\n // row's own card keeps resolving to its terminal/prior state via a\n // GET by id, rather than 404ing.\n if (\n existing &&\n (existing.status === 'failed' ||\n existing.status === 'cancelled' ||\n existing.status === 'expired' ||\n existing.status === 'confirmed' ||\n existing.status === 'executing')\n ) {\n existing.idempotencyKey = `${existing.idempotencyKey}:superseded:${existing.id}`\n await tx.persist(existing).flush()\n }\n const row = tx.create(AiPendingAction, {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId: input.agentId,\n toolName: input.toolName,\n conversationId: input.conversationId ?? null,\n targetEntityType: input.targetEntityType ?? null,\n targetRecordId: input.targetRecordId ?? null,\n normalizedInput: input.normalizedInput ?? {},\n fieldDiff: Array.isArray(input.fieldDiff) ? input.fieldDiff : [],\n records: normalizeRecords(input.records),\n failedRecords: null,\n sideEffectsSummary: input.sideEffectsSummary ?? null,\n recordVersion: input.recordVersion ?? null,\n attachmentIds: Array.isArray(input.attachmentIds)\n ? input.attachmentIds\n : [],\n idempotencyKey: input.idempotencyKey,\n createdByUserId: input.createdByUserId,\n status: 'pending' as AiPendingActionStatus,\n queueMode: (input.queueMode ?? 'inline') as AiPendingActionQueueMode,\n executionResult: null,\n createdAt: now,\n expiresAt,\n resolvedAt: null,\n resolvedByUserId: null,\n } as unknown as AiPendingAction)\n await tx.persist(row).flush()\n return { row, reused: false }\n })\n }\n\n async getById(\n id: string,\n ctx: AiPendingActionContext,\n ): Promise<AiPendingAction | null> {\n if (!id || !ctx?.tenantId) return null\n const owner = resolveOwnerScope(ctx)\n if (!owner) return null\n const row = await findOneWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n ...owner,\n } as any,\n { refresh: true },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return row ?? null\n }\n\n async listPendingForAgent(\n agentId: string,\n ctx: AiPendingActionContext,\n limit: number = 50,\n ): Promise<AiPendingAction[]> {\n if (!agentId || !ctx?.tenantId) return []\n const owner = resolveOwnerScope(ctx)\n if (!owner) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 200))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n agentId,\n status: 'pending',\n ...owner,\n } as any,\n {\n orderBy: { createdAt: 'desc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n\n async setStatus(\n id: string,\n nextStatus: AiPendingActionStatus,\n ctx: AiPendingActionContext,\n extra?: AiPendingActionSetStatusExtra,\n ): Promise<AiPendingAction> {\n if (!ctx?.tenantId) {\n throw new Error('AiPendingActionRepository.setStatus requires tenantId')\n }\n if (!id) {\n throw new Error('AiPendingActionRepository.setStatus requires id')\n }\n const owner = resolveOwnerScope(ctx)\n return this.em.transactional(async (tx) => {\n const existing = owner\n ? await findOneWithDecryption<AiPendingAction>(\n tx as unknown as EntityManager,\n AiPendingAction,\n {\n id,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n ...owner,\n } as any,\n { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n : null\n if (!existing) {\n throw new Error(`AiPendingAction not found: ${id}`)\n }\n if (extra?.expectedStatus && existing.status !== extra.expectedStatus) {\n throw new AiPendingActionStateError(existing.status, nextStatus)\n }\n if (existing.status === nextStatus) {\n return existing\n }\n const allowed = AI_PENDING_ACTION_ALLOWED_TRANSITIONS[existing.status] ?? []\n if (!allowed.includes(nextStatus)) {\n throw new AiPendingActionStateError(existing.status, nextStatus)\n }\n const now = extra?.now ?? new Date()\n existing.status = nextStatus\n if (\n nextStatus === 'confirmed' ||\n nextStatus === 'cancelled' ||\n nextStatus === 'expired' ||\n nextStatus === 'failed'\n ) {\n existing.resolvedAt = existing.resolvedAt ?? now\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'resolvedByUserId')) {\n existing.resolvedByUserId = extra.resolvedByUserId ?? null\n } else if (nextStatus === 'expired') {\n existing.resolvedByUserId = null\n }\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'executionResult')) {\n existing.executionResult = extra.executionResult ?? null\n }\n if (extra && Object.prototype.hasOwnProperty.call(extra, 'failedRecords')) {\n existing.failedRecords = normalizeFailedRecords(extra.failedRecords)\n }\n await tx.persist(existing).flush()\n return existing\n })\n }\n\n async listExpired(\n ctx: AiPendingActionContext,\n now: Date,\n limit: number = 100,\n ): Promise<AiPendingAction[]> {\n if (!ctx?.tenantId) return []\n const capped = Math.max(1, Math.min(Math.floor(limit), 500))\n const rows = await findWithDecryption<AiPendingAction>(\n this.em,\n AiPendingAction,\n {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n status: 'pending',\n expiresAt: { $lt: now } as any,\n } as any,\n {\n orderBy: { expiresAt: 'asc' } as any,\n limit: capped,\n },\n {\n tenantId: ctx.tenantId ?? null,\n organizationId: ctx.organizationId ?? null,\n },\n )\n return rows\n }\n}\n\nconst OWNER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nfunction resolveOwnerScope(ctx: AiPendingActionContext): { createdByUserId?: string } | null {\n if (ctx.userId === null) return {}\n if (typeof ctx.userId === 'string' && OWNER_ID_PATTERN.test(ctx.userId)) {\n return { createdByUserId: ctx.userId }\n }\n return null\n}\n\nfunction normalizeRecords(\n records: AiPendingActionRecordDiff[] | null | undefined,\n): AiPendingActionRecordDiff[] | null {\n if (!Array.isArray(records) || records.length === 0) return null\n return records\n}\n\nfunction normalizeFailedRecords(\n failed: AiPendingActionFailedRecord[] | null | undefined,\n): AiPendingActionFailedRecord[] | null {\n if (!Array.isArray(failed) || failed.length === 0) return null\n return failed\n}\n\nexport default AiPendingActionRepository\n"],
5
+ "mappings": "AAAA,SAAS,gBAAgB;AAEzB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AAwEA,MAAM,0BAA0B;AAAA,EACrC,YAA6B,IAAmB;AAAnB;AAAA,EAAoB;AAAA,EAEjD,MAAM,OACJ,OACA,KACsC;AACtC,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,oDAAoD;AAAA,IACtE;AACA,QAAI,CAAC,OAAO,SAAS;AACnB,YAAM,IAAI,MAAM,mDAAmD;AAAA,IACrE;AACA,QAAI,CAAC,OAAO,UAAU;AACpB,YAAM,IAAI,MAAM,oDAAoD;AAAA,IACtE;AACA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IAAI,KAAK,MAAM,KAAK,GAAG,GAAG,CAAC;AAC3D,UAAM,OAAO,MAAM;AAAA,MACjB,KAAK;AAAA,MACL;AAAA,MACA;AAAA,QACE,UAAU,IAAI;AAAA,QACd,gBAAgB,IAAI,kBAAkB;AAAA,QACtC,QAAQ;AAAA,QACR,WAAW,EAAE,KAAK,IAAI;AAAA,MACxB;AAAA,MACA;AAAA,QACE,SAAS,EAAE,WAAW,MAAM;AAAA,QAC5B,OAAO;AAAA,MACT;AAAA,MACA;AAAA,QACE,UAAU,IAAI,YAAY;AAAA,QAC1B,gBAAgB,IAAI,kBAAkB;AAAA,MACxC;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAEA,MAAM,mBAAmB;AAEzB,SAAS,kBAAkB,KAAkE;AAC3F,MAAI,IAAI,WAAW,KAAM,QAAO,CAAC;AACjC,MAAI,OAAO,IAAI,WAAW,YAAY,iBAAiB,KAAK,IAAI,MAAM,GAAG;AACvE,WAAO,EAAE,iBAAiB,IAAI,OAAO;AAAA,EACvC;AACA,SAAO;AACT;AAEA,SAAS,iBACP,SACoC;AACpC,MAAI,CAAC,MAAM,QAAQ,OAAO,KAAK,QAAQ,WAAW,EAAG,QAAO;AAC5D,SAAO;AACT;AAEA,SAAS,uBACP,QACsC;AACtC,MAAI,CAAC,MAAM,QAAQ,MAAM,KAAK,OAAO,WAAW,EAAG,QAAO;AAC1D,SAAO;AACT;AAEA,IAAO,oCAAQ;",
6
6
  "names": []
7
7
  }
@@ -1,8 +1,9 @@
1
+ import { AiPendingActionStateError } from "./pending-action-types.js";
1
2
  import { createLogger } from "@open-mercato/shared/lib/logger";
2
3
  import { AiPendingActionRepository } from "../data/repositories/AiPendingActionRepository.js";
3
4
  import { emitAiAssistantEvent } from "../events.js";
4
5
  import { hasRequiredFeatures } from "./auth.js";
5
- import { resolveToolFeaturesDeniedMessage } from "./pending-action-messages.js";
6
+ import { resolvePendingActionAlreadyResolvedMessage, resolveToolFeaturesDeniedMessage } from "./pending-action-messages.js";
6
7
  import {
7
8
  planPendingActionExecution,
8
9
  resolvePendingActionBatchMessages,
@@ -222,11 +223,30 @@ async function executePendingActionConfirm(input) {
222
223
  const droppedDuplicateFailedRecords = batchMessages ? toDuplicateDroppedFailedRecords(plan.droppedDuplicateRecordIds, batchMessages) : null;
223
224
  const blockedFailedRecords = mergeFailedRecords(partialFailedRecords, notPreviewedFailedRecords);
224
225
  const preExecutionFailedRecords = mergeFailedRecords(blockedFailedRecords, droppedDuplicateFailedRecords);
225
- const confirmedRow = await repo.setStatus(action.id, "confirmed", scope, {
226
- resolvedByUserId: ctx.userId,
227
- now: clock,
228
- ...preExecutionFailedRecords ? { failedRecords: preExecutionFailedRecords } : {}
229
- });
226
+ let confirmedRow;
227
+ try {
228
+ confirmedRow = await repo.setStatus(action.id, "confirmed", scope, {
229
+ expectedStatus: "pending",
230
+ resolvedByUserId: ctx.userId,
231
+ now: clock,
232
+ ...preExecutionFailedRecords ? { failedRecords: preExecutionFailedRecords } : {}
233
+ });
234
+ } catch (error) {
235
+ if (!(error instanceof AiPendingActionStateError)) throw error;
236
+ const current = await repo.getById(action.id, scope);
237
+ if (!current) throw error;
238
+ if (current.status === "confirmed" || current.status === "executing") {
239
+ return { ok: true, action: current, executionResult: current.executionResult ?? {} };
240
+ }
241
+ return {
242
+ ok: false,
243
+ action: current,
244
+ executionResult: current.executionResult ?? {
245
+ error: { code: "invalid_status", message: await resolvePendingActionAlreadyResolvedMessage() }
246
+ },
247
+ cause: error
248
+ };
249
+ }
230
250
  const executingRow = await repo.setStatus(confirmedRow.id, "executing", scope, { now: clock });
231
251
  let handlerOutput;
232
252
  try {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/lib/pending-action-executor.ts"],
4
- "sourcesContent": ["/**\n * Pending-action executor (spec \u00A79.4, Step 5.8).\n *\n * Transitions an `AiPendingAction` from `pending \u2192 confirmed \u2192 executing`,\n * invokes the wrapped tool handler, and records the outcome. Isolated from\n * the HTTP route so the unit suite can exercise the state-machine +\n * event-emission + idempotency guarantees without constructing a\n * `NextRequest`.\n *\n * Atomicity:\n * - The `pending \u2192 confirmed` and `confirmed \u2192 executing` transitions go\n * through the repository's `em.transactional` boundary. If the process\n * crashes between steps, the row is left in an intermediate terminal\n * state (`executing` or `confirmed`) that the operator can recover \u2014\n * NEVER in a partially-applied state that hides the crash.\n * - The tool handler itself runs OUTSIDE the repo transaction so that a\n * long-running write does not hold an `ai_pending_actions` row lock.\n * The handler's own transaction boundary (typically a command) is the\n * unit of atomicity for the underlying data change.\n */\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { AiPendingActionRepository } from '../data/repositories/AiPendingActionRepository'\nimport type { AiPendingAction } from '../data/entities'\nimport { emitAiAssistantEvent } from '../events'\nimport type { AiActionConfirmedPayload } from '../events'\nimport type { AiAgentDefinition } from './ai-agent-definition'\nimport type { AiToolDefinition, McpToolContext } from './types'\nimport { hasRequiredFeatures } from './auth'\nimport { resolveToolFeaturesDeniedMessage } from './pending-action-messages'\nimport type {\n AiPendingActionExecutionResult,\n AiPendingActionFailedRecord,\n} from './pending-action-types'\nimport {\n planPendingActionExecution,\n resolvePendingActionBatchMessages,\n toDuplicateDroppedFailedRecords,\n toNotPreviewedFailedRecords,\n} from './pending-action-batch'\n\nconst logger = createLogger('ai_assistant')\n\nexport interface PendingActionExecuteContext {\n tenantId: string\n organizationId: string | null\n userId: string\n userFeatures: string[]\n isSuperAdmin: boolean\n container: import('awilix').AwilixContainer\n}\n\nexport interface PendingActionExecuteInput {\n action: AiPendingAction\n agent: AiAgentDefinition\n tool: AiToolDefinition\n ctx: PendingActionExecuteContext\n /** Carried over from the re-check; written onto the row with status=confirmed. */\n failedRecords?: AiPendingActionFailedRecord[] | null\n repo?: AiPendingActionRepository\n /**\n * Injection seam for unit tests. When omitted, emission is routed via\n * the typed `emitAiAssistantEvent` helper (the normal production path).\n * When supplied, the raw bus is used directly \u2014 kept for legacy tests\n * that assert on the bus call surface.\n */\n emitEvent?: (\n eventId: 'ai.action.confirmed',\n payload: AiActionConfirmedPayload,\n ) => Promise<void>\n now?: Date\n}\n\nexport interface PendingActionExecuteOk {\n ok: true\n action: AiPendingAction\n executionResult: AiPendingActionExecutionResult\n}\n\nexport interface PendingActionExecuteFail {\n ok: false\n action: AiPendingAction\n executionResult: AiPendingActionExecutionResult\n /** The underlying error \u2014 the route translates into a 200 with `executionResult.error` set. */\n cause: unknown\n}\n\nexport type PendingActionExecuteResult = PendingActionExecuteOk | PendingActionExecuteFail\n\nconst CONFIRMED_EVENT_ID = 'ai.action.confirmed' as const\n\ntype ConfirmedEmitter = (\n eventId: 'ai.action.confirmed',\n payload: AiActionConfirmedPayload,\n) => Promise<void>\n\nconst defaultConfirmedEmitter: ConfirmedEmitter = async (eventId, payload) => {\n await emitAiAssistantEvent(eventId, payload as unknown as Record<string, unknown>, {\n persistent: true,\n })\n}\n\nasync function emitConfirmed(\n emitter: ConfirmedEmitter,\n payload: AiActionConfirmedPayload,\n): Promise<void> {\n try {\n await emitter(CONFIRMED_EVENT_ID, payload)\n } catch (error) {\n logger.warn('Failed to emit pending-action event', { eventId: CONFIRMED_EVENT_ID, err: error })\n }\n}\n\nfunction normalizeExecutionResult(\n raw: unknown,\n): AiPendingActionExecutionResult {\n if (!raw || typeof raw !== 'object') return {}\n const source = raw as Record<string, unknown>\n const result: AiPendingActionExecutionResult = {}\n if (typeof source.recordId === 'string') result.recordId = source.recordId\n if (typeof source.commandName === 'string') result.commandName = source.commandName\n return result\n}\n\n/**\n * Extract per-record handler failures from a bulk tool's return value so\n * they can be persisted onto the pending-action row's `failedRecords[]`.\n *\n * Bulk mutation tools (Step 5.14) return a result of the shape:\n * { commandName, records: [{ recordId, status, before, after, error? }],\n * failedRecordIds: string[], error? }\n *\n * We pull the entries whose `status !== 'updated'` AND carry an `error`\n * object, coerce them to the `AiPendingActionFailedRecord` shape, and\n * return them so the executor can merge with re-check-sourced failures\n * at the final `executing \u2192 confirmed` transition (spec \u00A79.8 line 746:\n * \"a failure inside the confirm handler ... is recorded per-record in\n * executionResult.failedRecords[] / row.failedRecords\").\n *\n * Returns an empty array when the handler output does not carry the\n * batch shape (single-record tools never populate this \u2014 their failures\n * either throw from the handler and land in `executionResult.error` or\n * succeed cleanly).\n */\n/**\n * Convert a thrown handler error into the structured shape we persist on\n * `executionResult.error`. The previous implementation only kept\n * `{ code: 'handler_error', message }` \u2014 for ZodError that flattened to\n * the literal string \"Invalid input\", which was not enough context for\n * the operator's \"Fix with AI\" retry to actually fix anything. This\n * version preserves the original error name, Zod issues / fieldErrors,\n * an `input` echo of the arguments the handler was called with, and any\n * structured `cause` so the model can self-correct.\n *\n * Stack traces are deliberately gated behind `OM_AI_INCLUDE_HANDLER_STACK=1`\n * \u2014 they're noise to the model and a leak risk in tenant-visible UI.\n */\nfunction buildHandlerErrorFromThrown(\n error: unknown,\n input: unknown,\n): NonNullable<AiPendingActionExecutionResult['error']> {\n const message = error instanceof Error ? error.message : String(error)\n const name = error instanceof Error ? error.name : undefined\n const out: NonNullable<AiPendingActionExecutionResult['error']> = {\n code: 'handler_error',\n message: message || 'Tool handler threw an error.',\n }\n if (name) out.name = name\n\n // Echo the input so the model can compare what it sent vs. what the\n // schema expected. `normalizedInput` has already been Zod-parsed at\n // prepareMutation time so the values are JSON-safe.\n if (input !== undefined) {\n try {\n out.input = JSON.parse(JSON.stringify(input))\n } catch {\n // ignore \u2014 non-serializable input is rare and the model can still\n // work from the message + Zod issues.\n }\n }\n\n const details: Record<string, unknown> = {}\n\n if (error && typeof error === 'object') {\n const err = error as Record<string, unknown>\n // ZodError: forward `issues[]` verbatim and a flat `fieldErrors`\n // form so the model can locate the failing field by name even when\n // the message has been collapsed to \"Invalid input\".\n const issues = err.issues\n if (Array.isArray(issues) && issues.length > 0) {\n details.issues = issues.map((issue) => {\n if (!issue || typeof issue !== 'object') return issue\n const obj = issue as Record<string, unknown>\n return {\n path: Array.isArray(obj.path) ? obj.path : undefined,\n message: typeof obj.message === 'string' ? obj.message : undefined,\n code: typeof obj.code === 'string' ? obj.code : undefined,\n ...(typeof obj.expected === 'string' ? { expected: obj.expected } : {}),\n ...(typeof obj.received === 'string' ? { received: obj.received } : {}),\n }\n })\n const fieldErrors: Record<string, string[]> = {}\n for (const issue of issues as Array<Record<string, unknown>>) {\n const path = Array.isArray(issue.path) ? issue.path.join('.') : ''\n const msg = typeof issue.message === 'string' ? issue.message : null\n if (!path || !msg) continue\n if (!fieldErrors[path]) fieldErrors[path] = []\n fieldErrors[path].push(msg)\n }\n if (Object.keys(fieldErrors).length > 0) {\n details.fieldErrors = fieldErrors\n }\n if (out.code === 'handler_error') out.code = 'validation_error'\n }\n // Forward a known `code` if the handler error carries one.\n if (typeof err.code === 'string' && err.code.length > 0) {\n out.code = err.code\n }\n // Carry the cause when it is JSON-serializable (string, number, plain object).\n if (err.cause !== undefined) {\n try {\n details.cause = JSON.parse(JSON.stringify(err.cause))\n } catch {\n if (err.cause instanceof Error) {\n details.cause = { message: err.cause.message, name: err.cause.name }\n }\n }\n }\n // Pull through any other plain-object enumerable own props the handler\n // attached (e.g. `expected`, `actual`, `target`).\n for (const key of Object.keys(err)) {\n if (key === 'issues' || key === 'cause' || key === 'code' || key === 'message' || key === 'name' || key === 'stack') continue\n const value = err[key]\n if (value === undefined) continue\n try {\n details[key] = JSON.parse(JSON.stringify(value))\n } catch {\n // skip non-serializable\n }\n }\n }\n\n if (Object.keys(details).length > 0) {\n out.details = details\n }\n\n if (process.env.OM_AI_INCLUDE_HANDLER_STACK === '1' && error instanceof Error && error.stack) {\n // Trim to the top frames so the persisted result stays bounded.\n const lines = error.stack.split('\\n').slice(0, 6)\n out.stack = lines.join('\\n')\n }\n\n return out\n}\n\nfunction extractHandlerFailedRecords(raw: unknown): AiPendingActionFailedRecord[] {\n if (!raw || typeof raw !== 'object') return []\n const source = raw as Record<string, unknown>\n const records = source.records\n if (!Array.isArray(records) || records.length === 0) return []\n const out: AiPendingActionFailedRecord[] = []\n for (const entry of records) {\n if (!entry || typeof entry !== 'object') continue\n const record = entry as Record<string, unknown>\n if (typeof record.recordId !== 'string') continue\n const status = typeof record.status === 'string' ? record.status : null\n if (status === 'updated') continue\n const errorField = record.error\n if (!errorField || typeof errorField !== 'object') continue\n const error = errorField as Record<string, unknown>\n const code = typeof error.code === 'string' ? error.code : 'handler_error'\n const message = typeof error.message === 'string' ? error.message : 'Record update failed.'\n out.push({\n recordId: record.recordId,\n error: { code, message },\n })\n }\n return out\n}\n\nfunction mergeFailedRecords(\n recheck: AiPendingActionFailedRecord[] | null | undefined,\n handler: AiPendingActionFailedRecord[] | null | undefined,\n): AiPendingActionFailedRecord[] | null {\n const seen = new Map<string, AiPendingActionFailedRecord>()\n for (const entry of recheck ?? []) {\n if (entry && typeof entry.recordId === 'string' && !seen.has(entry.recordId)) {\n seen.set(entry.recordId, entry)\n }\n }\n for (const entry of handler ?? []) {\n if (entry && typeof entry.recordId === 'string' && !seen.has(entry.recordId)) {\n seen.set(entry.recordId, entry)\n }\n }\n if (seen.size === 0) return null\n return Array.from(seen.values())\n}\n\nfunction toToolHandlerContext(\n ctx: PendingActionExecuteContext,\n tool: AiToolDefinition,\n approvedPendingActionId: string,\n expectedRecordVersions: Record<string, string>,\n): McpToolContext {\n return {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n container: ctx.container,\n userFeatures: ctx.userFeatures,\n isSuperAdmin: ctx.isSuperAdmin,\n tool,\n approvedPendingActionId,\n expectedRecordVersions,\n }\n}\n\n/**\n * Idempotent entry point for the Step 5.8 confirm route.\n *\n * - If the action is already `confirmed` with a stored `executionResult`,\n * returns that prior result without re-invoking the handler (double-click /\n * retry contract).\n * - If the action is already `confirmed` without a stored `executionResult`\n * (shouldn't happen in practice), returns a synthesized empty result.\n * - If the action is still `pending`, runs the transitions and the handler.\n * - Any other status is rejected at the re-check layer before this helper\n * is ever called; this helper treats them as invariant violations.\n * - A caller without the tool's `requiredFeatures` is refused before any\n * state transition, so the row stays `pending` (mirrors the re-check).\n */\nexport async function executePendingActionConfirm(\n input: PendingActionExecuteInput,\n): Promise<PendingActionExecuteResult> {\n const { action, agent, tool, ctx, failedRecords, now } = input\n const repo = input.repo ?? new AiPendingActionRepository(ctx.container.resolve('em'))\n const scope = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n }\n const clock = now ?? new Date()\n const emitter: ConfirmedEmitter = input.emitEvent ?? defaultConfirmedEmitter\n\n if (action.status === 'confirmed') {\n const prior = (action.executionResult ?? {}) as AiPendingActionExecutionResult\n return { ok: true, action, executionResult: prior }\n }\n\n if (action.status === 'executing') {\n const prior = (action.executionResult ?? {}) as AiPendingActionExecutionResult\n return { ok: true, action, executionResult: prior }\n }\n\n if (action.status !== 'pending') {\n return {\n ok: false,\n action,\n executionResult: {\n error: { code: 'invalid_status', message: `Action is in status \"${action.status}\".` },\n },\n cause: new Error(`Action is in status \"${action.status}\"`),\n }\n }\n\n const toolFeatures = tool.requiredFeatures ?? []\n if (!hasRequiredFeatures(toolFeatures, ctx.userFeatures, ctx.isSuperAdmin)) {\n return {\n ok: false,\n action,\n executionResult: {\n error: {\n code: 'tool_features_denied',\n message: await resolveToolFeaturesDeniedMessage(toolFeatures),\n },\n },\n cause: new Error(`Caller lacks one of the tool's required features for \"${tool.name}\"`),\n }\n }\n\n const partialFailedRecords =\n Array.isArray(failedRecords) && failedRecords.length > 0 ? failedRecords : null\n\n const plan = planPendingActionExecution(action, tool, partialFailedRecords)\n if (plan.kind === 'refuse') {\n const messages = await resolvePendingActionBatchMessages()\n return {\n ok: false,\n action,\n executionResult: { error: { code: plan.code, message: messages.batchNotApplicable } },\n cause: new Error(`Pending action \"${action.id}\" no longer matches its approved preview`),\n }\n }\n if (plan.droppedDuplicateRecordIds.length > 0) {\n logger.warn('Pending action input repeats previewed records; only the first entry per record runs', {\n pendingActionId: action.id,\n toolName: tool.name,\n recordIds: plan.droppedDuplicateRecordIds,\n })\n }\n const batchMessages =\n plan.notPreviewedRecordIds.length > 0 || plan.droppedDuplicateRecordIds.length > 0\n ? await resolvePendingActionBatchMessages()\n : null\n const notPreviewedFailedRecords = batchMessages\n ? toNotPreviewedFailedRecords(plan.notPreviewedRecordIds, batchMessages)\n : null\n const droppedDuplicateFailedRecords = batchMessages\n ? toDuplicateDroppedFailedRecords(plan.droppedDuplicateRecordIds, batchMessages)\n : null\n const blockedFailedRecords = mergeFailedRecords(partialFailedRecords, notPreviewedFailedRecords)\n const preExecutionFailedRecords = mergeFailedRecords(blockedFailedRecords, droppedDuplicateFailedRecords)\n\n const confirmedRow = await repo.setStatus(action.id, 'confirmed', scope, {\n resolvedByUserId: ctx.userId,\n now: clock,\n ...(preExecutionFailedRecords ? { failedRecords: preExecutionFailedRecords } : {}),\n })\n const executingRow = await repo.setStatus(confirmedRow.id, 'executing', scope, { now: clock })\n\n let handlerOutput: unknown\n try {\n handlerOutput = await tool.handler(\n plan.input as never,\n toToolHandlerContext(ctx, tool, action.id, plan.expectedRecordVersions),\n )\n } catch (error) {\n const failureResult: AiPendingActionExecutionResult = {\n error: buildHandlerErrorFromThrown(error, plan.input),\n }\n const failedRow = await repo.setStatus(executingRow.id, 'failed', scope, {\n executionResult: failureResult,\n now: clock,\n })\n await emitConfirmed(emitter, {\n pendingActionId: failedRow.id,\n agentId: agent.id,\n toolName: tool.name,\n status: failedRow.status,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n userId: ctx.userId,\n resolvedByUserId: ctx.userId,\n resolvedAt: (failedRow.resolvedAt ?? clock).toISOString?.() ?? new Date(clock).toISOString(),\n executionResult: failureResult,\n })\n return {\n ok: false,\n action: failedRow,\n executionResult: failureResult,\n cause: error,\n }\n }\n\n const successResult = normalizeExecutionResult(handlerOutput)\n const handlerFailedRecords = extractHandlerFailedRecords(handlerOutput)\n const mergedFailedRecords = mergeFailedRecords(\n mergeFailedRecords(blockedFailedRecords, handlerFailedRecords),\n droppedDuplicateFailedRecords,\n )\n const confirmedExtra: Record<string, unknown> = {\n executionResult: successResult,\n now: clock,\n }\n // Always write `failedRecords` on the final transition so a batch that\n // had re-check-stale records but zero handler failures keeps the\n // original list, and a batch with handler failures merges both sets.\n // Explicit `null` collapses to \"no failures\" in the repository's\n // `normalizeFailedRecords` helper.\n confirmedExtra.failedRecords = mergedFailedRecords\n const confirmedFinal = await repo.setStatus(executingRow.id, 'confirmed', scope, confirmedExtra)\n const emitFailedRecordsPayload =\n Array.isArray(mergedFailedRecords) && mergedFailedRecords.length > 0\n ? mergedFailedRecords\n : null\n await emitConfirmed(emitter, {\n pendingActionId: confirmedFinal.id,\n agentId: agent.id,\n toolName: tool.name,\n status: confirmedFinal.status,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n userId: ctx.userId,\n resolvedByUserId: ctx.userId,\n resolvedAt: (confirmedFinal.resolvedAt ?? clock).toISOString?.() ?? new Date(clock).toISOString(),\n executionResult: successResult,\n ...(emitFailedRecordsPayload ? { failedRecords: emitFailedRecordsPayload } : {}),\n })\n return { ok: true, action: confirmedFinal, executionResult: successResult }\n}\n\nexport const PENDING_ACTION_CONFIRMED_EVENT_ID = CONFIRMED_EVENT_ID\n"],
5
- "mappings": "AAoBA,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAE1C,SAAS,4BAA4B;AAIrC,SAAS,2BAA2B;AACpC,SAAS,wCAAwC;AAKjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,cAAc;AAgD1C,MAAM,qBAAqB;AAO3B,MAAM,0BAA4C,OAAO,SAAS,YAAY;AAC5E,QAAM,qBAAqB,SAAS,SAA+C;AAAA,IACjF,YAAY;AAAA,EACd,CAAC;AACH;AAEA,eAAe,cACb,SACA,SACe;AACf,MAAI;AACF,UAAM,QAAQ,oBAAoB,OAAO;AAAA,EAC3C,SAAS,OAAO;AACd,WAAO,KAAK,uCAAuC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AAyB,aAAa;AAC5D,QAAM,uBAAuB,4BAA4B,aAAa;AACtE,QAAM,sBAAsB;AAAA,IAC1B,mBAAmB,sBAAsB,oBAAoB;AAAA,IAC7D;AAAA,EACF;AACA,QAAM,iBAA0C;AAAA,IAC9C,iBAAiB;AAAA,IACjB,KAAK;AAAA,EACP;AAMA,iBAAe,gBAAgB;AAC/B,QAAM,iBAAiB,MAAM,KAAK,UAAU,aAAa,IAAI,aAAa,OAAO,cAAc;AAC/F,QAAM,2BACJ,MAAM,QAAQ,mBAAmB,KAAK,oBAAoB,SAAS,IAC/D,sBACA;AACN,QAAM,cAAc,SAAS;AAAA,IAC3B,iBAAiB,eAAe;AAAA,IAChC,SAAS,MAAM;AAAA,IACf,UAAU,KAAK;AAAA,IACf,QAAQ,eAAe;AAAA,IACvB,UAAU,IAAI;AAAA,IACd,gBAAgB,IAAI,kBAAkB;AAAA,IACtC,QAAQ,IAAI;AAAA,IACZ,kBAAkB,IAAI;AAAA,IACtB,aAAa,eAAe,cAAc,OAAO,cAAc,KAAK,IAAI,KAAK,KAAK,EAAE,YAAY;AAAA,IAChG,iBAAiB;AAAA,IACjB,GAAI,2BAA2B,EAAE,eAAe,yBAAyB,IAAI,CAAC;AAAA,EAChF,CAAC;AACD,SAAO,EAAE,IAAI,MAAM,QAAQ,gBAAgB,iBAAiB,cAAc;AAC5E;AAEO,MAAM,oCAAoC;",
4
+ "sourcesContent": ["/**\n * Pending-action executor (spec \u00A79.4, Step 5.8).\n *\n * Transitions an `AiPendingAction` from `pending \u2192 confirmed \u2192 executing`,\n * invokes the wrapped tool handler, and records the outcome. Isolated from\n * the HTTP route so the unit suite can exercise the state-machine +\n * event-emission + idempotency guarantees without constructing a\n * `NextRequest`.\n *\n * Atomicity:\n * - The `pending \u2192 confirmed` and `confirmed \u2192 executing` transitions go\n * through the repository's `em.transactional` boundary. If the process\n * crashes between steps, the row is left in an intermediate terminal\n * state (`executing` or `confirmed`) that the operator can recover \u2014\n * NEVER in a partially-applied state that hides the crash.\n * - The tool handler itself runs OUTSIDE the repo transaction so that a\n * long-running write does not hold an `ai_pending_actions` row lock.\n * The handler's own transaction boundary (typically a command) is the\n * unit of atomicity for the underlying data change.\n */\nimport { AiPendingActionStateError } from './pending-action-types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { AiPendingActionRepository } from '../data/repositories/AiPendingActionRepository'\nimport type { AiPendingAction } from '../data/entities'\nimport { emitAiAssistantEvent } from '../events'\nimport type { AiActionConfirmedPayload } from '../events'\nimport type { AiAgentDefinition } from './ai-agent-definition'\nimport type { AiToolDefinition, McpToolContext } from './types'\nimport { hasRequiredFeatures } from './auth'\nimport { resolvePendingActionAlreadyResolvedMessage, resolveToolFeaturesDeniedMessage } from './pending-action-messages'\nimport type {\n AiPendingActionExecutionResult,\n AiPendingActionFailedRecord,\n} from './pending-action-types'\nimport {\n planPendingActionExecution,\n resolvePendingActionBatchMessages,\n toDuplicateDroppedFailedRecords,\n toNotPreviewedFailedRecords,\n} from './pending-action-batch'\n\nconst logger = createLogger('ai_assistant')\n\nexport interface PendingActionExecuteContext {\n tenantId: string\n organizationId: string | null\n userId: string\n userFeatures: string[]\n isSuperAdmin: boolean\n container: import('awilix').AwilixContainer\n}\n\nexport interface PendingActionExecuteInput {\n action: AiPendingAction\n agent: AiAgentDefinition\n tool: AiToolDefinition\n ctx: PendingActionExecuteContext\n /** Carried over from the re-check; written onto the row with status=confirmed. */\n failedRecords?: AiPendingActionFailedRecord[] | null\n repo?: AiPendingActionRepository\n /**\n * Injection seam for unit tests. When omitted, emission is routed via\n * the typed `emitAiAssistantEvent` helper (the normal production path).\n * When supplied, the raw bus is used directly \u2014 kept for legacy tests\n * that assert on the bus call surface.\n */\n emitEvent?: (\n eventId: 'ai.action.confirmed',\n payload: AiActionConfirmedPayload,\n ) => Promise<void>\n now?: Date\n}\n\nexport interface PendingActionExecuteOk {\n ok: true\n action: AiPendingAction\n executionResult: AiPendingActionExecutionResult\n}\n\nexport interface PendingActionExecuteFail {\n ok: false\n action: AiPendingAction\n executionResult: AiPendingActionExecutionResult\n /** The underlying error \u2014 the route translates into a 200 with `executionResult.error` set. */\n cause: unknown\n}\n\nexport type PendingActionExecuteResult = PendingActionExecuteOk | PendingActionExecuteFail\n\nconst CONFIRMED_EVENT_ID = 'ai.action.confirmed' as const\n\ntype ConfirmedEmitter = (\n eventId: 'ai.action.confirmed',\n payload: AiActionConfirmedPayload,\n) => Promise<void>\n\nconst defaultConfirmedEmitter: ConfirmedEmitter = async (eventId, payload) => {\n await emitAiAssistantEvent(eventId, payload as unknown as Record<string, unknown>, {\n persistent: true,\n })\n}\n\nasync function emitConfirmed(\n emitter: ConfirmedEmitter,\n payload: AiActionConfirmedPayload,\n): Promise<void> {\n try {\n await emitter(CONFIRMED_EVENT_ID, payload)\n } catch (error) {\n logger.warn('Failed to emit pending-action event', { eventId: CONFIRMED_EVENT_ID, err: error })\n }\n}\n\nfunction normalizeExecutionResult(\n raw: unknown,\n): AiPendingActionExecutionResult {\n if (!raw || typeof raw !== 'object') return {}\n const source = raw as Record<string, unknown>\n const result: AiPendingActionExecutionResult = {}\n if (typeof source.recordId === 'string') result.recordId = source.recordId\n if (typeof source.commandName === 'string') result.commandName = source.commandName\n return result\n}\n\n/**\n * Extract per-record handler failures from a bulk tool's return value so\n * they can be persisted onto the pending-action row's `failedRecords[]`.\n *\n * Bulk mutation tools (Step 5.14) return a result of the shape:\n * { commandName, records: [{ recordId, status, before, after, error? }],\n * failedRecordIds: string[], error? }\n *\n * We pull the entries whose `status !== 'updated'` AND carry an `error`\n * object, coerce them to the `AiPendingActionFailedRecord` shape, and\n * return them so the executor can merge with re-check-sourced failures\n * at the final `executing \u2192 confirmed` transition (spec \u00A79.8 line 746:\n * \"a failure inside the confirm handler ... is recorded per-record in\n * executionResult.failedRecords[] / row.failedRecords\").\n *\n * Returns an empty array when the handler output does not carry the\n * batch shape (single-record tools never populate this \u2014 their failures\n * either throw from the handler and land in `executionResult.error` or\n * succeed cleanly).\n */\n/**\n * Convert a thrown handler error into the structured shape we persist on\n * `executionResult.error`. The previous implementation only kept\n * `{ code: 'handler_error', message }` \u2014 for ZodError that flattened to\n * the literal string \"Invalid input\", which was not enough context for\n * the operator's \"Fix with AI\" retry to actually fix anything. This\n * version preserves the original error name, Zod issues / fieldErrors,\n * an `input` echo of the arguments the handler was called with, and any\n * structured `cause` so the model can self-correct.\n *\n * Stack traces are deliberately gated behind `OM_AI_INCLUDE_HANDLER_STACK=1`\n * \u2014 they're noise to the model and a leak risk in tenant-visible UI.\n */\nfunction buildHandlerErrorFromThrown(\n error: unknown,\n input: unknown,\n): NonNullable<AiPendingActionExecutionResult['error']> {\n const message = error instanceof Error ? error.message : String(error)\n const name = error instanceof Error ? error.name : undefined\n const out: NonNullable<AiPendingActionExecutionResult['error']> = {\n code: 'handler_error',\n message: message || 'Tool handler threw an error.',\n }\n if (name) out.name = name\n\n // Echo the input so the model can compare what it sent vs. what the\n // schema expected. `normalizedInput` has already been Zod-parsed at\n // prepareMutation time so the values are JSON-safe.\n if (input !== undefined) {\n try {\n out.input = JSON.parse(JSON.stringify(input))\n } catch {\n // ignore \u2014 non-serializable input is rare and the model can still\n // work from the message + Zod issues.\n }\n }\n\n const details: Record<string, unknown> = {}\n\n if (error && typeof error === 'object') {\n const err = error as Record<string, unknown>\n // ZodError: forward `issues[]` verbatim and a flat `fieldErrors`\n // form so the model can locate the failing field by name even when\n // the message has been collapsed to \"Invalid input\".\n const issues = err.issues\n if (Array.isArray(issues) && issues.length > 0) {\n details.issues = issues.map((issue) => {\n if (!issue || typeof issue !== 'object') return issue\n const obj = issue as Record<string, unknown>\n return {\n path: Array.isArray(obj.path) ? obj.path : undefined,\n message: typeof obj.message === 'string' ? obj.message : undefined,\n code: typeof obj.code === 'string' ? obj.code : undefined,\n ...(typeof obj.expected === 'string' ? { expected: obj.expected } : {}),\n ...(typeof obj.received === 'string' ? { received: obj.received } : {}),\n }\n })\n const fieldErrors: Record<string, string[]> = {}\n for (const issue of issues as Array<Record<string, unknown>>) {\n const path = Array.isArray(issue.path) ? issue.path.join('.') : ''\n const msg = typeof issue.message === 'string' ? issue.message : null\n if (!path || !msg) continue\n if (!fieldErrors[path]) fieldErrors[path] = []\n fieldErrors[path].push(msg)\n }\n if (Object.keys(fieldErrors).length > 0) {\n details.fieldErrors = fieldErrors\n }\n if (out.code === 'handler_error') out.code = 'validation_error'\n }\n // Forward a known `code` if the handler error carries one.\n if (typeof err.code === 'string' && err.code.length > 0) {\n out.code = err.code\n }\n // Carry the cause when it is JSON-serializable (string, number, plain object).\n if (err.cause !== undefined) {\n try {\n details.cause = JSON.parse(JSON.stringify(err.cause))\n } catch {\n if (err.cause instanceof Error) {\n details.cause = { message: err.cause.message, name: err.cause.name }\n }\n }\n }\n // Pull through any other plain-object enumerable own props the handler\n // attached (e.g. `expected`, `actual`, `target`).\n for (const key of Object.keys(err)) {\n if (key === 'issues' || key === 'cause' || key === 'code' || key === 'message' || key === 'name' || key === 'stack') continue\n const value = err[key]\n if (value === undefined) continue\n try {\n details[key] = JSON.parse(JSON.stringify(value))\n } catch {\n // skip non-serializable\n }\n }\n }\n\n if (Object.keys(details).length > 0) {\n out.details = details\n }\n\n if (process.env.OM_AI_INCLUDE_HANDLER_STACK === '1' && error instanceof Error && error.stack) {\n // Trim to the top frames so the persisted result stays bounded.\n const lines = error.stack.split('\\n').slice(0, 6)\n out.stack = lines.join('\\n')\n }\n\n return out\n}\n\nfunction extractHandlerFailedRecords(raw: unknown): AiPendingActionFailedRecord[] {\n if (!raw || typeof raw !== 'object') return []\n const source = raw as Record<string, unknown>\n const records = source.records\n if (!Array.isArray(records) || records.length === 0) return []\n const out: AiPendingActionFailedRecord[] = []\n for (const entry of records) {\n if (!entry || typeof entry !== 'object') continue\n const record = entry as Record<string, unknown>\n if (typeof record.recordId !== 'string') continue\n const status = typeof record.status === 'string' ? record.status : null\n if (status === 'updated') continue\n const errorField = record.error\n if (!errorField || typeof errorField !== 'object') continue\n const error = errorField as Record<string, unknown>\n const code = typeof error.code === 'string' ? error.code : 'handler_error'\n const message = typeof error.message === 'string' ? error.message : 'Record update failed.'\n out.push({\n recordId: record.recordId,\n error: { code, message },\n })\n }\n return out\n}\n\nfunction mergeFailedRecords(\n recheck: AiPendingActionFailedRecord[] | null | undefined,\n handler: AiPendingActionFailedRecord[] | null | undefined,\n): AiPendingActionFailedRecord[] | null {\n const seen = new Map<string, AiPendingActionFailedRecord>()\n for (const entry of recheck ?? []) {\n if (entry && typeof entry.recordId === 'string' && !seen.has(entry.recordId)) {\n seen.set(entry.recordId, entry)\n }\n }\n for (const entry of handler ?? []) {\n if (entry && typeof entry.recordId === 'string' && !seen.has(entry.recordId)) {\n seen.set(entry.recordId, entry)\n }\n }\n if (seen.size === 0) return null\n return Array.from(seen.values())\n}\n\nfunction toToolHandlerContext(\n ctx: PendingActionExecuteContext,\n tool: AiToolDefinition,\n approvedPendingActionId: string,\n expectedRecordVersions: Record<string, string>,\n): McpToolContext {\n return {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n container: ctx.container,\n userFeatures: ctx.userFeatures,\n isSuperAdmin: ctx.isSuperAdmin,\n tool,\n approvedPendingActionId,\n expectedRecordVersions,\n }\n}\n\n/**\n * Idempotent entry point for the Step 5.8 confirm route.\n *\n * - If the action is already `confirmed` with a stored `executionResult`,\n * returns that prior result without re-invoking the handler (double-click /\n * retry contract).\n * - If the action is already `confirmed` without a stored `executionResult`\n * (shouldn't happen in practice), returns a synthesized empty result.\n * - If the action is still `pending`, runs the transitions and the handler.\n * - Any other status is rejected at the re-check layer before this helper\n * is ever called; this helper treats them as invariant violations.\n * - A caller without the tool's `requiredFeatures` is refused before any\n * state transition, so the row stays `pending` (mirrors the re-check).\n */\nexport async function executePendingActionConfirm(\n input: PendingActionExecuteInput,\n): Promise<PendingActionExecuteResult> {\n const { action, agent, tool, ctx, failedRecords, now } = input\n const repo = input.repo ?? new AiPendingActionRepository(ctx.container.resolve('em'))\n const scope = {\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId,\n userId: ctx.userId,\n }\n const clock = now ?? new Date()\n const emitter: ConfirmedEmitter = input.emitEvent ?? defaultConfirmedEmitter\n\n if (action.status === 'confirmed') {\n const prior = (action.executionResult ?? {}) as AiPendingActionExecutionResult\n return { ok: true, action, executionResult: prior }\n }\n\n if (action.status === 'executing') {\n const prior = (action.executionResult ?? {}) as AiPendingActionExecutionResult\n return { ok: true, action, executionResult: prior }\n }\n\n if (action.status !== 'pending') {\n return {\n ok: false,\n action,\n executionResult: {\n error: { code: 'invalid_status', message: `Action is in status \"${action.status}\".` },\n },\n cause: new Error(`Action is in status \"${action.status}\"`),\n }\n }\n\n const toolFeatures = tool.requiredFeatures ?? []\n if (!hasRequiredFeatures(toolFeatures, ctx.userFeatures, ctx.isSuperAdmin)) {\n return {\n ok: false,\n action,\n executionResult: {\n error: {\n code: 'tool_features_denied',\n message: await resolveToolFeaturesDeniedMessage(toolFeatures),\n },\n },\n cause: new Error(`Caller lacks one of the tool's required features for \"${tool.name}\"`),\n }\n }\n\n const partialFailedRecords =\n Array.isArray(failedRecords) && failedRecords.length > 0 ? failedRecords : null\n\n const plan = planPendingActionExecution(action, tool, partialFailedRecords)\n if (plan.kind === 'refuse') {\n const messages = await resolvePendingActionBatchMessages()\n return {\n ok: false,\n action,\n executionResult: { error: { code: plan.code, message: messages.batchNotApplicable } },\n cause: new Error(`Pending action \"${action.id}\" no longer matches its approved preview`),\n }\n }\n if (plan.droppedDuplicateRecordIds.length > 0) {\n logger.warn('Pending action input repeats previewed records; only the first entry per record runs', {\n pendingActionId: action.id,\n toolName: tool.name,\n recordIds: plan.droppedDuplicateRecordIds,\n })\n }\n const batchMessages =\n plan.notPreviewedRecordIds.length > 0 || plan.droppedDuplicateRecordIds.length > 0\n ? await resolvePendingActionBatchMessages()\n : null\n const notPreviewedFailedRecords = batchMessages\n ? toNotPreviewedFailedRecords(plan.notPreviewedRecordIds, batchMessages)\n : null\n const droppedDuplicateFailedRecords = batchMessages\n ? toDuplicateDroppedFailedRecords(plan.droppedDuplicateRecordIds, batchMessages)\n : null\n const blockedFailedRecords = mergeFailedRecords(partialFailedRecords, notPreviewedFailedRecords)\n const preExecutionFailedRecords = mergeFailedRecords(blockedFailedRecords, droppedDuplicateFailedRecords)\n\n let confirmedRow: AiPendingAction\n try {\n confirmedRow = await repo.setStatus(action.id, 'confirmed', scope, {\n expectedStatus: 'pending',\n resolvedByUserId: ctx.userId,\n now: clock,\n ...(preExecutionFailedRecords ? { failedRecords: preExecutionFailedRecords } : {}),\n })\n } catch (error) {\n if (!(error instanceof AiPendingActionStateError)) throw error\n const current = await repo.getById(action.id, scope)\n if (!current) throw error\n if (current.status === 'confirmed' || current.status === 'executing') {\n return { ok: true, action: current, executionResult: current.executionResult ?? {} }\n }\n return {\n ok: false,\n action: current,\n executionResult: current.executionResult ?? {\n error: { code: 'invalid_status', message: await resolvePendingActionAlreadyResolvedMessage() },\n },\n cause: error,\n }\n }\n const executingRow = await repo.setStatus(confirmedRow.id, 'executing', scope, { now: clock })\n\n let handlerOutput: unknown\n try {\n handlerOutput = await tool.handler(\n plan.input as never,\n toToolHandlerContext(ctx, tool, action.id, plan.expectedRecordVersions),\n )\n } catch (error) {\n const failureResult: AiPendingActionExecutionResult = {\n error: buildHandlerErrorFromThrown(error, plan.input),\n }\n const failedRow = await repo.setStatus(executingRow.id, 'failed', scope, {\n executionResult: failureResult,\n now: clock,\n })\n await emitConfirmed(emitter, {\n pendingActionId: failedRow.id,\n agentId: agent.id,\n toolName: tool.name,\n status: failedRow.status,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n userId: ctx.userId,\n resolvedByUserId: ctx.userId,\n resolvedAt: (failedRow.resolvedAt ?? clock).toISOString?.() ?? new Date(clock).toISOString(),\n executionResult: failureResult,\n })\n return {\n ok: false,\n action: failedRow,\n executionResult: failureResult,\n cause: error,\n }\n }\n\n const successResult = normalizeExecutionResult(handlerOutput)\n const handlerFailedRecords = extractHandlerFailedRecords(handlerOutput)\n const mergedFailedRecords = mergeFailedRecords(\n mergeFailedRecords(blockedFailedRecords, handlerFailedRecords),\n droppedDuplicateFailedRecords,\n )\n const confirmedExtra: Record<string, unknown> = {\n executionResult: successResult,\n now: clock,\n }\n // Always write `failedRecords` on the final transition so a batch that\n // had re-check-stale records but zero handler failures keeps the\n // original list, and a batch with handler failures merges both sets.\n // Explicit `null` collapses to \"no failures\" in the repository's\n // `normalizeFailedRecords` helper.\n confirmedExtra.failedRecords = mergedFailedRecords\n const confirmedFinal = await repo.setStatus(executingRow.id, 'confirmed', scope, confirmedExtra)\n const emitFailedRecordsPayload =\n Array.isArray(mergedFailedRecords) && mergedFailedRecords.length > 0\n ? mergedFailedRecords\n : null\n await emitConfirmed(emitter, {\n pendingActionId: confirmedFinal.id,\n agentId: agent.id,\n toolName: tool.name,\n status: confirmedFinal.status,\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n userId: ctx.userId,\n resolvedByUserId: ctx.userId,\n resolvedAt: (confirmedFinal.resolvedAt ?? clock).toISOString?.() ?? new Date(clock).toISOString(),\n executionResult: successResult,\n ...(emitFailedRecordsPayload ? { failedRecords: emitFailedRecordsPayload } : {}),\n })\n return { ok: true, action: confirmedFinal, executionResult: successResult }\n}\n\nexport const PENDING_ACTION_CONFIRMED_EVENT_ID = CONFIRMED_EVENT_ID\n"],
5
+ "mappings": "AAoBA,SAAS,iCAAiC;AAC1C,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAE1C,SAAS,4BAA4B;AAIrC,SAAS,2BAA2B;AACpC,SAAS,4CAA4C,wCAAwC;AAK7F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,cAAc;AAgD1C,MAAM,qBAAqB;AAO3B,MAAM,0BAA4C,OAAO,SAAS,YAAY;AAC5E,QAAM,qBAAqB,SAAS,SAA+C;AAAA,IACjF,YAAY;AAAA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AAI;AAAA,IACZ,kBAAkB,IAAI;AAAA,IACtB,aAAa,eAAe,cAAc,OAAO,cAAc,KAAK,IAAI,KAAK,KAAK,EAAE,YAAY;AAAA,IAChG,iBAAiB;AAAA,IACjB,GAAI,2BAA2B,EAAE,eAAe,yBAAyB,IAAI,CAAC;AAAA,EAChF,CAAC;AACD,SAAO,EAAE,IAAI,MAAM,QAAQ,gBAAgB,iBAAiB,cAAc;AAC5E;AAEO,MAAM,oCAAoC;",
6
6
  "names": []
7
7
  }
@@ -6,7 +6,12 @@ async function resolveToolFeaturesDeniedMessage(requiredFeatures) {
6
6
  features: requiredFeatures.join(", ")
7
7
  });
8
8
  }
9
+ async function resolvePendingActionAlreadyResolvedMessage() {
10
+ const { translate } = await resolveTranslations();
11
+ return translate("ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody");
12
+ }
9
13
  export {
14
+ resolvePendingActionAlreadyResolvedMessage,
10
15
  resolveToolFeaturesDeniedMessage
11
16
  };
12
17
  //# sourceMappingURL=pending-action-messages.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/ai_assistant/lib/pending-action-messages.ts"],
4
- "sourcesContent": ["import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst TOOL_FEATURES_DENIED_MESSAGE_FALLBACK = \"Caller lacks one of the tool's required features: {features}\"\n\n/**\n * Localized message for the `tool_features_denied` refusal, shared by the\n * confirm re-check and the executor so both paths answer in the caller's\n * locale. The stable `code` stays on the envelope for programmatic clients.\n */\nexport async function resolveToolFeaturesDeniedMessage(requiredFeatures: string[]): Promise<string> {\n const { translate } = await resolveTranslations()\n return translate('ai_assistant.errors.toolFeaturesDenied', TOOL_FEATURES_DENIED_MESSAGE_FALLBACK, {\n features: requiredFeatures.join(', '),\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,2BAA2B;AAEpC,MAAM,wCAAwC;AAO9C,eAAsB,iCAAiC,kBAA6C;AAClG,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,SAAO,UAAU,0CAA0C,uCAAuC;AAAA,IAChG,UAAU,iBAAiB,KAAK,IAAI;AAAA,EACtC,CAAC;AACH;",
4
+ "sourcesContent": ["import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst TOOL_FEATURES_DENIED_MESSAGE_FALLBACK = \"Caller lacks one of the tool's required features: {features}\"\n\n/**\n * Localized message for the `tool_features_denied` refusal, shared by the\n * confirm re-check and the executor so both paths answer in the caller's\n * locale. The stable `code` stays on the envelope for programmatic clients.\n */\nexport async function resolveToolFeaturesDeniedMessage(requiredFeatures: string[]): Promise<string> {\n const { translate } = await resolveTranslations()\n return translate('ai_assistant.errors.toolFeaturesDenied', TOOL_FEATURES_DENIED_MESSAGE_FALLBACK, {\n features: requiredFeatures.join(', '),\n })\n}\n\nexport async function resolvePendingActionAlreadyResolvedMessage(): Promise<string> {\n const { translate } = await resolveTranslations()\n return translate('ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody')\n}\n"],
5
+ "mappings": "AAAA,SAAS,2BAA2B;AAEpC,MAAM,wCAAwC;AAO9C,eAAsB,iCAAiC,kBAA6C;AAClG,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,SAAO,UAAU,0CAA0C,uCAAuC;AAAA,IAChG,UAAU,iBAAiB,KAAK,IAAI;AAAA,EACtC,CAAC;AACH;AAEA,eAAsB,6CAA8D;AAClF,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,SAAO,UAAU,iEAAiE;AACpF;",
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.10.1-develop.8116.1.25333cebaa",
3
+ "version": "0.10.1-develop.8123.1.acf6ca6db8",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "engines": {
@@ -103,16 +103,16 @@
103
103
  "zod-to-json-schema": "^3.25.2"
104
104
  },
105
105
  "peerDependencies": {
106
- "@open-mercato/shared": "0.10.1-develop.8116.1.25333cebaa",
107
- "@open-mercato/ui": "0.10.1-develop.8116.1.25333cebaa",
106
+ "@open-mercato/shared": "0.10.1-develop.8123.1.acf6ca6db8",
107
+ "@open-mercato/ui": "0.10.1-develop.8123.1.acf6ca6db8",
108
108
  "react": "^19.0.0",
109
109
  "react-dom": "^19.0.0",
110
110
  "zod": ">=3.23.0"
111
111
  },
112
112
  "devDependencies": {
113
- "@open-mercato/cli": "0.10.1-develop.8116.1.25333cebaa",
114
- "@open-mercato/shared": "0.10.1-develop.8116.1.25333cebaa",
115
- "@open-mercato/ui": "0.10.1-develop.8116.1.25333cebaa",
113
+ "@open-mercato/cli": "0.10.1-develop.8123.1.acf6ca6db8",
114
+ "@open-mercato/shared": "0.10.1-develop.8123.1.acf6ca6db8",
115
+ "@open-mercato/ui": "0.10.1-develop.8123.1.acf6ca6db8",
116
116
  "@types/react": "^19.2.18",
117
117
  "@types/react-dom": "^19.2.5",
118
118
  "react": "19.2.8",
@@ -0,0 +1,54 @@
1
+ import { test, expect } from '@playwright/test'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
4
+ import { createCompanyFixture, deleteEntityIfExists } from '@open-mercato/core/helpers/integration/crmFixtures'
5
+ import { getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
6
+ import { seedPendingActionInDb, deletePendingActionInDb } from './helpers/aiAssistantFixtures'
7
+
8
+ type CommentList = { items: Array<{ id: string; body: string }> }
9
+ type Confirmation = { ok?: boolean; pendingAction?: { status: string }; code?: string }
10
+
11
+ const actionsPath = '/api/ai_assistant/ai/actions'
12
+
13
+ test('TC-AI-ACTIONS-CLAIM-011: concurrent confirmation creates exactly one comment', async ({ request }) => {
14
+ const token = await getAuthToken(request, 'admin')
15
+ const { tenantId, organizationId, userId } = getTokenScope(token)
16
+ const marker = `IT exclusive approval ${randomUUID()}`
17
+ const companyId = await createCompanyFixture(request, token, marker)
18
+ let pendingActionId: string | null = null
19
+ try {
20
+ const action = await seedPendingActionInDb({
21
+ tenantId,
22
+ organizationId,
23
+ createdByUserId: userId,
24
+ agentId: 'customers.account_assistant',
25
+ toolName: 'customers.manage_record_comment',
26
+ normalizedInput: { operation: 'create', companyId, body: marker },
27
+ })
28
+ pendingActionId = action.id
29
+ const confirmations = await Promise.all(Array.from({ length: 20 }, () => apiRequest(
30
+ request, 'POST', `${actionsPath}/${action.id}/confirm`, { token, data: {} },
31
+ )))
32
+ const bodies = await Promise.all(confirmations.map((response) => readJsonSafe<Confirmation>(response)))
33
+ for (const [index, response] of confirmations.entries()) {
34
+ expect([200, 409], JSON.stringify(bodies[index])).toContain(response.status())
35
+ if (response.status() === 409) expect(bodies[index]?.code).toBe('invalid_status')
36
+ }
37
+ expect(bodies.some((body) => body?.ok === true)).toBe(true)
38
+ const replay = await apiRequest(request, 'POST', `${actionsPath}/${action.id}/confirm`, { token, data: {} })
39
+ expect(replay.status()).toBe(200)
40
+ expect(await readJsonSafe<Confirmation>(replay)).toMatchObject({ ok: true, pendingAction: { status: 'confirmed' } })
41
+ const comments = await apiRequest(request, 'GET', `/api/customers/comments?entityId=${companyId}`, { token })
42
+ expect(comments.status()).toBe(200)
43
+ const list = await readJsonSafe<CommentList>(comments)
44
+ expect(list?.items.filter((comment) => comment.body === marker)).toHaveLength(1)
45
+ } finally {
46
+ const response = await apiRequest(request, 'GET', `/api/customers/comments?entityId=${companyId}`, { token })
47
+ const comments = await readJsonSafe<CommentList>(response)
48
+ for (const comment of comments?.items ?? []) {
49
+ await deleteEntityIfExists(request, token, '/api/customers/comments', comment.id)
50
+ }
51
+ if (pendingActionId) await deletePendingActionInDb(pendingActionId)
52
+ await deleteEntityIfExists(request, token, '/api/customers/companies', companyId)
53
+ }
54
+ })
@@ -1,3 +1,4 @@
1
+ import { LockMode } from '@mikro-orm/core'
1
2
  import type { EntityManager } from '@mikro-orm/postgresql'
2
3
  import {
3
4
  findOneWithDecryption,
@@ -54,6 +55,7 @@ export interface AiPendingActionCreateResult {
54
55
  }
55
56
 
56
57
  export interface AiPendingActionSetStatusExtra {
58
+ expectedStatus?: AiPendingActionStatus
57
59
  resolvedByUserId?: string | null
58
60
  executionResult?: AiPendingActionExecutionResult | null
59
61
  failedRecords?: AiPendingActionFailedRecord[] | null
@@ -231,7 +233,7 @@ export class AiPendingActionRepository {
231
233
  organizationId: ctx.organizationId ?? null,
232
234
  ...owner,
233
235
  } as any,
234
- {},
236
+ { refresh: true },
235
237
  {
236
238
  tenantId: ctx.tenantId ?? null,
237
239
  organizationId: ctx.organizationId ?? null,
@@ -295,7 +297,7 @@ export class AiPendingActionRepository {
295
297
  organizationId: ctx.organizationId ?? null,
296
298
  ...owner,
297
299
  } as any,
298
- {},
300
+ { lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true },
299
301
  {
300
302
  tenantId: ctx.tenantId ?? null,
301
303
  organizationId: ctx.organizationId ?? null,
@@ -305,6 +307,9 @@ export class AiPendingActionRepository {
305
307
  if (!existing) {
306
308
  throw new Error(`AiPendingAction not found: ${id}`)
307
309
  }
310
+ if (extra?.expectedStatus && existing.status !== extra.expectedStatus) {
311
+ throw new AiPendingActionStateError(existing.status, nextStatus)
312
+ }
308
313
  if (existing.status === nextStatus) {
309
314
  return existing
310
315
  }
@@ -1,3 +1,4 @@
1
+ import { LockMode } from '@mikro-orm/core'
1
2
  import { AiPendingActionRepository } from '../AiPendingActionRepository'
2
3
  import { AiPendingAction } from '../../entities'
3
4
  import {
@@ -175,6 +176,23 @@ function baseInput(overrides: Partial<any> = {}) {
175
176
  }
176
177
 
177
178
  describe('AiPendingActionRepository', () => {
179
+ it('rejects a second expected-pending claim rather than treating confirmed as a successful claim', async () => {
180
+ const em = mockEm()
181
+ const repo = new AiPendingActionRepository(em)
182
+ const ctx = { tenantId: tenantAlpha, organizationId: 'org-a', userId: userOne }
183
+ const { row } = await repo.create(baseInput(), ctx)
184
+ const claim = { expectedStatus: 'pending' as const, resolvedByUserId: userOne }
185
+ const findOne = jest.spyOn(em, 'findOne')
186
+ await repo.setStatus(row.id, 'confirmed', ctx, claim)
187
+ expect(findOne).toHaveBeenCalledWith(
188
+ AiPendingAction,
189
+ expect.objectContaining({ id: row.id, tenantId: tenantAlpha, organizationId: 'org-a', createdByUserId: userOne }),
190
+ expect.objectContaining({ lockMode: LockMode.PESSIMISTIC_WRITE, refresh: true }),
191
+ )
192
+ await expect(repo.setStatus(row.id, 'confirmed', ctx, claim)).rejects.toBeInstanceOf(AiPendingActionStateError)
193
+ expect((await repo.getById(row.id, ctx))?.status).toBe('confirmed')
194
+ })
195
+
178
196
  it('creates a row in status=pending with TTL-derived expiresAt and empty attachmentIds default', async () => {
179
197
  const em = mockEm()
180
198
  const repo = new AiPendingActionRepository(em)
@@ -10,6 +10,7 @@ import type { AiToolDefinition } from '../types'
10
10
  import type { AiPendingAction } from '../../data/entities'
11
11
  import { AiPendingActionRepository } from '../../data/repositories/AiPendingActionRepository'
12
12
  import { registerModules } from '@open-mercato/shared/lib/modules/registry'
13
+ import { AiPendingActionStateError } from '../pending-action-types'
13
14
  import plTranslations from '../../i18n/pl.json'
14
15
 
15
16
  const requestHeaders = { acceptLanguage: '' }
@@ -79,6 +80,9 @@ function makeRepoStub(initialRow: AiPendingAction) {
79
80
  let row = { ...initialRow } as AiPendingAction & Record<string, unknown>
80
81
  const setStatus = jest.fn(
81
82
  async (_id: string, nextStatus: string, _scope: unknown, extra?: Record<string, unknown>) => {
83
+ if (extra?.expectedStatus && row.status !== extra.expectedStatus) {
84
+ throw new AiPendingActionStateError(row.status, nextStatus as AiPendingAction['status'])
85
+ }
82
86
  row = {
83
87
  ...row,
84
88
  status: nextStatus as never,
@@ -100,6 +104,7 @@ function makeRepoStub(initialRow: AiPendingAction) {
100
104
  )
101
105
  return {
102
106
  setStatus,
107
+ getById: jest.fn(async () => row),
103
108
  get current() {
104
109
  return row
105
110
  },
@@ -124,6 +129,56 @@ function makeCtx() {
124
129
  }
125
130
 
126
131
  describe('executePendingActionConfirm', () => {
132
+ it('executes one handler and emits one event for concurrent confirmations of detached pending snapshots', async () => {
133
+ const action = makeAction()
134
+ const repo = makeRepoStub(action)
135
+ const emitEvent = jest.fn().mockResolvedValue(undefined)
136
+ const handler = jest.fn(async () => ({ recordId: 'p-1' }))
137
+ const results = await Promise.all(Array.from({ length: 20 }, () => executePendingActionConfirm({
138
+ action: { ...action },
139
+ agent: makeAgent(),
140
+ tool: makeTool({ handler }),
141
+ ctx: makeCtx(),
142
+ repo: repo as unknown as AiPendingActionRepository,
143
+ emitEvent,
144
+ })))
145
+ expect(handler).toHaveBeenCalledTimes(1)
146
+ expect(emitEvent).toHaveBeenCalledTimes(1)
147
+ expect(results.every((result) => result.ok)).toBe(true)
148
+ expect(repo.current.status).toBe('confirmed')
149
+ expect(repo.current.executionResult).toEqual({ recordId: 'p-1' })
150
+ })
151
+
152
+ it.each(['cancelled', 'expired', 'failed'] as const)('localizes a lost claim to %s without invoking a handler or emitting', async (status) => {
153
+ registerModules([
154
+ { id: 'ai_assistant', translations: { pl: plTranslations } },
155
+ ] as unknown as Parameters<typeof registerModules>[0])
156
+ requestHeaders.acceptLanguage = 'pl'
157
+ try {
158
+ const repo = makeRepoStub(makeAction({ status }))
159
+ const handler = jest.fn()
160
+ const emitEvent = jest.fn()
161
+ const result = await executePendingActionConfirm({
162
+ action: makeAction(),
163
+ agent: makeAgent(),
164
+ tool: makeTool({ handler }),
165
+ ctx: makeCtx(),
166
+ repo: repo as unknown as AiPendingActionRepository,
167
+ emitEvent,
168
+ })
169
+ expect(result.ok).toBe(false)
170
+ expect(result.action.status).toBe(status)
171
+ expect(result.executionResult.error).toEqual({
172
+ code: 'invalid_status',
173
+ message: plTranslations['ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody'],
174
+ })
175
+ expect(handler).not.toHaveBeenCalled()
176
+ expect(emitEvent).not.toHaveBeenCalled()
177
+ } finally {
178
+ requestHeaders.acceptLanguage = ''
179
+ }
180
+ })
181
+
127
182
  it('transitions pending → confirmed → executing → confirmed on handler success and emits typed ai.action.confirmed', async () => {
128
183
  const repo = makeRepoStub(makeAction())
129
184
  const emitEvent = jest.fn().mockResolvedValue(undefined)
@@ -18,6 +18,7 @@
18
18
  * The handler's own transaction boundary (typically a command) is the
19
19
  * unit of atomicity for the underlying data change.
20
20
  */
21
+ import { AiPendingActionStateError } from './pending-action-types'
21
22
  import { createLogger } from '@open-mercato/shared/lib/logger'
22
23
  import { AiPendingActionRepository } from '../data/repositories/AiPendingActionRepository'
23
24
  import type { AiPendingAction } from '../data/entities'
@@ -26,7 +27,7 @@ import type { AiActionConfirmedPayload } from '../events'
26
27
  import type { AiAgentDefinition } from './ai-agent-definition'
27
28
  import type { AiToolDefinition, McpToolContext } from './types'
28
29
  import { hasRequiredFeatures } from './auth'
29
- import { resolveToolFeaturesDeniedMessage } from './pending-action-messages'
30
+ import { resolvePendingActionAlreadyResolvedMessage, resolveToolFeaturesDeniedMessage } from './pending-action-messages'
30
31
  import type {
31
32
  AiPendingActionExecutionResult,
32
33
  AiPendingActionFailedRecord,
@@ -411,11 +412,30 @@ export async function executePendingActionConfirm(
411
412
  const blockedFailedRecords = mergeFailedRecords(partialFailedRecords, notPreviewedFailedRecords)
412
413
  const preExecutionFailedRecords = mergeFailedRecords(blockedFailedRecords, droppedDuplicateFailedRecords)
413
414
 
414
- const confirmedRow = await repo.setStatus(action.id, 'confirmed', scope, {
415
- resolvedByUserId: ctx.userId,
416
- now: clock,
417
- ...(preExecutionFailedRecords ? { failedRecords: preExecutionFailedRecords } : {}),
418
- })
415
+ let confirmedRow: AiPendingAction
416
+ try {
417
+ confirmedRow = await repo.setStatus(action.id, 'confirmed', scope, {
418
+ expectedStatus: 'pending',
419
+ resolvedByUserId: ctx.userId,
420
+ now: clock,
421
+ ...(preExecutionFailedRecords ? { failedRecords: preExecutionFailedRecords } : {}),
422
+ })
423
+ } catch (error) {
424
+ if (!(error instanceof AiPendingActionStateError)) throw error
425
+ const current = await repo.getById(action.id, scope)
426
+ if (!current) throw error
427
+ if (current.status === 'confirmed' || current.status === 'executing') {
428
+ return { ok: true, action: current, executionResult: current.executionResult ?? {} }
429
+ }
430
+ return {
431
+ ok: false,
432
+ action: current,
433
+ executionResult: current.executionResult ?? {
434
+ error: { code: 'invalid_status', message: await resolvePendingActionAlreadyResolvedMessage() },
435
+ },
436
+ cause: error,
437
+ }
438
+ }
419
439
  const executingRow = await repo.setStatus(confirmedRow.id, 'executing', scope, { now: clock })
420
440
 
421
441
  let handlerOutput: unknown
@@ -13,3 +13,8 @@ export async function resolveToolFeaturesDeniedMessage(requiredFeatures: string[
13
13
  features: requiredFeatures.join(', '),
14
14
  })
15
15
  }
16
+
17
+ export async function resolvePendingActionAlreadyResolvedMessage(): Promise<string> {
18
+ const { translate } = await resolveTranslations()
19
+ return translate('ai_assistant.chat.mutation_cards.confirmation.invalidStatusBody')
20
+ }