@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8567.1.a167594505

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/api_keys/di.js +6 -2
  3. package/dist/modules/api_keys/di.js.map +2 -2
  4. package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
  5. package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
  6. package/dist/modules/audit_logs/di.js +2 -1
  7. package/dist/modules/audit_logs/di.js.map +2 -2
  8. package/dist/modules/audit_logs/services/actionLogService.js +65 -1
  9. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  10. package/dist/modules/auth/cli.js +1 -0
  11. package/dist/modules/auth/cli.js.map +2 -2
  12. package/dist/modules/auth/commands/users.js +10 -2
  13. package/dist/modules/auth/commands/users.js.map +2 -2
  14. package/dist/modules/auth/lib/setup-app.js +19 -5
  15. package/dist/modules/auth/lib/setup-app.js.map +2 -2
  16. package/dist/modules/configs/cli.js +26 -29
  17. package/dist/modules/configs/cli.js.map +2 -2
  18. package/dist/modules/configs/di.js +3 -1
  19. package/dist/modules/configs/di.js.map +2 -2
  20. package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
  21. package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
  22. package/dist/modules/configs/lib/instance-defaults.js +204 -0
  23. package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
  24. package/dist/modules/configs/lib/module-config-service.js +115 -1
  25. package/dist/modules/configs/lib/module-config-service.js.map +2 -2
  26. package/dist/modules/entities/api/definitions.batch.js +55 -25
  27. package/dist/modules/entities/api/definitions.batch.js.map +2 -2
  28. package/dist/modules/entities/api/definitions.js +35 -8
  29. package/dist/modules/entities/api/definitions.js.map +2 -2
  30. package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
  31. package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
  32. package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
  33. package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
  34. package/dist/modules/notifications/setup.js +10 -0
  35. package/dist/modules/notifications/setup.js.map +2 -2
  36. package/dist/modules/translations/components/TranslationManager.js +47 -10
  37. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  38. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
  39. package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
  40. package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
  41. package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
  42. package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
  43. package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
  44. package/dist/modules/workflows/api/instances/route.js +1 -1
  45. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  46. package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
  47. package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
  48. package/dist/modules/workflows/di.js +3 -1
  49. package/dist/modules/workflows/di.js.map +2 -2
  50. package/dist/modules/workflows/lib/activity-executor.js +35 -7
  51. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  52. package/dist/modules/workflows/lib/condition-handler.js +1 -1
  53. package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
  54. package/dist/modules/workflows/lib/error-handler.js +1 -1
  55. package/dist/modules/workflows/lib/error-handler.js.map +2 -2
  56. package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
  57. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  58. package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
  59. package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
  60. package/dist/modules/workflows/lib/named-rules.js +42 -0
  61. package/dist/modules/workflows/lib/named-rules.js.map +7 -0
  62. package/dist/modules/workflows/lib/owned-definition.js +2 -0
  63. package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
  64. package/dist/modules/workflows/lib/parallel-handler.js +1 -1
  65. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  66. package/dist/modules/workflows/lib/signal-handler.js +1 -0
  67. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  68. package/dist/modules/workflows/lib/start-validator.js +87 -85
  69. package/dist/modules/workflows/lib/start-validator.js.map +2 -2
  70. package/dist/modules/workflows/lib/step-handler.js +1 -1
  71. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  72. package/dist/modules/workflows/lib/task-handler.js +1 -0
  73. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  74. package/dist/modules/workflows/lib/timer-handler.js +1 -0
  75. package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
  76. package/dist/modules/workflows/lib/transition-handler.js +48 -166
  77. package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
  78. package/dist/modules/workflows/lib/workflow-executor.js +3 -2
  79. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  80. package/package.json +8 -8
  81. package/src/modules/api_keys/di.ts +7 -2
  82. package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
  83. package/src/modules/audit_logs/di.ts +1 -0
  84. package/src/modules/audit_logs/services/actionLogService.ts +132 -1
  85. package/src/modules/auth/cli.ts +1 -0
  86. package/src/modules/auth/commands/users.ts +10 -2
  87. package/src/modules/auth/i18n/de.json +2 -0
  88. package/src/modules/auth/i18n/en.json +2 -0
  89. package/src/modules/auth/i18n/es.json +2 -0
  90. package/src/modules/auth/i18n/ko.json +2 -0
  91. package/src/modules/auth/i18n/pl.json +2 -0
  92. package/src/modules/auth/lib/setup-app.ts +30 -7
  93. package/src/modules/configs/cli.ts +39 -37
  94. package/src/modules/configs/di.ts +2 -0
  95. package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
  96. package/src/modules/configs/lib/instance-defaults.ts +262 -0
  97. package/src/modules/configs/lib/module-config-service.ts +156 -0
  98. package/src/modules/entities/api/definitions.batch.ts +65 -27
  99. package/src/modules/entities/api/definitions.ts +40 -11
  100. package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
  101. package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
  102. package/src/modules/notifications/setup.ts +11 -0
  103. package/src/modules/translations/components/TranslationManager.tsx +49 -10
  104. package/src/modules/translations/i18n/de.json +1 -0
  105. package/src/modules/translations/i18n/en.json +1 -0
  106. package/src/modules/translations/i18n/es.json +1 -0
  107. package/src/modules/translations/i18n/ko.json +1 -0
  108. package/src/modules/translations/i18n/pl.json +1 -0
  109. package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
  110. package/src/modules/wms/i18n/de.json +1 -0
  111. package/src/modules/wms/i18n/en.json +1 -0
  112. package/src/modules/wms/i18n/es.json +1 -0
  113. package/src/modules/wms/i18n/ko.json +1 -0
  114. package/src/modules/wms/i18n/pl.json +1 -0
  115. package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
  116. package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
  117. package/src/modules/workflows/api/instances/route.ts +1 -1
  118. package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
  119. package/src/modules/workflows/di.ts +2 -0
  120. package/src/modules/workflows/lib/activity-executor.ts +48 -30
  121. package/src/modules/workflows/lib/condition-handler.ts +1 -1
  122. package/src/modules/workflows/lib/error-handler.ts +1 -1
  123. package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
  124. package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
  125. package/src/modules/workflows/lib/named-rules.ts +54 -0
  126. package/src/modules/workflows/lib/owned-definition.ts +4 -1
  127. package/src/modules/workflows/lib/parallel-handler.ts +1 -1
  128. package/src/modules/workflows/lib/signal-handler.ts +1 -0
  129. package/src/modules/workflows/lib/start-validator.ts +96 -94
  130. package/src/modules/workflows/lib/step-handler.ts +1 -1
  131. package/src/modules/workflows/lib/task-handler.ts +1 -0
  132. package/src/modules/workflows/lib/timer-handler.ts +1 -0
  133. package/src/modules/workflows/lib/transition-handler.ts +74 -238
  134. package/src/modules/workflows/lib/workflow-executor.ts +7 -4
@@ -0,0 +1,42 @@
1
+ import { reportError } from "@open-mercato/telemetry";
2
+ import { getRequestScopeContainer, runInRequestScope } from "@open-mercato/shared/lib/di/request-scope";
3
+ import { isBusinessRulesModuleEnabled } from "./optional-modules.js";
4
+ function resolveNamedRuleRunner(container) {
5
+ const runner = container?.resolve("ruleEngine", { allowUnregistered: true });
6
+ return typeof runner?.executeRuleByRuleId === "function" ? runner : void 0;
7
+ }
8
+ function createNamedWorkflowRuleScope(container) {
9
+ let ownedContainer;
10
+ let resolved;
11
+ async function resolve() {
12
+ const activeContainer = container === void 0 ? getRequestScopeContainer() : container;
13
+ if (activeContainer || container !== void 0) return resolveNamedRuleRunner(activeContainer);
14
+ if (!isBusinessRulesModuleEnabled()) return void 0;
15
+ const { createRequestContainer } = await import("@open-mercato/shared/lib/di/container");
16
+ ownedContainer = await runInRequestScope(createRequestContainer);
17
+ return resolveNamedRuleRunner(ownedContainer);
18
+ }
19
+ return {
20
+ resolve: () => resolved ??= resolve(),
21
+ async dispose() {
22
+ try {
23
+ await ownedContainer?.dispose();
24
+ } catch (error) {
25
+ reportError(error, { module: "workflows", code: "workflows.named_rule_scope_disposal_failed" });
26
+ }
27
+ }
28
+ };
29
+ }
30
+ async function withNamedWorkflowRuleRunner(container, useRunner) {
31
+ const scope = createNamedWorkflowRuleScope(container);
32
+ try {
33
+ return await useRunner(await scope.resolve());
34
+ } finally {
35
+ await scope.dispose();
36
+ }
37
+ }
38
+ export {
39
+ createNamedWorkflowRuleScope,
40
+ withNamedWorkflowRuleRunner
41
+ };
42
+ //# sourceMappingURL=named-rules.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/workflows/lib/named-rules.ts"],
4
+ "sourcesContent": ["import type { executeRuleByRuleId } from '@open-mercato/core/modules/business_rules'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport { reportError } from '@open-mercato/telemetry'\nimport { getRequestScopeContainer, runInRequestScope } from '@open-mercato/shared/lib/di/request-scope'\nimport { isBusinessRulesModuleEnabled } from './optional-modules'\n\nexport type WorkflowRuleContainer = {\n resolve: <T>(name: string, options?: { allowUnregistered?: boolean }) => T\n}\n\ntype NamedWorkflowRuleRunner = { executeRuleByRuleId: typeof executeRuleByRuleId }\n\nfunction resolveNamedRuleRunner(container: WorkflowRuleContainer | null): NamedWorkflowRuleRunner | undefined {\n const runner = container?.resolve<NamedWorkflowRuleRunner | undefined>('ruleEngine', { allowUnregistered: true })\n return typeof runner?.executeRuleByRuleId === 'function' ? runner : undefined\n}\n\nexport function createNamedWorkflowRuleScope(container: WorkflowRuleContainer | null | undefined) {\n let ownedContainer: AppContainer | undefined\n let resolved: Promise<NamedWorkflowRuleRunner | undefined> | undefined\n\n async function resolve() {\n const activeContainer = container === undefined ? getRequestScopeContainer() : container\n if (activeContainer || container !== undefined) return resolveNamedRuleRunner(activeContainer)\n if (!isBusinessRulesModuleEnabled()) return undefined\n\n const { createRequestContainer } = await import('@open-mercato/shared/lib/di/container')\n ownedContainer = await runInRequestScope(createRequestContainer)\n return resolveNamedRuleRunner(ownedContainer)\n }\n\n return {\n resolve: () => resolved ??= resolve(),\n async dispose() {\n try {\n await ownedContainer?.dispose()\n } catch (error) {\n reportError(error, { module: 'workflows', code: 'workflows.named_rule_scope_disposal_failed' })\n }\n },\n }\n}\n\nexport async function withNamedWorkflowRuleRunner<Result>(\n container: WorkflowRuleContainer | null | undefined,\n useRunner: (runner: NamedWorkflowRuleRunner | undefined) => Promise<Result>,\n): Promise<Result> {\n const scope = createNamedWorkflowRuleScope(container)\n try {\n return await useRunner(await scope.resolve())\n } finally {\n await scope.dispose()\n }\n}\n"],
5
+ "mappings": "AAEA,SAAS,mBAAmB;AAC5B,SAAS,0BAA0B,yBAAyB;AAC5D,SAAS,oCAAoC;AAQ7C,SAAS,uBAAuB,WAA8E;AAC5G,QAAM,SAAS,WAAW,QAA6C,cAAc,EAAE,mBAAmB,KAAK,CAAC;AAChH,SAAO,OAAO,QAAQ,wBAAwB,aAAa,SAAS;AACtE;AAEO,SAAS,6BAA6B,WAAqD;AAChG,MAAI;AACJ,MAAI;AAEJ,iBAAe,UAAU;AACvB,UAAM,kBAAkB,cAAc,SAAY,yBAAyB,IAAI;AAC/E,QAAI,mBAAmB,cAAc,OAAW,QAAO,uBAAuB,eAAe;AAC7F,QAAI,CAAC,6BAA6B,EAAG,QAAO;AAE5C,UAAM,EAAE,uBAAuB,IAAI,MAAM,OAAO,uCAAuC;AACvF,qBAAiB,MAAM,kBAAkB,sBAAsB;AAC/D,WAAO,uBAAuB,cAAc;AAAA,EAC9C;AAEA,SAAO;AAAA,IACL,SAAS,MAAM,aAAa,QAAQ;AAAA,IACpC,MAAM,UAAU;AACd,UAAI;AACF,cAAM,gBAAgB,QAAQ;AAAA,MAChC,SAAS,OAAO;AACd,oBAAY,OAAO,EAAE,QAAQ,aAAa,MAAM,6CAA6C,CAAC;AAAA,MAChG;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAsB,4BACpB,WACA,WACiB;AACjB,QAAM,QAAQ,6BAA6B,SAAS;AACpD,MAAI;AACF,WAAO,MAAM,UAAU,MAAM,MAAM,QAAQ,CAAC;AAAA,EAC9C,UAAE;AACA,UAAM,MAAM,QAAQ;AAAA,EACtB;AACF;",
6
+ "names": []
7
+ }
@@ -4,12 +4,14 @@ import {
4
4
  } from "../data/entities.js";
5
5
  import { normalizeGrantedFeatures, syncWorkflowDefinitionPrincipal } from "./definition-grant.js";
6
6
  import { invalidateTriggerCache } from "./event-trigger-service.js";
7
+ import { createWorkflowExampleAuthoring } from "./example-definition-authoring.js";
7
8
  function ownedBy(definition, ownerModule, ownerId) {
8
9
  const generatedBy = definition.metadata?.generatedBy;
9
10
  return !!generatedBy && generatedBy.module === ownerModule && generatedBy.ownerId === ownerId;
10
11
  }
11
12
  function createWorkflowDefinitionAuthoring(container) {
12
13
  return {
14
+ ...createWorkflowExampleAuthoring(container),
13
15
  async findOwnedDefinition(em, params) {
14
16
  return em.findOne(
15
17
  WorkflowDefinition,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/workflows/lib/owned-definition.ts"],
4
- "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport {\n WorkflowDefinition,\n type WorkflowDefinitionData,\n type WorkflowMetadata,\n} from '../data/entities'\nimport { normalizeGrantedFeatures, syncWorkflowDefinitionPrincipal } from './definition-grant'\nimport { invalidateTriggerCache } from './event-trigger-service'\n\n/**\n * Create-or-update of a workflow definition that ANOTHER module authors and owns.\n *\n * The point of this service is that there is exactly one workflow engine and one\n * kind of workflow definition. When a module offers a simplified way to express a\n * process \u2014 \"run this agent every morning\" \u2014 the right answer is to generate a\n * real definition here, not to build a parallel executor for the simple case. The\n * generated row is an ordinary `WorkflowDefinition`: it shows up in the Studio,\n * it can be opened and extended by hand, and it runs through the same engine with\n * the same retry, wait, signal and cancellation semantics as anything else.\n *\n * Ownership is recorded in `metadata.generatedBy` and re-checked on every write,\n * so this can never silently take over a workflow a person authored or one\n * belonging to a different owner.\n *\n * Execution identity comes with it: `grantedFeatures` is applied through the same\n * `syncWorkflowDefinitionPrincipal` the definitions API uses, so a generated\n * workflow runs as its own least-privilege principal exactly like a hand-authored\n * one. AUTHORIZING that grant is the caller's job \u2014 this service is a write\n * primitive, not a permission boundary.\n */\n\nexport type OwnedWorkflowDefinitionInput = {\n ownerModule: string\n ownerId: string\n workflowId: string\n workflowName: string\n description?: string | null\n definition: WorkflowDefinitionData\n metadata?: Omit<WorkflowMetadata, 'generatedBy'> | null\n grantedFeatures?: string[] | null\n enabled?: boolean\n tenantId: string\n organizationId: string\n actorUserId?: string | null\n}\n\nexport type OwnedWorkflowDefinitionResult =\n | { ok: true; definition: WorkflowDefinition; created: boolean }\n | { ok: false; reason: 'owned_by_other'; definition: WorkflowDefinition }\n\nexport interface WorkflowDefinitionAuthoring {\n upsertOwnedDefinition(\n em: EntityManager,\n input: OwnedWorkflowDefinitionInput,\n ): Promise<OwnedWorkflowDefinitionResult>\n findOwnedDefinition(\n em: EntityManager,\n params: { workflowId: string; tenantId: string; organizationId: string },\n ): Promise<WorkflowDefinition | null>\n /** Batch form for a list page: one query for a page of workflow ids. */\n findDefinitionsByWorkflowIds(\n em: EntityManager,\n params: { workflowIds: string[]; tenantId: string; organizationId: string },\n ): Promise<WorkflowDefinition[]>\n deleteOwnedDefinition(\n em: EntityManager,\n params: { workflowId: string; ownerModule: string; ownerId: string; tenantId: string; organizationId: string },\n ): Promise<boolean>\n}\n\nfunction ownedBy(definition: WorkflowDefinition, ownerModule: string, ownerId: string): boolean {\n const generatedBy = definition.metadata?.generatedBy\n return !!generatedBy && generatedBy.module === ownerModule && generatedBy.ownerId === ownerId\n}\n\nexport function createWorkflowDefinitionAuthoring(container: AwilixContainer): WorkflowDefinitionAuthoring {\n return {\n async findOwnedDefinition(em, params) {\n return em.findOne(\n WorkflowDefinition,\n {\n workflowId: params.workflowId,\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n deletedAt: null,\n },\n { orderBy: { version: 'DESC' } },\n )\n },\n\n async findDefinitionsByWorkflowIds(em, params) {\n if (params.workflowIds.length === 0) return []\n return em.find(\n WorkflowDefinition,\n {\n workflowId: { $in: params.workflowIds },\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n deletedAt: null,\n },\n { orderBy: { version: 'DESC' } },\n )\n },\n\n async upsertOwnedDefinition(em, input) {\n const grantedFeatures = normalizeGrantedFeatures(input.grantedFeatures)\n const existing = await em.findOne(\n WorkflowDefinition,\n {\n workflowId: input.workflowId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { orderBy: { version: 'DESC' } },\n )\n\n // A row that exists but belongs to someone else \u2014 a person's own workflow,\n // or another owner's \u2014 is never overwritten. The caller decides what to do\n // about it; silently replacing a hand-authored graph would be the worst\n // possible failure mode of a convenience feature.\n if (existing && !ownedBy(existing, input.ownerModule, input.ownerId)) {\n return { ok: false, reason: 'owned_by_other', definition: existing }\n }\n\n const metadata: WorkflowMetadata = {\n ...(input.metadata ?? {}),\n generatedBy: { module: input.ownerModule, ownerId: input.ownerId },\n }\n\n const definition =\n existing ??\n em.create(WorkflowDefinition, {\n // The PK is minted up front (MikroORM does not generate UUIDs\n // client-side) so the execution principal \u2014 whose identity key is the\n // definition id \u2014 can be provisioned BEFORE the row claiming the grant\n // is persisted.\n id: randomUUID(),\n workflowId: input.workflowId,\n workflowName: input.workflowName,\n version: 1,\n definition: input.definition,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n createdBy: input.actorUserId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n definition.workflowName = input.workflowName\n definition.description = input.description ?? null\n definition.definition = input.definition\n definition.metadata = metadata\n definition.enabled = input.enabled ?? true\n definition.grantedFeatures = grantedFeatures.length ? grantedFeatures : null\n definition.updatedBy = input.actorUserId ?? definition.updatedBy ?? null\n definition.updatedAt = new Date()\n\n await syncWorkflowDefinitionPrincipal(container, definition)\n em.persist(definition)\n await em.flush()\n\n // Embedded triggers on a freshly written definition must be visible to the\n // wildcard event subscriber immediately.\n invalidateTriggerCache(input.tenantId, input.organizationId)\n\n return { ok: true, definition, created: !existing }\n },\n\n async deleteOwnedDefinition(em, params) {\n const existing = await em.findOne(WorkflowDefinition, {\n workflowId: params.workflowId,\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n deletedAt: null,\n })\n if (!existing) return false\n if (!ownedBy(existing, params.ownerModule, params.ownerId)) return false\n existing.deletedAt = new Date()\n em.persist(existing)\n await em.flush()\n invalidateTriggerCache(params.tenantId, params.organizationId)\n return true\n },\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;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AAO;AACnE,eAAS,YAAY,oBAAI,KAAK;AAC9B,SAAG,QAAQ,QAAQ;AACnB,YAAM,GAAG,MAAM;AACf,6BAAuB,OAAO,UAAU,OAAO,cAAc;AAC7D,aAAO;AAAA,IACT;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport {\n WorkflowDefinition,\n type WorkflowDefinitionData,\n type WorkflowMetadata,\n} from '../data/entities'\nimport { normalizeGrantedFeatures, syncWorkflowDefinitionPrincipal } from './definition-grant'\nimport { invalidateTriggerCache } from './event-trigger-service'\nimport { createWorkflowExampleAuthoring, type WorkflowExampleAuthoring } from './example-definition-authoring'\n\n/**\n * Create-or-update of a workflow definition that ANOTHER module authors and owns.\n *\n * The point of this service is that there is exactly one workflow engine and one\n * kind of workflow definition. When a module offers a simplified way to express a\n * process \u2014 \"run this agent every morning\" \u2014 the right answer is to generate a\n * real definition here, not to build a parallel executor for the simple case. The\n * generated row is an ordinary `WorkflowDefinition`: it shows up in the Studio,\n * it can be opened and extended by hand, and it runs through the same engine with\n * the same retry, wait, signal and cancellation semantics as anything else.\n *\n * Ownership is recorded in `metadata.generatedBy` and re-checked on every write,\n * so this can never silently take over a workflow a person authored or one\n * belonging to a different owner.\n *\n * Execution identity comes with it: `grantedFeatures` is applied through the same\n * `syncWorkflowDefinitionPrincipal` the definitions API uses, so a generated\n * workflow runs as its own least-privilege principal exactly like a hand-authored\n * one. AUTHORIZING that grant is the caller's job \u2014 this service is a write\n * primitive, not a permission boundary.\n */\n\nexport type OwnedWorkflowDefinitionInput = {\n ownerModule: string\n ownerId: string\n workflowId: string\n workflowName: string\n description?: string | null\n definition: WorkflowDefinitionData\n metadata?: Omit<WorkflowMetadata, 'generatedBy'> | null\n grantedFeatures?: string[] | null\n enabled?: boolean\n tenantId: string\n organizationId: string\n actorUserId?: string | null\n}\n\nexport type OwnedWorkflowDefinitionResult =\n | { ok: true; definition: WorkflowDefinition; created: boolean }\n | { ok: false; reason: 'owned_by_other'; definition: WorkflowDefinition }\n\nexport interface WorkflowDefinitionAuthoring extends Partial<WorkflowExampleAuthoring> {\n upsertOwnedDefinition(\n em: EntityManager,\n input: OwnedWorkflowDefinitionInput,\n ): Promise<OwnedWorkflowDefinitionResult>\n findOwnedDefinition(\n em: EntityManager,\n params: { workflowId: string; tenantId: string; organizationId: string },\n ): Promise<WorkflowDefinition | null>\n /** Batch form for a list page: one query for a page of workflow ids. */\n findDefinitionsByWorkflowIds(\n em: EntityManager,\n params: { workflowIds: string[]; tenantId: string; organizationId: string },\n ): Promise<WorkflowDefinition[]>\n deleteOwnedDefinition(\n em: EntityManager,\n params: { workflowId: string; ownerModule: string; ownerId: string; tenantId: string; organizationId: string },\n ): Promise<boolean>\n}\n\nfunction ownedBy(definition: WorkflowDefinition, ownerModule: string, ownerId: string): boolean {\n const generatedBy = definition.metadata?.generatedBy\n return !!generatedBy && generatedBy.module === ownerModule && generatedBy.ownerId === ownerId\n}\n\nexport function createWorkflowDefinitionAuthoring(container: AwilixContainer): WorkflowDefinitionAuthoring {\n return {\n ...createWorkflowExampleAuthoring(container),\n\n async findOwnedDefinition(em, params) {\n return em.findOne(\n WorkflowDefinition,\n {\n workflowId: params.workflowId,\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n deletedAt: null,\n },\n { orderBy: { version: 'DESC' } },\n )\n },\n\n async findDefinitionsByWorkflowIds(em, params) {\n if (params.workflowIds.length === 0) return []\n return em.find(\n WorkflowDefinition,\n {\n workflowId: { $in: params.workflowIds },\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n deletedAt: null,\n },\n { orderBy: { version: 'DESC' } },\n )\n },\n\n async upsertOwnedDefinition(em, input) {\n const grantedFeatures = normalizeGrantedFeatures(input.grantedFeatures)\n const existing = await em.findOne(\n WorkflowDefinition,\n {\n workflowId: input.workflowId,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n deletedAt: null,\n },\n { orderBy: { version: 'DESC' } },\n )\n\n // A row that exists but belongs to someone else \u2014 a person's own workflow,\n // or another owner's \u2014 is never overwritten. The caller decides what to do\n // about it; silently replacing a hand-authored graph would be the worst\n // possible failure mode of a convenience feature.\n if (existing && !ownedBy(existing, input.ownerModule, input.ownerId)) {\n return { ok: false, reason: 'owned_by_other', definition: existing }\n }\n\n const metadata: WorkflowMetadata = {\n ...(input.metadata ?? {}),\n generatedBy: { module: input.ownerModule, ownerId: input.ownerId },\n }\n\n const definition =\n existing ??\n em.create(WorkflowDefinition, {\n // The PK is minted up front (MikroORM does not generate UUIDs\n // client-side) so the execution principal \u2014 whose identity key is the\n // definition id \u2014 can be provisioned BEFORE the row claiming the grant\n // is persisted.\n id: randomUUID(),\n workflowId: input.workflowId,\n workflowName: input.workflowName,\n version: 1,\n definition: input.definition,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n createdBy: input.actorUserId ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n definition.workflowName = input.workflowName\n definition.description = input.description ?? null\n definition.definition = input.definition\n definition.metadata = metadata\n definition.enabled = input.enabled ?? true\n definition.grantedFeatures = grantedFeatures.length ? grantedFeatures : null\n definition.updatedBy = input.actorUserId ?? definition.updatedBy ?? null\n definition.updatedAt = new Date()\n\n await syncWorkflowDefinitionPrincipal(container, definition)\n em.persist(definition)\n await em.flush()\n\n // Embedded triggers on a freshly written definition must be visible to the\n // wildcard event subscriber immediately.\n invalidateTriggerCache(input.tenantId, input.organizationId)\n\n return { ok: true, definition, created: !existing }\n },\n\n async deleteOwnedDefinition(em, params) {\n const existing = await em.findOne(WorkflowDefinition, {\n workflowId: params.workflowId,\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n deletedAt: null,\n })\n if (!existing) return false\n if (!ownedBy(existing, params.ownerModule, params.ownerId)) return false\n existing.deletedAt = new Date()\n em.persist(existing)\n await em.flush()\n invalidateTriggerCache(params.tenantId, params.organizationId)\n return true\n },\n }\n}\n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ACD,UAAI,CAAC,SAAU,QAAO;AACtB,UAAI,CAAC,QAAQ,UAAU,OAAO,aAAa,OAAO,OAAO,EAAG,QAAO;AACnE,eAAS,YAAY,oBAAI,KAAK;AAC9B,SAAG,QAAQ,QAAQ;AACnB,YAAM,GAAG,MAAM;AACf,6BAAuB,OAAO,UAAU,OAAO,cAAc;AAC7D,aAAO;AAAA,IACT;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -277,7 +277,7 @@ async function advanceOneBranch(em, container, instance, definition, branch, con
277
277
  const transitionHandler = await import("./transition-handler.js");
278
278
  const token = branchToken(instance, branch);
279
279
  const readContext = { ...instance.context || {}, ...branch.contextNamespace || {} };
280
- const evalContext = { workflowContext: readContext, userId: context.userId };
280
+ const evalContext = { container, workflowContext: readContext, userId: context.userId };
281
281
  let selected = null;
282
282
  if (branch.currentStepId === branch.forkStepId) {
283
283
  selected = (definition.definition.transitions || []).find(
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/workflows/lib/parallel-handler.ts"],
4
- "sourcesContent": ["/**\n * Workflows Module - Parallel Fork / Join Handler\n *\n * Implements PARALLEL_FORK / PARALLEL_JOIN execution with a multi-token model:\n *\n * - `openFork` turns a PARALLEL_FORK step into N persistent branch tokens\n * (`WorkflowBranchInstance`), one per outgoing `auto` transition, and puts the\n * instance into the dormant `FORKED` state.\n * - `advanceBranches` runs the interleaved loop: while the instance is FORKED it\n * advances each ACTIVE branch one step at a time (BPMN semantics \u2014 single lock,\n * no thread-level concurrency). A branch pauses independently (USER_TASK /\n * signal / timer / async activity) without blocking siblings.\n * - When every branch has reached its JOIN (wait-all), `fireJoin` merges the\n * branch namespaces back into `instance.context`, applies optional\n * `outputMapping`, and resumes the root token at the step after the JOIN.\n * - A failed branch cancels its siblings and fails the whole instance.\n *\n * All work happens under the executor's pessimistic instance lock + transaction,\n * so wait-all counting and JOIN firing are race-free.\n */\n\nimport { EntityManager, LockMode } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport {\n WorkflowInstance,\n WorkflowBranchInstance,\n WorkflowDefinition,\n StepInstance,\n UserTask,\n WorkflowEvent,\n} from '../data/entities'\nimport { logWorkflowEvent } from './event-logger'\nimport {\n ASYNC_ACTIVITY_OUTCOME_EVENT_TYPES,\n readPendingAsyncJobIds,\n resolveAsyncActivityWait,\n} from './async-activity-wait'\nimport * as stepHandler from './step-handler'\nimport { branchToken, mergeTokenContext, type ExecutionToken } from './execution-token'\nimport { WORKFLOW_ERROR_CONTEXT_KEY, buildErrorContextEntry, resolveStepFailureHandling } from './error-routing'\nimport { findDefinitionForInstance } from './find-definition'\nimport { isSafeMappingTargetPath, safeGetNestedValue } from './safe-mapping-path'\n\nconst logger = createLogger('workflows')\n\nexport interface AdvanceBranchesResult {\n outcome: 'joined' | 'waiting' | 'failed'\n error?: string\n}\n\nexport interface ResumeBranchOptions {\n instanceId: string\n branchInstanceId: string\n tenantId: string\n organizationId: string\n /** Values merged into the branch's private namespace before resuming (task form data, signal payload, \u2026). */\n contextMerge?: Record<string, any>\n /** Step instance to exit (the paused step's instance) before the branch advances past it. */\n exitStepInstanceId?: string | null\n exitOutput?: any\n}\n\n/**\n * Resume a single paused/waiting branch: optionally merge data into its\n * namespace, exit its paused step instance, and mark it ACTIVE. The caller then\n * re-enters `executeWorkflow` (FORKED mode) so the interleaved loop advances the\n * branch and, if it is the last to arrive, fires the JOIN.\n *\n * Idempotent: a re-delivered signal/timer/task on an already-ACTIVE or terminal\n * branch is a no-op. Returns false when there is nothing to resume.\n */\nexport async function resumeBranch(\n em: EntityManager,\n options: ResumeBranchOptions,\n): Promise<boolean> {\n const branch = await em.findOne(WorkflowBranchInstance, {\n id: options.branchInstanceId,\n workflowInstanceId: options.instanceId,\n tenantId: options.tenantId,\n organizationId: options.organizationId,\n })\n\n if (!branch) return false\n if (branch.status !== 'PAUSED' && branch.status !== 'WAITING_FOR_ACTIVITIES') {\n // Already active or terminal \u2014 re-delivery; nothing to do.\n return false\n }\n\n const now = new Date()\n if (options.contextMerge) {\n branch.contextNamespace = { ...(branch.contextNamespace || {}), ...options.contextMerge }\n }\n\n if (options.exitStepInstanceId) {\n const stepInstance = await em.findOne(StepInstance, {\n id: options.exitStepInstanceId,\n workflowInstanceId: options.instanceId,\n status: 'ACTIVE',\n })\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, options.exitOutput)\n }\n }\n\n branch.status = 'ACTIVE'\n branch.pendingTransition = null\n branch.updatedAt = now\n await em.flush()\n\n return true\n}\n\ninterface ParallelContext {\n userId?: string\n}\n\nexport function applyParallelJoinOutputMapping(\n context: Record<string, unknown>,\n outputMapping: Record<string, string>,\n): void {\n for (const [topKey, sourcePath] of Object.entries(outputMapping)) {\n if (topKey === 'branches' || !isSafeMappingTargetPath(topKey)) continue\n const value = safeGetNestedValue(context, sourcePath)\n if (value !== undefined) context[topKey] = value\n }\n}\n\nfunction normalizeWorkflowUserId(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n if (!trimmed || trimmed.startsWith('trigger:')) return null\n return trimmed\n}\n\n/**\n * Open a PARALLEL_FORK: create one ACTIVE branch per outgoing `auto` transition\n * and mark the instance FORKED. Branch tokens start positioned ON the fork step\n * so the interleaved loop runs each branch's fork transition (and its\n * activities) in that branch's own context.\n */\nexport async function openFork(\n em: EntityManager,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n forkStepDef: any,\n): Promise<void> {\n const forkStepId: string = forkStepDef.stepId\n const joinStepId: string | undefined = forkStepDef.config?.joinStepId\n if (!joinStepId) {\n throw new Error(`[internal] PARALLEL_FORK \"${forkStepId}\" missing config.joinStepId`)\n }\n\n const outgoing = (definition.definition.transitions || []).filter(\n (transition: any) => transition.fromStepId === forkStepId && transition.trigger === 'auto',\n )\n\n const now = new Date()\n const branchKeys: string[] = []\n for (const transition of outgoing) {\n branchKeys.push(transition.transitionId)\n const branch = em.create(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId,\n joinStepId,\n branchKey: transition.transitionId,\n parentBranchId: null,\n // Start ON the fork; advanceBranches runs the branch_key transition first.\n currentStepId: forkStepId,\n status: 'ACTIVE',\n contextNamespace: {},\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n startedAt: now,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(branch)\n }\n\n instance.status = 'FORKED'\n instance.activeForkStepId = forkStepId\n instance.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'PARALLEL_FORK_OPENED',\n eventData: { forkStepId, joinStepId, branchKeys },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Resume a branch that was WAITING_FOR_ACTIVITIES after its async activities\n * finished. Mirrors the instance-level resume but scoped to the branch:\n * merges completed-activity outputs into the branch namespace, advances the\n * branch's pending transition target, and marks it ACTIVE (or FAILED if any\n * async activity failed). The caller re-enters the interleaved loop.\n */\nexport async function resumeBranchAfterActivities(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n branchInstanceId: string,\n): Promise<{ continueExecution: boolean }> {\n const branch = await em.findOne(\n WorkflowBranchInstance,\n { id: branchInstanceId, workflowInstanceId: instanceId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n )\n if (!branch) {\n throw new Error('[internal] Branch not found during async resume')\n }\n if (branch.status !== 'WAITING_FOR_ACTIVITIES') {\n // Re-delivery or already advanced \u2014 nothing to do.\n return { continueExecution: false }\n }\n\n const namespace = branch.contextNamespace || {}\n const pendingJobIds = readPendingAsyncJobIds(namespace._pendingAsyncActivities)\n\n const outcomeEvents = pendingJobIds.length === 0\n ? []\n : await em.find(\n WorkflowEvent,\n {\n workflowInstanceId: instanceId,\n branchInstanceId,\n eventType: { $in: [...ASYNC_ACTIVITY_OUTCOME_EVENT_TYPES] },\n eventData: { async: true, jobId: { $in: pendingJobIds } },\n },\n { orderBy: { occurredAt: 'asc', id: 'asc' } },\n )\n const wait = resolveAsyncActivityWait(pendingJobIds, outcomeEvents)\n\n if (!wait.settled) {\n // Still waiting on other branch activities.\n return { continueExecution: false }\n }\n\n const completedEvents = wait.completed\n const failedCount = wait.failed.length\n\n const now = new Date()\n if (failedCount > 0) {\n branch.status = 'FAILED'\n branch.errorMessage = `${failedCount} async activities failed in branch \"${branch.branchKey}\"`\n branch.updatedAt = now\n await em.flush()\n // The interleaved loop will observe the FAILED branch and cancel siblings.\n return { continueExecution: true }\n }\n\n const mergedNamespace: Record<string, any> = { ...namespace }\n for (const event of completedEvents) {\n if (event.eventData?.output) {\n mergedNamespace[`${event.eventData.activityId}_result`] = event.eventData.output\n }\n }\n delete mergedNamespace._pendingAsyncActivities\n branch.contextNamespace = mergedNamespace\n\n const pending = branch.pendingTransition\n branch.pendingTransition = null\n branch.status = 'ACTIVE'\n branch.updatedAt = now\n await em.flush()\n\n // Execute the destination step in branch context (mirrors the instance-level\n // resume) so the branch cursor lands on an executed step. The step may pause\n // the branch again (e.g. a following USER_TASK); that is handled by the loop.\n if (pending) {\n const instance = await em.findOne(WorkflowInstance, { id: instanceId })\n if (instance) {\n branch.currentStepId = pending.toStepId\n await em.flush()\n const evalContext = {\n workflowContext: { ...(instance.context || {}), ...(branch.contextNamespace || {}) },\n userId: normalizeWorkflowUserId(instance.metadata?.initiatedBy) ?? undefined,\n }\n const stepResult = await stepHandler.executeStep(\n em,\n instance,\n pending.toStepId,\n evalContext,\n container,\n branch,\n )\n if (stepResult.status === 'FAILED') {\n const token = branchToken(instance, branch)\n const definition = await findDefinitionForInstance(em, instance)\n const handling = resolveStepFailureHandling(definition?.definition, pending.toStepId)\n if (handling.kind === 'continue') {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'ERROR_DIRECTIVE_APPLIED',\n eventData: {\n stepId: pending.toStepId,\n directive: 'continueWithFallback',\n error: stepResult.error,\n hasFallbackValue: handling.fallbackValue !== undefined,\n },\n userId: evalContext.userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n if (handling.fallbackValue !== undefined) {\n mergeTokenContext(token, { [pending.toStepId]: handling.fallbackValue })\n await em.flush()\n }\n } else {\n const error = stepResult.error || 'Step execution failed'\n try {\n const routed = await followBranchErrorRoute(em, container, instance, branch, token, {\n failedStepId: pending.toStepId,\n error,\n errorRoute: handling.kind === 'route' && handling.transition.toStepId\n ? { transitionId: handling.transition.transitionId, toStepId: handling.transition.toStepId }\n : undefined,\n }, evalContext)\n if (!routed) {\n await failBranch(em, instance, branch, error)\n } else if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n }\n } catch (error) {\n await failBranch(em, instance, branch, error instanceof Error ? error.message : String(error))\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'workflows',\n code: 'workflows.branch_resume_error_route_failed',\n attributes: { instanceId: instance.id, branchInstanceId: branch.id },\n })\n } catch (reportingError) {\n logger.warn('Failed to report branch resume error', { err: reportingError })\n }\n }\n }\n }\n }\n }\n\n return { continueExecution: true }\n}\n\n/**\n * Interleaved branch execution loop. Advances ACTIVE branches one step at a\n * time until either all branches reach the JOIN (\u2192 fireJoin \u2192 'joined'), a\n * branch fails (\u2192 cancel siblings + 'failed'), or no branch is ACTIVE because\n * they are all waiting on external resume (\u2192 'waiting').\n */\nexport async function advanceBranches(\n em: EntityManager,\n container: AwilixContainer,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n context: ParallelContext,\n): Promise<AdvanceBranchesResult> {\n const forkStepId = instance.activeForkStepId\n if (!forkStepId) {\n throw new Error('[internal] advanceBranches called but instance has no active fork')\n }\n\n // Branch-aware iteration budget: each branch gets the same per-token budget as\n // the single-token loop, so fan-out alone never trips the guard.\n const allBranchesForBudget = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId,\n })\n const maxIterations = Math.max(1, allBranchesForBudget.length) * 100\n let iterations = 0\n\n while (iterations < maxIterations) {\n iterations++\n\n const branches = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId,\n })\n\n const active = branches.filter((b) => b.status === 'ACTIVE')\n\n if (active.length === 0) {\n const failed = branches.find((b) => b.status === 'FAILED')\n if (failed) {\n // A branch failed out-of-band (e.g. async-activity resume marked it\n // FAILED); cancel any non-terminal siblings before failing the instance.\n await cancelSiblings(em, instance, failed)\n return { outcome: 'failed', error: failed.errorMessage || 'Branch failed' }\n }\n if (branches.every((b) => b.status === 'COMPLETED')) {\n await fireJoin(em, instance, definition, branches, forkStepId)\n return { outcome: 'joined' }\n }\n // Some branches paused/waiting for external resume \u2014 instance idles.\n return { outcome: 'waiting' }\n }\n\n for (const branch of active) {\n const result = await advanceOneBranch(em, container, instance, definition, branch, context)\n if (result === 'failed') {\n await cancelSiblings(em, instance, branch)\n return { outcome: 'failed', error: branch.errorMessage || 'Branch failed' }\n }\n }\n }\n\n throw new Error('[internal] Maximum branch execution iterations reached - possible infinite loop')\n}\n\n/**\n * Advance a single ACTIVE branch by one step. Returns 'failed' if the branch\n * failed; otherwise mutates branch state (advanced / completed@join / paused).\n */\nasync function advanceOneBranch(\n em: EntityManager,\n container: AwilixContainer,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n branch: WorkflowBranchInstance,\n context: ParallelContext,\n): Promise<'advanced' | 'failed'> {\n // Already at the join \u2192 synchronize (mark completed, do not execute the join).\n if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n return 'advanced'\n }\n\n const transitionHandler = await import('./transition-handler')\n\n const token = branchToken(instance, branch)\n // Token read context = instance snapshot overlaid with branch namespace.\n const readContext = { ...(instance.context || {}), ...(branch.contextNamespace || {}) }\n const evalContext = { workflowContext: readContext, userId: context.userId }\n\n // Select the transition to take. Branches positioned on the fork follow their\n // own branch_key transition; otherwise pick the highest-priority valid auto one.\n let selected: any | null = null\n if (branch.currentStepId === branch.forkStepId) {\n selected = (definition.definition.transitions || []).find(\n (transition: any) => transition.transitionId === branch.branchKey,\n ) || null\n } else {\n const valid = await transitionHandler.findValidTransitions(\n em,\n instance,\n branch.currentStepId,\n evalContext,\n )\n const validAuto = valid.filter((vt) => vt.isValid && vt.transition?.trigger === 'auto')\n selected = validAuto.length > 0 ? validAuto[0].transition : null\n }\n\n if (!selected) {\n // No outgoing transition and not at the join \u2192 the branch is stuck.\n await failBranch(em, instance, branch, `Branch \"${branch.branchKey}\" has no valid transition from \"${branch.currentStepId}\"`)\n return 'failed'\n }\n\n try {\n const transitionResult = await transitionHandler.executeTransitionForToken(\n em,\n container,\n token,\n selected.fromStepId,\n selected.toStepId,\n { ...evalContext, transitionId: selected.transitionId },\n )\n\n if (!transitionResult.success) {\n // Error routing (spec 5.9) inside a branch: a wired error route is taken\n // in the branch itself, so only unhandled failures propagate to the\n // instance. The failure-queue directive is deliberately instance-level and\n // is not honored per branch \u2014 such a branch keeps failing as it does today.\n const routed = await followBranchErrorRoute(\n em,\n container,\n instance,\n branch,\n token,\n transitionResult,\n evalContext,\n )\n if (routed) {\n if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n }\n return 'advanced'\n }\n await failBranch(em, instance, branch, transitionResult.error || 'Branch transition failed')\n return 'failed'\n }\n\n // executeTransitionForToken set branch.currentStepId = toStepId. If that is\n // the join, synchronize now (the join step itself is a no-op).\n if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n }\n return 'advanced'\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n await failBranch(em, instance, branch, message)\n return 'failed'\n }\n}\n\n/**\n * Follow a branch step's wired error route with the branch token, so the branch\n * keeps its own cursor and context namespace. Returns false when the transition\n * result carries no route or the route could not be taken.\n */\nasync function followBranchErrorRoute(\n em: EntityManager,\n container: AwilixContainer,\n instance: WorkflowInstance,\n branch: WorkflowBranchInstance,\n token: ExecutionToken,\n transitionResult: { failedStepId?: string; errorRoute?: { transitionId?: string; toStepId: string }; error?: string },\n evalContext: { workflowContext: Record<string, any>; userId?: string },\n): Promise<boolean> {\n const { failedStepId, errorRoute } = transitionResult\n if (!failedStepId || !errorRoute) return false\n\n const error = transitionResult.error || 'Branch transition failed'\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'ERROR_ROUTED',\n eventData: {\n failedStepId,\n toStepId: errorRoute.toStepId,\n transitionId: errorRoute.transitionId,\n branchKey: branch.branchKey,\n error,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const errorEntry = buildErrorContextEntry(failedStepId, error)\n mergeTokenContext(token, { [WORKFLOW_ERROR_CONTEXT_KEY]: errorEntry })\n await em.flush()\n\n const transitionHandler = await import('./transition-handler')\n const routedResult = await transitionHandler.executeTransitionForToken(\n em,\n container,\n token,\n failedStepId,\n errorRoute.toStepId,\n {\n ...evalContext,\n workflowContext: {\n ...evalContext.workflowContext,\n [WORKFLOW_ERROR_CONTEXT_KEY]: errorEntry,\n },\n transitionId: errorRoute.transitionId,\n },\n )\n\n return routedResult.success === true\n}\n\nasync function completeBranchAtJoin(\n em: EntityManager,\n instance: WorkflowInstance,\n branch: WorkflowBranchInstance,\n): Promise<void> {\n const now = new Date()\n branch.status = 'COMPLETED'\n branch.completedAt = now\n branch.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'PARALLEL_BRANCH_COMPLETED',\n eventData: { branchKey: branch.branchKey, joinStepId: branch.joinStepId },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\nasync function failBranch(\n em: EntityManager,\n instance: WorkflowInstance,\n branch: WorkflowBranchInstance,\n message: string,\n): Promise<void> {\n const now = new Date()\n branch.status = 'FAILED'\n branch.errorMessage = message\n branch.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'PARALLEL_BRANCH_FAILED',\n eventData: { branchKey: branch.branchKey, error: message },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Cancel sibling branches of a failed branch (best-effort), cancel their open\n * user tasks, and log a cancellation event per branch.\n */\nasync function cancelSiblings(\n em: EntityManager,\n instance: WorkflowInstance,\n failedBranch: WorkflowBranchInstance,\n): Promise<void> {\n const siblings = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId: failedBranch.forkStepId,\n })\n\n const now = new Date()\n for (const sibling of siblings) {\n if (sibling.id === failedBranch.id) continue\n if (sibling.status === 'ACTIVE' || sibling.status === 'PAUSED' || sibling.status === 'WAITING_FOR_ACTIVITIES') {\n sibling.status = 'CANCELLED'\n sibling.updatedAt = now\n\n // Best-effort: cancel the branch's open user tasks.\n const openTasks = await em.find(UserTask, {\n workflowInstanceId: instance.id,\n branchInstanceId: sibling.id,\n status: 'PENDING',\n })\n for (const task of openTasks) {\n task.status = 'CANCELLED'\n task.updatedAt = now\n }\n\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: sibling.id,\n eventType: 'PARALLEL_BRANCH_CANCELLED',\n eventData: { branchKey: sibling.branchKey, reason: 'sibling-failed' },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n }\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'PARALLEL_FORK_FAILED',\n eventData: { forkStepId: failedBranch.forkStepId, failedBranchKey: failedBranch.branchKey },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Fire the JOIN once all branches are COMPLETED: merge each branch namespace\n * under `instance.context.branches[branchKey]`, apply optional outputMapping to\n * lift selected values to the top level, then resume the root token at the step\n * after the JOIN.\n */\nasync function fireJoin(\n em: EntityManager,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n branches: WorkflowBranchInstance[],\n forkStepId: string,\n): Promise<void> {\n const joinStepId = branches[0]?.joinStepId\n if (!joinStepId) {\n throw new Error('[internal] fireJoin called without a join step id')\n }\n\n const joinStep = definition.definition.steps.find((s: any) => s.stepId === joinStepId)\n\n // Deterministic merge \u2014 no silent collisions: each branch keeps its own slot.\n const branchesContext: Record<string, any> = { ...(instance.context?.branches || {}) }\n const mergedBranchKeys: string[] = []\n for (const branch of branches) {\n branchesContext[branch.branchKey] = branch.contextNamespace || {}\n mergedBranchKeys.push(branch.branchKey)\n }\n\n let nextContext: Record<string, any> = {\n ...(instance.context || {}),\n branches: branchesContext,\n }\n\n // Optional outputMapping: topLevelKey -> 'branches.<branchKey>.<path>'. The\n // reserved `branches` slot map is never overwritten \u2014 guard it explicitly so a\n // mapping cannot clobber the per-branch namespaces.\n const outputMapping: Record<string, string> | undefined = joinStep?.config?.outputMapping\n if (outputMapping) {\n applyParallelJoinOutputMapping(nextContext, outputMapping)\n }\n\n // Park the root token ON the JOIN step (not its successor) and let the\n // single-token executor loop run the JOIN's outgoing transition. Jumping\n // straight to the post-join step would bypass stepHandler.executeStep() for\n // that step \u2014 so a following USER_TASK / WAIT_FOR_TIMER / WAIT_FOR_SIGNAL would\n // never have its task created / timer enqueued / signal wait registered (the\n // instance would hang), and any activities on the JOIN's outgoing transition\n // would be skipped. The JOIN step itself is a no-op, so the loop simply runs\n // its outgoing transition through the normal step-entry path.\n const afterJoinStepId = (definition.definition.transitions || []).find(\n (transition: any) => transition.fromStepId === joinStepId,\n )?.toStepId ?? null\n\n const now = new Date()\n instance.context = nextContext\n instance.status = 'RUNNING'\n instance.activeForkStepId = null\n instance.currentStepId = joinStepId\n instance.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'PARALLEL_JOIN_COMPLETED',\n eventData: { forkStepId, joinStepId, mergedBranchKeys, afterJoinStepId },\n tenantId: instance.tenantId,\n organizationId: inst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jB,mCAA+B,aAAa,aAAa;AAAA,EAC3D;AAUA,QAAM,mBAAmB,WAAW,WAAW,eAAe,CAAC,GAAG;AAAA,IAChE,CAAC,eAAoB,WAAW,eAAe;AAAA,EACjD,GAAG,YAAY;AAEf,QAAM,MAAM,oBAAI,KAAK;AACrB,WAAS,UAAU;AACnB,WAAS,SAAS;AAClB,WAAS,mBAAmB;AAC5B,WAAS,gBAAgB;AACzB,WAAS,YAAY;AACrB,QAAM,GAAG,MAAM;AAEf,QAAM,iBAAiB,IAAI;AAAA,IACzB,oBAAoB,SAAS;AAAA,IAC7B,WAAW;AAAA,IACX,WAAW,EAAE,YAAY,YAAY,kBAAkB,gBAAgB;AAAA,IACvE,UAAU,SAAS;AAAA,IACnB,gBAAgB,SAAS;AAAA,EAC3B,CAAC;AACH;",
4
+ "sourcesContent": ["/**\n * Workflows Module - Parallel Fork / Join Handler\n *\n * Implements PARALLEL_FORK / PARALLEL_JOIN execution with a multi-token model:\n *\n * - `openFork` turns a PARALLEL_FORK step into N persistent branch tokens\n * (`WorkflowBranchInstance`), one per outgoing `auto` transition, and puts the\n * instance into the dormant `FORKED` state.\n * - `advanceBranches` runs the interleaved loop: while the instance is FORKED it\n * advances each ACTIVE branch one step at a time (BPMN semantics \u2014 single lock,\n * no thread-level concurrency). A branch pauses independently (USER_TASK /\n * signal / timer / async activity) without blocking siblings.\n * - When every branch has reached its JOIN (wait-all), `fireJoin` merges the\n * branch namespaces back into `instance.context`, applies optional\n * `outputMapping`, and resumes the root token at the step after the JOIN.\n * - A failed branch cancels its siblings and fails the whole instance.\n *\n * All work happens under the executor's pessimistic instance lock + transaction,\n * so wait-all counting and JOIN firing are race-free.\n */\n\nimport { EntityManager, LockMode } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport {\n WorkflowInstance,\n WorkflowBranchInstance,\n WorkflowDefinition,\n StepInstance,\n UserTask,\n WorkflowEvent,\n} from '../data/entities'\nimport { logWorkflowEvent } from './event-logger'\nimport {\n ASYNC_ACTIVITY_OUTCOME_EVENT_TYPES,\n readPendingAsyncJobIds,\n resolveAsyncActivityWait,\n} from './async-activity-wait'\nimport * as stepHandler from './step-handler'\nimport { branchToken, mergeTokenContext, type ExecutionToken } from './execution-token'\nimport { WORKFLOW_ERROR_CONTEXT_KEY, buildErrorContextEntry, resolveStepFailureHandling } from './error-routing'\nimport { findDefinitionForInstance } from './find-definition'\nimport { isSafeMappingTargetPath, safeGetNestedValue } from './safe-mapping-path'\n\nconst logger = createLogger('workflows')\n\nexport interface AdvanceBranchesResult {\n outcome: 'joined' | 'waiting' | 'failed'\n error?: string\n}\n\nexport interface ResumeBranchOptions {\n instanceId: string\n branchInstanceId: string\n tenantId: string\n organizationId: string\n /** Values merged into the branch's private namespace before resuming (task form data, signal payload, \u2026). */\n contextMerge?: Record<string, any>\n /** Step instance to exit (the paused step's instance) before the branch advances past it. */\n exitStepInstanceId?: string | null\n exitOutput?: any\n}\n\n/**\n * Resume a single paused/waiting branch: optionally merge data into its\n * namespace, exit its paused step instance, and mark it ACTIVE. The caller then\n * re-enters `executeWorkflow` (FORKED mode) so the interleaved loop advances the\n * branch and, if it is the last to arrive, fires the JOIN.\n *\n * Idempotent: a re-delivered signal/timer/task on an already-ACTIVE or terminal\n * branch is a no-op. Returns false when there is nothing to resume.\n */\nexport async function resumeBranch(\n em: EntityManager,\n options: ResumeBranchOptions,\n): Promise<boolean> {\n const branch = await em.findOne(WorkflowBranchInstance, {\n id: options.branchInstanceId,\n workflowInstanceId: options.instanceId,\n tenantId: options.tenantId,\n organizationId: options.organizationId,\n })\n\n if (!branch) return false\n if (branch.status !== 'PAUSED' && branch.status !== 'WAITING_FOR_ACTIVITIES') {\n // Already active or terminal \u2014 re-delivery; nothing to do.\n return false\n }\n\n const now = new Date()\n if (options.contextMerge) {\n branch.contextNamespace = { ...(branch.contextNamespace || {}), ...options.contextMerge }\n }\n\n if (options.exitStepInstanceId) {\n const stepInstance = await em.findOne(StepInstance, {\n id: options.exitStepInstanceId,\n workflowInstanceId: options.instanceId,\n status: 'ACTIVE',\n })\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, options.exitOutput)\n }\n }\n\n branch.status = 'ACTIVE'\n branch.pendingTransition = null\n branch.updatedAt = now\n await em.flush()\n\n return true\n}\n\ninterface ParallelContext {\n userId?: string\n}\n\nexport function applyParallelJoinOutputMapping(\n context: Record<string, unknown>,\n outputMapping: Record<string, string>,\n): void {\n for (const [topKey, sourcePath] of Object.entries(outputMapping)) {\n if (topKey === 'branches' || !isSafeMappingTargetPath(topKey)) continue\n const value = safeGetNestedValue(context, sourcePath)\n if (value !== undefined) context[topKey] = value\n }\n}\n\nfunction normalizeWorkflowUserId(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n if (!trimmed || trimmed.startsWith('trigger:')) return null\n return trimmed\n}\n\n/**\n * Open a PARALLEL_FORK: create one ACTIVE branch per outgoing `auto` transition\n * and mark the instance FORKED. Branch tokens start positioned ON the fork step\n * so the interleaved loop runs each branch's fork transition (and its\n * activities) in that branch's own context.\n */\nexport async function openFork(\n em: EntityManager,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n forkStepDef: any,\n): Promise<void> {\n const forkStepId: string = forkStepDef.stepId\n const joinStepId: string | undefined = forkStepDef.config?.joinStepId\n if (!joinStepId) {\n throw new Error(`[internal] PARALLEL_FORK \"${forkStepId}\" missing config.joinStepId`)\n }\n\n const outgoing = (definition.definition.transitions || []).filter(\n (transition: any) => transition.fromStepId === forkStepId && transition.trigger === 'auto',\n )\n\n const now = new Date()\n const branchKeys: string[] = []\n for (const transition of outgoing) {\n branchKeys.push(transition.transitionId)\n const branch = em.create(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId,\n joinStepId,\n branchKey: transition.transitionId,\n parentBranchId: null,\n // Start ON the fork; advanceBranches runs the branch_key transition first.\n currentStepId: forkStepId,\n status: 'ACTIVE',\n contextNamespace: {},\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n startedAt: now,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(branch)\n }\n\n instance.status = 'FORKED'\n instance.activeForkStepId = forkStepId\n instance.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'PARALLEL_FORK_OPENED',\n eventData: { forkStepId, joinStepId, branchKeys },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Resume a branch that was WAITING_FOR_ACTIVITIES after its async activities\n * finished. Mirrors the instance-level resume but scoped to the branch:\n * merges completed-activity outputs into the branch namespace, advances the\n * branch's pending transition target, and marks it ACTIVE (or FAILED if any\n * async activity failed). The caller re-enters the interleaved loop.\n */\nexport async function resumeBranchAfterActivities(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n branchInstanceId: string,\n): Promise<{ continueExecution: boolean }> {\n const branch = await em.findOne(\n WorkflowBranchInstance,\n { id: branchInstanceId, workflowInstanceId: instanceId },\n { lockMode: LockMode.PESSIMISTIC_WRITE },\n )\n if (!branch) {\n throw new Error('[internal] Branch not found during async resume')\n }\n if (branch.status !== 'WAITING_FOR_ACTIVITIES') {\n // Re-delivery or already advanced \u2014 nothing to do.\n return { continueExecution: false }\n }\n\n const namespace = branch.contextNamespace || {}\n const pendingJobIds = readPendingAsyncJobIds(namespace._pendingAsyncActivities)\n\n const outcomeEvents = pendingJobIds.length === 0\n ? []\n : await em.find(\n WorkflowEvent,\n {\n workflowInstanceId: instanceId,\n branchInstanceId,\n eventType: { $in: [...ASYNC_ACTIVITY_OUTCOME_EVENT_TYPES] },\n eventData: { async: true, jobId: { $in: pendingJobIds } },\n },\n { orderBy: { occurredAt: 'asc', id: 'asc' } },\n )\n const wait = resolveAsyncActivityWait(pendingJobIds, outcomeEvents)\n\n if (!wait.settled) {\n // Still waiting on other branch activities.\n return { continueExecution: false }\n }\n\n const completedEvents = wait.completed\n const failedCount = wait.failed.length\n\n const now = new Date()\n if (failedCount > 0) {\n branch.status = 'FAILED'\n branch.errorMessage = `${failedCount} async activities failed in branch \"${branch.branchKey}\"`\n branch.updatedAt = now\n await em.flush()\n // The interleaved loop will observe the FAILED branch and cancel siblings.\n return { continueExecution: true }\n }\n\n const mergedNamespace: Record<string, any> = { ...namespace }\n for (const event of completedEvents) {\n if (event.eventData?.output) {\n mergedNamespace[`${event.eventData.activityId}_result`] = event.eventData.output\n }\n }\n delete mergedNamespace._pendingAsyncActivities\n branch.contextNamespace = mergedNamespace\n\n const pending = branch.pendingTransition\n branch.pendingTransition = null\n branch.status = 'ACTIVE'\n branch.updatedAt = now\n await em.flush()\n\n // Execute the destination step in branch context (mirrors the instance-level\n // resume) so the branch cursor lands on an executed step. The step may pause\n // the branch again (e.g. a following USER_TASK); that is handled by the loop.\n if (pending) {\n const instance = await em.findOne(WorkflowInstance, { id: instanceId })\n if (instance) {\n branch.currentStepId = pending.toStepId\n await em.flush()\n const evalContext = {\n workflowContext: { ...(instance.context || {}), ...(branch.contextNamespace || {}) },\n userId: normalizeWorkflowUserId(instance.metadata?.initiatedBy) ?? undefined,\n }\n const stepResult = await stepHandler.executeStep(\n em,\n instance,\n pending.toStepId,\n evalContext,\n container,\n branch,\n )\n if (stepResult.status === 'FAILED') {\n const token = branchToken(instance, branch)\n const definition = await findDefinitionForInstance(em, instance)\n const handling = resolveStepFailureHandling(definition?.definition, pending.toStepId)\n if (handling.kind === 'continue') {\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'ERROR_DIRECTIVE_APPLIED',\n eventData: {\n stepId: pending.toStepId,\n directive: 'continueWithFallback',\n error: stepResult.error,\n hasFallbackValue: handling.fallbackValue !== undefined,\n },\n userId: evalContext.userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n if (handling.fallbackValue !== undefined) {\n mergeTokenContext(token, { [pending.toStepId]: handling.fallbackValue })\n await em.flush()\n }\n } else {\n const error = stepResult.error || 'Step execution failed'\n try {\n const routed = await followBranchErrorRoute(em, container, instance, branch, token, {\n failedStepId: pending.toStepId,\n error,\n errorRoute: handling.kind === 'route' && handling.transition.toStepId\n ? { transitionId: handling.transition.transitionId, toStepId: handling.transition.toStepId }\n : undefined,\n }, evalContext)\n if (!routed) {\n await failBranch(em, instance, branch, error)\n } else if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n }\n } catch (error) {\n await failBranch(em, instance, branch, error instanceof Error ? error.message : String(error))\n try {\n getTelemetryRuntime()?.reportError(error, {\n module: 'workflows',\n code: 'workflows.branch_resume_error_route_failed',\n attributes: { instanceId: instance.id, branchInstanceId: branch.id },\n })\n } catch (reportingError) {\n logger.warn('Failed to report branch resume error', { err: reportingError })\n }\n }\n }\n }\n }\n }\n\n return { continueExecution: true }\n}\n\n/**\n * Interleaved branch execution loop. Advances ACTIVE branches one step at a\n * time until either all branches reach the JOIN (\u2192 fireJoin \u2192 'joined'), a\n * branch fails (\u2192 cancel siblings + 'failed'), or no branch is ACTIVE because\n * they are all waiting on external resume (\u2192 'waiting').\n */\nexport async function advanceBranches(\n em: EntityManager,\n container: AwilixContainer,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n context: ParallelContext,\n): Promise<AdvanceBranchesResult> {\n const forkStepId = instance.activeForkStepId\n if (!forkStepId) {\n throw new Error('[internal] advanceBranches called but instance has no active fork')\n }\n\n // Branch-aware iteration budget: each branch gets the same per-token budget as\n // the single-token loop, so fan-out alone never trips the guard.\n const allBranchesForBudget = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId,\n })\n const maxIterations = Math.max(1, allBranchesForBudget.length) * 100\n let iterations = 0\n\n while (iterations < maxIterations) {\n iterations++\n\n const branches = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId,\n })\n\n const active = branches.filter((b) => b.status === 'ACTIVE')\n\n if (active.length === 0) {\n const failed = branches.find((b) => b.status === 'FAILED')\n if (failed) {\n // A branch failed out-of-band (e.g. async-activity resume marked it\n // FAILED); cancel any non-terminal siblings before failing the instance.\n await cancelSiblings(em, instance, failed)\n return { outcome: 'failed', error: failed.errorMessage || 'Branch failed' }\n }\n if (branches.every((b) => b.status === 'COMPLETED')) {\n await fireJoin(em, instance, definition, branches, forkStepId)\n return { outcome: 'joined' }\n }\n // Some branches paused/waiting for external resume \u2014 instance idles.\n return { outcome: 'waiting' }\n }\n\n for (const branch of active) {\n const result = await advanceOneBranch(em, container, instance, definition, branch, context)\n if (result === 'failed') {\n await cancelSiblings(em, instance, branch)\n return { outcome: 'failed', error: branch.errorMessage || 'Branch failed' }\n }\n }\n }\n\n throw new Error('[internal] Maximum branch execution iterations reached - possible infinite loop')\n}\n\n/**\n * Advance a single ACTIVE branch by one step. Returns 'failed' if the branch\n * failed; otherwise mutates branch state (advanced / completed@join / paused).\n */\nasync function advanceOneBranch(\n em: EntityManager,\n container: AwilixContainer,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n branch: WorkflowBranchInstance,\n context: ParallelContext,\n): Promise<'advanced' | 'failed'> {\n // Already at the join \u2192 synchronize (mark completed, do not execute the join).\n if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n return 'advanced'\n }\n\n const transitionHandler = await import('./transition-handler')\n\n const token = branchToken(instance, branch)\n // Token read context = instance snapshot overlaid with branch namespace.\n const readContext = { ...(instance.context || {}), ...(branch.contextNamespace || {}) }\n const evalContext = { container, workflowContext: readContext, userId: context.userId }\n\n // Select the transition to take. Branches positioned on the fork follow their\n // own branch_key transition; otherwise pick the highest-priority valid auto one.\n let selected: any | null = null\n if (branch.currentStepId === branch.forkStepId) {\n selected = (definition.definition.transitions || []).find(\n (transition: any) => transition.transitionId === branch.branchKey,\n ) || null\n } else {\n const valid = await transitionHandler.findValidTransitions(\n em,\n instance,\n branch.currentStepId,\n evalContext,\n )\n const validAuto = valid.filter((vt) => vt.isValid && vt.transition?.trigger === 'auto')\n selected = validAuto.length > 0 ? validAuto[0].transition : null\n }\n\n if (!selected) {\n // No outgoing transition and not at the join \u2192 the branch is stuck.\n await failBranch(em, instance, branch, `Branch \"${branch.branchKey}\" has no valid transition from \"${branch.currentStepId}\"`)\n return 'failed'\n }\n\n try {\n const transitionResult = await transitionHandler.executeTransitionForToken(\n em,\n container,\n token,\n selected.fromStepId,\n selected.toStepId,\n { ...evalContext, transitionId: selected.transitionId },\n )\n\n if (!transitionResult.success) {\n // Error routing (spec 5.9) inside a branch: a wired error route is taken\n // in the branch itself, so only unhandled failures propagate to the\n // instance. The failure-queue directive is deliberately instance-level and\n // is not honored per branch \u2014 such a branch keeps failing as it does today.\n const routed = await followBranchErrorRoute(\n em,\n container,\n instance,\n branch,\n token,\n transitionResult,\n evalContext,\n )\n if (routed) {\n if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n }\n return 'advanced'\n }\n await failBranch(em, instance, branch, transitionResult.error || 'Branch transition failed')\n return 'failed'\n }\n\n // executeTransitionForToken set branch.currentStepId = toStepId. If that is\n // the join, synchronize now (the join step itself is a no-op).\n if (branch.currentStepId === branch.joinStepId) {\n await completeBranchAtJoin(em, instance, branch)\n }\n return 'advanced'\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n await failBranch(em, instance, branch, message)\n return 'failed'\n }\n}\n\n/**\n * Follow a branch step's wired error route with the branch token, so the branch\n * keeps its own cursor and context namespace. Returns false when the transition\n * result carries no route or the route could not be taken.\n */\nasync function followBranchErrorRoute(\n em: EntityManager,\n container: AwilixContainer,\n instance: WorkflowInstance,\n branch: WorkflowBranchInstance,\n token: ExecutionToken,\n transitionResult: { failedStepId?: string; errorRoute?: { transitionId?: string; toStepId: string }; error?: string },\n evalContext: { workflowContext: Record<string, any>; userId?: string },\n): Promise<boolean> {\n const { failedStepId, errorRoute } = transitionResult\n if (!failedStepId || !errorRoute) return false\n\n const error = transitionResult.error || 'Branch transition failed'\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'ERROR_ROUTED',\n eventData: {\n failedStepId,\n toStepId: errorRoute.toStepId,\n transitionId: errorRoute.transitionId,\n branchKey: branch.branchKey,\n error,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const errorEntry = buildErrorContextEntry(failedStepId, error)\n mergeTokenContext(token, { [WORKFLOW_ERROR_CONTEXT_KEY]: errorEntry })\n await em.flush()\n\n const transitionHandler = await import('./transition-handler')\n const routedResult = await transitionHandler.executeTransitionForToken(\n em,\n container,\n token,\n failedStepId,\n errorRoute.toStepId,\n {\n ...evalContext,\n workflowContext: {\n ...evalContext.workflowContext,\n [WORKFLOW_ERROR_CONTEXT_KEY]: errorEntry,\n },\n transitionId: errorRoute.transitionId,\n },\n )\n\n return routedResult.success === true\n}\n\nasync function completeBranchAtJoin(\n em: EntityManager,\n instance: WorkflowInstance,\n branch: WorkflowBranchInstance,\n): Promise<void> {\n const now = new Date()\n branch.status = 'COMPLETED'\n branch.completedAt = now\n branch.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'PARALLEL_BRANCH_COMPLETED',\n eventData: { branchKey: branch.branchKey, joinStepId: branch.joinStepId },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\nasync function failBranch(\n em: EntityManager,\n instance: WorkflowInstance,\n branch: WorkflowBranchInstance,\n message: string,\n): Promise<void> {\n const now = new Date()\n branch.status = 'FAILED'\n branch.errorMessage = message\n branch.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: branch.id,\n eventType: 'PARALLEL_BRANCH_FAILED',\n eventData: { branchKey: branch.branchKey, error: message },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Cancel sibling branches of a failed branch (best-effort), cancel their open\n * user tasks, and log a cancellation event per branch.\n */\nasync function cancelSiblings(\n em: EntityManager,\n instance: WorkflowInstance,\n failedBranch: WorkflowBranchInstance,\n): Promise<void> {\n const siblings = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instance.id,\n forkStepId: failedBranch.forkStepId,\n })\n\n const now = new Date()\n for (const sibling of siblings) {\n if (sibling.id === failedBranch.id) continue\n if (sibling.status === 'ACTIVE' || sibling.status === 'PAUSED' || sibling.status === 'WAITING_FOR_ACTIVITIES') {\n sibling.status = 'CANCELLED'\n sibling.updatedAt = now\n\n // Best-effort: cancel the branch's open user tasks.\n const openTasks = await em.find(UserTask, {\n workflowInstanceId: instance.id,\n branchInstanceId: sibling.id,\n status: 'PENDING',\n })\n for (const task of openTasks) {\n task.status = 'CANCELLED'\n task.updatedAt = now\n }\n\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n branchInstanceId: sibling.id,\n eventType: 'PARALLEL_BRANCH_CANCELLED',\n eventData: { branchKey: sibling.branchKey, reason: 'sibling-failed' },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n }\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'PARALLEL_FORK_FAILED',\n eventData: { forkStepId: failedBranch.forkStepId, failedBranchKey: failedBranch.branchKey },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Fire the JOIN once all branches are COMPLETED: merge each branch namespace\n * under `instance.context.branches[branchKey]`, apply optional outputMapping to\n * lift selected values to the top level, then resume the root token at the step\n * after the JOIN.\n */\nasync function fireJoin(\n em: EntityManager,\n instance: WorkflowInstance,\n definition: WorkflowDefinition,\n branches: WorkflowBranchInstance[],\n forkStepId: string,\n): Promise<void> {\n const joinStepId = branches[0]?.joinStepId\n if (!joinStepId) {\n throw new Error('[internal] fireJoin called without a join step id')\n }\n\n const joinStep = definition.definition.steps.find((s: any) => s.stepId === joinStepId)\n\n // Deterministic merge \u2014 no silent collisions: each branch keeps its own slot.\n const branchesContext: Record<string, any> = { ...(instance.context?.branches || {}) }\n const mergedBranchKeys: string[] = []\n for (const branch of branches) {\n branchesContext[branch.branchKey] = branch.contextNamespace || {}\n mergedBranchKeys.push(branch.branchKey)\n }\n\n let nextContext: Record<string, any> = {\n ...(instance.context || {}),\n branches: branchesContext,\n }\n\n // Optional outputMapping: topLevelKey -> 'branches.<branchKey>.<path>'. The\n // reserved `branches` slot map is never overwritten \u2014 guard it explicitly so a\n // mapping cannot clobber the per-branch namespaces.\n const outputMapping: Record<string, string> | undefined = joinStep?.config?.outputMapping\n if (outputMapping) {\n applyParallelJoinOutputMapping(nextContext, outputMapping)\n }\n\n // Park the root token ON the JOIN step (not its successor) and let the\n // single-token executor loop run the JOIN's outgoing transition. Jumping\n // straight to the post-join step would bypass stepHandler.executeStep() for\n // that step \u2014 so a following USER_TASK / WAIT_FOR_TIMER / WAIT_FOR_SIGNAL would\n // never have its task created / timer enqueued / signal wait registered (the\n // instance would hang), and any activities on the JOIN's outgoing transition\n // would be skipped. The JOIN step itself is a no-op, so the loop simply runs\n // its outgoing transition through the normal step-entry path.\n const afterJoinStepId = (definition.definition.transitions || []).find(\n (transition: any) => transition.fromStepId === joinStepId,\n )?.toStepId ?? null\n\n const now = new Date()\n instance.context = nextContext\n instance.status = 'RUNNING'\n instance.activeForkStepId = null\n instance.currentStepId = joinStepId\n instance.updatedAt = now\n await em.flush()\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'PARALLEL_JOIN_COMPLETED',\n eventData: { forkStepId, joinStepId, mergedBranchKeys, afterJoinStepId },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n"],
5
+ "mappings": "AAqBA,SAAwB,gBAAgB;AAExC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;A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QAAM,MAAM,oBAAI,KAAK;AACrB,WAAS,UAAU;AACnB,WAAS,SAAS;AAClB,WAAS,mBAAmB;AAC5B,WAAS,gBAAgB;AACzB,WAAS,YAAY;AACrB,QAAM,GAAG,MAAM;AAEf,QAAM,iBAAiB,IAAI;AAAA,IACzB,oBAAoB,SAAS;AAAA,IAC7B,WAAW;AAAA,IACX,WAAW,EAAE,YAAY,YAAY,kBAAkB,gBAAgB;AAAA,IACvE,UAAU,SAAS;AAAA,IACnB,gBAAgB,SAAS;AAAA,EAC3B,CAAC;AACH;",
6
6
  "names": ["error"]
7
7
  }
@@ -295,6 +295,7 @@ async function sendSignal(em, container, options) {
295
295
  return;
296
296
  }
297
297
  const transitionContext = {
298
+ container,
298
299
  workflowContext: instance.context,
299
300
  userId
300
301
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/workflows/lib/signal-handler.ts"],
4
- "sourcesContent": ["/**\n * Signal Handler Service\n *\n * Receives external signals and resumes workflows waiting for them.\n */\n\nimport { EntityManager, raw } from '@mikro-orm/core'\nimport type { EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WorkflowInstance, WorkflowBranchInstance, WorkflowDefinition, StepInstance } from '../data/entities'\nimport { INVOKE_AGENT_SIGNAL_NAME, SUB_WORKFLOW_SIGNAL_NAME } from './activity-executor'\nimport type * as eventLoggerModule from './event-logger'\nimport type * as stepHandlerModule from './step-handler'\nimport type * as transitionHandlerModule from './transition-handler'\nimport type * as workflowExecutorModule from './workflow-executor'\nimport { resolveCodeDefinitionForInstance } from './find-definition'\nimport {\n WORKFLOW_AGENT_OUTCOME_CONTEXT_KEY,\n buildAgentOutcomeContextEntry,\n mapDispositionToAgentOutcome,\n type AgentOutcomeKind,\n} from './outcome-routing'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst logger = createLogger('workflows')\n\nexport interface SendSignalOptions {\n /**\n * Workflow instance ID\n */\n instanceId: string\n\n /**\n * Signal name to match against WAIT_FOR_SIGNAL step config\n */\n signalName: string\n\n /**\n * Optional payload to merge into workflow context\n */\n payload?: Record<string, any>\n\n /** Engine-owned outcome metadata kept separate from author-visible mappings. */\n agentOutcome?: AgentOutcomeKind\n\n /** Proposal identifier associated with `agentOutcome`, when present. */\n agentProposalId?: string\n\n /**\n * User ID sending the signal\n */\n userId?: string\n\n /**\n * Step the caller observed the instance waiting on. When set, the signal is\n * refused with `WORKFLOW_NOT_PAUSED` unless the instance is still parked on\n * exactly this step, so a delivery addressed to one wait can never consume a\n * later wait the instance has since parked on.\n */\n expectedStepId?: string\n\n /**\n * `waitVersion` the caller observed while the instance was parked. Identifies\n * the OCCURRENCE of the wait, not just its step: every park and every claim\n * increments `waitVersion` in SQL, so a delivery addressed to one occurrence\n * is refused with `WORKFLOW_NOT_PAUSED` once the instance has looped back and\n * parked on the same step again.\n */\n expectedWaitVersion?: number\n\n /**\n * Tenant/org scope\n */\n tenantId: string\n organizationId: string\n}\n\nexport class SignalError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'SignalError'\n }\n}\n\n/**\n * Send signal to workflow instance and resume execution\n */\nexport async function sendSignal(\n em: EntityManager,\n container: AwilixContainer,\n options: SendSignalOptions\n): Promise<void> {\n const {\n instanceId,\n signalName,\n payload,\n agentOutcome,\n agentProposalId,\n expectedStepId,\n expectedWaitVersion,\n userId,\n tenantId,\n organizationId,\n } = options\n\n const eventLogger = container.resolve<typeof eventLoggerModule>('eventLogger')\n const stepHandler = container.resolve<typeof stepHandlerModule>('stepHandler')\n const transitionHandler = container.resolve<typeof transitionHandlerModule>('transitionHandler')\n const workflowExecutor = container.resolve<typeof workflowExecutorModule>('workflowExecutor')\n\n // Fetch workflow instance\n const instance = await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowInstance,\n {\n id: instanceId,\n tenantId,\n organizationId,\n },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!instance) {\n throw new SignalError(\n 'Workflow instance not found',\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n // Branch-scoped signal: a FORKED instance routes the signal to the branch\n // paused at a matching WAIT_FOR_SIGNAL step.\n if (instance.status === 'FORKED') {\n const branchDefinition = (await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowDefinition,\n { id: instance.definitionId, tenantId: instance.tenantId, organizationId: instance.organizationId, deletedAt: null },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )) ?? resolveCodeDefinitionForInstance(instance)\n if (!branchDefinition) {\n throw new SignalError('Workflow definition not found', 'DEFINITION_NOT_FOUND', { definitionId: instance.definitionId })\n }\n\n const pausedBranches = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instanceId,\n status: 'PAUSED',\n tenantId,\n organizationId,\n })\n\n let targetBranch: WorkflowBranchInstance | null = null\n for (const candidate of pausedBranches) {\n const step = branchDefinition.definition.steps.find((s: any) => s.stepId === candidate.currentStepId)\n if (step?.stepType === 'WAIT_FOR_SIGNAL') {\n const candidateSignal = step.signalConfig?.signalName || step.stepId\n if (candidateSignal === signalName) {\n targetBranch = candidate\n break\n }\n }\n }\n\n if (!targetBranch) {\n throw new SignalError('No parallel branch awaiting this signal', 'NO_BRANCH_AWAITING_SIGNAL', { instanceId, signalName })\n }\n\n const branchStepInstance = await em.findOne(StepInstance, {\n workflowInstanceId: instanceId,\n branchInstanceId: targetBranch.id,\n stepId: targetBranch.currentStepId,\n status: 'ACTIVE',\n })\n\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instanceId,\n stepInstanceId: branchStepInstance?.id,\n branchInstanceId: targetBranch.id,\n eventType: 'SIGNAL_RECEIVED',\n eventData: { signalName, branch: true },\n userId,\n tenantId,\n organizationId,\n })\n\n const { resumeBranch } = await import('./parallel-handler')\n const resumed = await resumeBranch(em, {\n instanceId,\n branchInstanceId: targetBranch.id,\n tenantId,\n organizationId,\n contextMerge: payload,\n exitStepInstanceId: branchStepInstance?.id ?? null,\n exitOutput: { signalName, payload },\n })\n if (resumed) {\n await workflowExecutor.executeWorkflow(em, container, instanceId, { userId })\n }\n return\n }\n\n // Verify workflow is paused\n if (instance.status !== 'PAUSED') {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, status: instance.status }\n )\n }\n\n if (expectedStepId !== undefined && instance.currentStepId !== expectedStepId) {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, reason: 'step_changed', expectedStepId, currentStepId: instance.currentStepId }\n )\n }\n\n const observedWaitVersion = expectedWaitVersion ?? instance.waitVersion\n if (expectedWaitVersion !== undefined && instance.waitVersion !== expectedWaitVersion) {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, reason: 'wait_changed', currentStepId: instance.currentStepId }\n )\n }\n\n // Load workflow definition with tenant/org scope to check current step\n const definition = (await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowDefinition,\n {\n id: instance.definitionId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )) ?? resolveCodeDefinitionForInstance(instance)\n if (!definition) {\n throw new SignalError(\n 'Workflow definition not found',\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n // Find current step\n const currentStep = definition.definition.steps.find(\n (s: any) => s.stepId === instance.currentStepId\n )\n\n // A dedicated WAIT_FOR_SIGNAL step \u2014 OR any step that parked while declaring a\n // `signalConfig.signalName` (e.g. an AUTOMATED step whose INVOKE_AGENT activity\n // routed its proposal to a human) \u2014 can be resumed by a matching signal. The\n // resume path below (merge payload \u2192 exit step \u2192 run auto transitions) is\n // step-type-agnostic, so widening this guard is additive and safe.\n //\n // INVOKE_AGENT steps run their agent asynchronously (off the workflow\n // transaction) and park on `agent_orchestrator.proposal.ready`; recognize them\n // even when the definition omits an explicit `signalConfig.signalName` (e.g.\n // seeded blueprints not re-saved through the visual editor) so the activity\n // worker can resume them after the agent completes.\n const isInvokeAgentStep =\n !!currentStep &&\n Array.isArray(currentStep.activities) &&\n currentStep.activities.some((a: any) => a?.activityType === 'INVOKE_AGENT')\n // SUB_WORKFLOW steps park while their child instance runs its own async/agent\n // steps and resume on SUB_WORKFLOW_SIGNAL_NAME once the child terminates;\n // recognize them even without an explicit signalConfig.signalName.\n const isSubWorkflowStep = !!currentStep && currentStep.stepType === 'SUB_WORKFLOW'\n const stepCanReceiveSignal =\n !!currentStep &&\n (currentStep.stepType === 'WAIT_FOR_SIGNAL' ||\n !!currentStep.signalConfig?.signalName ||\n isInvokeAgentStep ||\n isSubWorkflowStep)\n if (!stepCanReceiveSignal) {\n throw new SignalError(\n 'Workflow is not waiting for signal',\n 'NOT_WAITING_FOR_SIGNAL',\n { instanceId, currentStepId: instance.currentStepId }\n )\n }\n\n // Check signal name matches\n const expectedSignalName =\n currentStep.signalConfig?.signalName ||\n (isInvokeAgentStep\n ? INVOKE_AGENT_SIGNAL_NAME\n : isSubWorkflowStep\n ? SUB_WORKFLOW_SIGNAL_NAME\n : currentStep.stepId)\n if (expectedSignalName !== signalName) {\n throw new SignalError(\n 'Signal name mismatch',\n 'SIGNAL_NAME_MISMATCH',\n { expected: expectedSignalName, received: signalName }\n )\n }\n\n const now = new Date()\n\n // Claim the wait before mutating anything (#7185). Every check above reads a\n // snapshot, so concurrent deliveries of the same signal all pass it; only the\n // conditional UPDATE is atomic, and exactly one delivery wins it. Pinning the\n // validated `currentStepId` stops a stale delivery from consuming a LATER wait\n // the winner has since parked on, and pinning the observed `waitVersion` stops\n // it from consuming a later occurrence of the SAME wait once a loop brings the\n // instance back to it: the claim increments `waitVersion` in SQL and every\n // re-park increments it again, whatever the wall clock says. Losers surface as\n // WORKFLOW_NOT_PAUSED, which the instance signal route already maps to 409.\n const claimed = await em.nativeUpdate(\n WorkflowInstance,\n {\n id: instance.id,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n status: 'PAUSED',\n currentStepId: instance.currentStepId,\n waitVersion: observedWaitVersion,\n },\n { status: 'RUNNING', updatedAt: now, waitVersion: raw('wait_version + 1') },\n )\n if (claimed === 0) {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, reason: 'claimed_by_concurrent_delivery' }\n )\n }\n const claimedStepId = instance.currentStepId\n const preClaimContext = instance.context\n const preClaimUpdatedAt = instance.updatedAt\n // Mirror the claimed row onto the identity-mapped entity so later flushes\n // cannot write the pre-claim status back.\n instance.status = 'RUNNING'\n\n try {\n // Merge signal payload into workflow context\n if (payload) {\n instance.context = {\n ...instance.context,\n ...payload,\n [`signal_${signalName}_payload`]: payload,\n [`signal_${signalName}_receivedAt`]: now.toISOString(),\n }\n }\n\n // Outcome routing (spec 7.2). The signal is how EVERY resolved disposition\n // reaches a parked agent step \u2014 the activity worker's auto_approved and\n // researcher resumes and the human dispose path alike \u2014 so this is the one\n // place the disposition has to be translated into the engine-owned outcome\n // marker the executor routes on. Recorded regardless of who sent the signal;\n // the author-visible `disposition` key stays untouched and unread by routing.\n if (isInvokeAgentStep && instance.currentStepId) {\n const resolvedOutcome = agentOutcome ?? mapDispositionToAgentOutcome(\n (payload as Record<string, unknown> | undefined)?.disposition,\n )\n if (resolvedOutcome) {\n const proposalId = agentProposalId\n ?? (payload as Record<string, unknown> | undefined)?.agentProposalId\n ?? (payload as Record<string, unknown> | undefined)?.proposalId\n instance.context = {\n ...instance.context,\n [WORKFLOW_AGENT_OUTCOME_CONTEXT_KEY]: buildAgentOutcomeContextEntry(\n instance.currentStepId,\n resolvedOutcome,\n typeof proposalId === 'string' ? proposalId : undefined,\n ),\n }\n }\n }\n\n instance.updatedAt = now\n\n // Log signal received event. Its flush is the first write of this delivery\n // to commit (the payload, the outcome marker and the event land together).\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'SIGNAL_RECEIVED',\n eventData: {\n signalName,\n payload,\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n } catch (error) {\n // The claim committed on its own but nothing else of this delivery did, so\n // hand the wait back: otherwise every retry would be refused as a duplicate\n // of a delivery that never landed and the signal would be lost.\n await releaseSignalClaim(em, instance, claimedStepId, preClaimContext, preClaimUpdatedAt)\n throw error\n }\n\n // Find active step instance and exit it\n const stepInstance = await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n StepInstance,\n {\n workflowInstanceId: instance.id,\n stepId: instance.currentStepId,\n status: 'ACTIVE',\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )\n\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, {\n signalName,\n payload,\n })\n }\n\n // Outcome routing (spec 7.2). A resumed agent step is advanced HERE, not by\n // the executor loop, so the wired outcome route has to be honoured here too \u2014\n // routing it in only one of the two places would silently send every\n // human-dispositioned proposal down the happy path.\n //\n // Resume from the paused wait BEFORE dispatching, exactly as the ordinary\n // resume path below does. On this path the instance is PAUSED by definition \u2014\n // it is parked on the very signal being delivered \u2014 and two things depended on\n // that being cleared first: the executor's defence-in-depth PAUSED guard stops\n // a routed run at its first step, and `instance.status === 'PAUSED'` below\n // could never mean \"this dispatch parked the run\" while the pre-existing pause\n // was still set. Every routed outcome therefore returned early and the run sat\n // on its route target, PAUSED, forever (TC-WF-051, TC-WF-052).\n instance.status = 'RUNNING'\n await em.flush()\n\n // Imported lazily rather than read off the DI-resolved executor: the resolved\n // service is the module, and reaching for a named export on it couples this\n // path to every test double that stubs only the two methods it needed.\n const { dispatchAgentOutcomeForCurrentStep } = await import('./workflow-executor')\n const outcomeDispatch = await dispatchAgentOutcomeForCurrentStep(\n em,\n container,\n instance,\n definition.definition,\n { workflowContext: instance.context, userId },\n )\n if (outcomeDispatch && outcomeDispatch.kind !== 'default') {\n if (outcomeDispatch.kind === 'failed') {\n await workflowExecutor.completeWorkflow(em, container, instance.id, 'FAILED', {\n error: outcomeDispatch.error,\n })\n return\n }\n if (outcomeDispatch.kind === 'parked') return\n // `paused` is the dispatch's own report that IT parked the run (a\n // step-through release, a wait step on the far side of the route).\n if (outcomeDispatch.paused) return\n await em.flush()\n await workflowExecutor.executeWorkflow(em, container, instance.id, { userId })\n return\n }\n\n // Find automatic transitions from current step\n const autoTransitions = (definition.definition.transitions || []).filter(\n (t: any) => t.fromStepId === instance.currentStepId && t.trigger === 'auto'\n )\n\n if (autoTransitions.length === 0) {\n // No automatic transitions, mark as RUNNING but stay at current step\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n // Find valid transitions\n const transitionContext = {\n workflowContext: instance.context,\n userId,\n }\n\n const validTransitions = await transitionHandler.findValidTransitions(\n em,\n instance,\n instance.currentStepId,\n transitionContext\n )\n\n const firstValidTransition = validTransitions.find((t) => t.isValid)\n\n if (!firstValidTransition || !firstValidTransition.transition) {\n // No valid transitions, mark as RUNNING anyway\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n // Resume from the paused wait: flip to RUNNING before executing the transition\n // and re-entering executeWorkflow. Without this the executor's defense-in-depth\n // PAUSED check stops the run after the first traversed step, so an intermediate\n // AUTOMATED step (e.g. an emit-event \"flag\") between the waiting step and END\n // leaves the instance permanently parked \u2014 and any parent sub-workflow waiting on\n // its completion never resumes. The no-transition branches above already do this.\n instance.status = 'RUNNING'\n await em.flush()\n\n // Execute transition to next step\n const transitionResult = await transitionHandler.executeTransition(\n em,\n container,\n instance,\n instance.currentStepId,\n firstValidTransition.transition.toStepId,\n { ...transitionContext, transitionId: firstValidTransition.transition.transitionId },\n )\n\n if (!transitionResult.success) {\n const { handleTransitionFailure } = await import('./workflow-executor')\n const failure = await handleTransitionFailure(em, container, instance, transitionResult, {\n evalContext: transitionContext,\n fromStepId: firstValidTransition.transition.fromStepId,\n toStepId: firstValidTransition.transition.toStepId,\n source: 'signal',\n })\n if (failure.kind === 'parked') return\n if (failure.kind === 'failed') {\n throw new SignalError(\n 'Transition failed after signal',\n 'TRANSITION_FAILED',\n { error: transitionResult.error }\n )\n }\n }\n\n // Resume workflow execution\n await workflowExecutor.executeWorkflow(em, container, instance.id, { userId })\n}\n\nasync function releaseSignalClaim(\n em: EntityManager,\n instance: WorkflowInstance,\n claimedStepId: string,\n preClaimContext: WorkflowInstance['context'],\n preClaimUpdatedAt: WorkflowInstance['updatedAt'],\n): Promise<void> {\n instance.status = 'PAUSED'\n instance.context = preClaimContext\n instance.updatedAt = preClaimUpdatedAt\n try {\n await em.nativeUpdate(\n WorkflowInstance,\n {\n id: instance.id,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n status: 'RUNNING',\n currentStepId: claimedStepId,\n },\n { status: 'PAUSED', updatedAt: new Date(), waitVersion: raw('wait_version + 1') },\n )\n } catch (releaseError) {\n logger.error('Failed to release signal claim', { instanceId: instance.id, err: releaseError })\n reportSignalError(releaseError, {\n code: 'workflows.signal_claim_release_failed',\n attributes: { instanceId: instance.id, stepId: claimedStepId },\n })\n }\n}\n\n// Reporting is best-effort: a throwing telemetry runtime must neither stop a\n// fan-out mid-loop nor replace the delivery error a caller is about to see.\nfunction reportSignalError(\n error: unknown,\n report: { code: string; attributes: Record<string, string | number | boolean | undefined> },\n): void {\n try {\n getTelemetryRuntime()?.reportError(error, { module: 'workflows', ...report })\n } catch (reportingError) {\n logger.warn('Failed to report signal error', { code: report.code, err: reportingError })\n }\n}\n\nexport type SendSignalByCorrelationKeyOptions = Omit<SendSignalOptions, 'instanceId'> & { correlationKey: string }\n\nexport interface SignalDeliveryFailure {\n instanceId: string\n code: string\n message: string\n}\n\nexport interface SendSignalByCorrelationKeyResult {\n count: number\n failures: SignalDeliveryFailure[]\n}\n\n/**\n * Send signal by correlation key (finds all waiting instances)\n *\n * Returns only the number of instances that were advanced; use\n * `sendSignalByCorrelationKeyWithResults` to learn which instances failed.\n */\nexport async function sendSignalByCorrelationKey(\n em: EntityManager,\n container: AwilixContainer,\n options: SendSignalByCorrelationKeyOptions\n): Promise<number> {\n const { count } = await sendSignalByCorrelationKeyWithResults(em, container, options)\n return count\n}\n\n/**\n * Send signal by correlation key and report every per-instance failure, so a\n * caller can tell which instances were not advanced (including deliveries that\n * lost the claim to a concurrent one, reported as `WORKFLOW_NOT_PAUSED`).\n */\nexport async function sendSignalByCorrelationKeyWithResults(\n em: EntityManager,\n container: AwilixContainer,\n options: SendSignalByCorrelationKeyOptions\n): Promise<SendSignalByCorrelationKeyResult> {\n const { correlationKey, signalName, payload, userId, tenantId, organizationId } = options\n\n // Find all paused instances with this correlation key\n const instances = await findWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowInstance,\n {\n correlationKey,\n status: 'PAUSED',\n tenantId,\n organizationId,\n },\n undefined,\n { tenantId, organizationId },\n )\n\n // Snapshot the wait each instance was listed on before delivering anything:\n // re-reads below refresh the identity-mapped entities, and a delivery must\n // only consume the wait it was addressed to, never a later one a concurrent\n // fan-out has already advanced the instance onto \u2014 nor a later occurrence of\n // the same wait it has looped back to, which only `waitVersion` tells apart.\n const targets = instances.map((instance) => ({\n id: instance.id,\n currentStepId: instance.currentStepId,\n waitVersion: instance.waitVersion,\n }))\n\n let signalsProcessed = 0\n const failures: SignalDeliveryFailure[] = []\n\n for (const instance of targets) {\n try {\n await sendSignal(em, container, {\n instanceId: instance.id,\n expectedStepId: instance.currentStepId,\n expectedWaitVersion: instance.waitVersion,\n signalName,\n payload,\n userId,\n tenantId,\n organizationId,\n })\n signalsProcessed++\n } catch (error) {\n // Log error but continue processing other instances\n logger.error('Failed to send signal to instance', { instanceId: instance.id, err: error })\n if (!isExpectedSignalRefusal(error)) {\n reportSignalError(error, {\n code: 'workflows.signal_fanout_delivery_failed',\n attributes: {\n instanceId: instance.id,\n stepId: instance.currentStepId,\n signalName,\n ...(error instanceof SignalError ? { signalErrorCode: error.code } : {}),\n },\n })\n }\n // Only a SignalError's message is a deliberate, caller-safe description;\n // anything else may carry internals and is reported generically.\n failures.push(\n error instanceof SignalError\n ? { instanceId: instance.id, code: error.code, message: error.message }\n : { instanceId: instance.id, code: SIGNAL_DELIVERY_FAILED_CODE, message: await resolveDeliveryFailedMessage() },\n )\n }\n }\n\n return { count: signalsProcessed, failures }\n}\n\nexport const SIGNAL_DELIVERY_FAILED_CODE = 'SIGNAL_DELIVERY_FAILED'\n\n// Refusals that describe the instance's state at delivery time (a concurrent\n// delivery won, the run moved on). They are outcomes, not faults, so they are\n// returned to the caller without reaching error reporting.\nconst EXPECTED_SIGNAL_REFUSAL_CODES = new Set([\n 'INSTANCE_NOT_FOUND',\n 'WORKFLOW_NOT_PAUSED',\n 'NOT_WAITING_FOR_SIGNAL',\n 'SIGNAL_NAME_MISMATCH',\n 'NO_BRANCH_AWAITING_SIGNAL',\n])\n\nfunction isExpectedSignalRefusal(error: unknown): boolean {\n return error instanceof SignalError && EXPECTED_SIGNAL_REFUSAL_CODES.has(error.code)\n}\n\nasync function resolveDeliveryFailedMessage(): Promise<string> {\n const { translate } = await resolveTranslations()\n return translate('workflows.signals.errors.deliveryFailed', 'Failed to deliver signal')\n}\n"],
5
- "mappings": "AAMA,SAAwB,WAAW;AAGnC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,kBAAkB,wBAAwB,oBAAoB,oBAAoB;AAC3F,SAAS,0BAA0B,gCAAgC;AAKnE,SAAS,wCAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,WAAW;AAqDhC,MAAM,oBAAoB,MAAM;AAAA,EACrC,YACE,SACO,MACA,SAC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AAAA,EACA;AACF,CAAC;AAED,SAAS,wBAAwB,OAAyB;AACxD,SAAO,iBAAiB,eAAe,8BAA8B,IAAI,MAAM,IAAI;AACrF;AAEA,eAAe,+BAAgD;AAC7D,QAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,SAAO,UAAU,2CAA2C,0BAA0B;AACxF;",
4
+ "sourcesContent": ["/**\n * Signal Handler Service\n *\n * Receives external signals and resumes workflows waiting for them.\n */\n\nimport { EntityManager, raw } from '@mikro-orm/core'\nimport type { EntityManager as PostgreSqlEntityManager } from '@mikro-orm/postgresql'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { WorkflowInstance, WorkflowBranchInstance, WorkflowDefinition, StepInstance } from '../data/entities'\nimport { INVOKE_AGENT_SIGNAL_NAME, SUB_WORKFLOW_SIGNAL_NAME } from './activity-executor'\nimport type * as eventLoggerModule from './event-logger'\nimport type * as stepHandlerModule from './step-handler'\nimport type * as transitionHandlerModule from './transition-handler'\nimport type * as workflowExecutorModule from './workflow-executor'\nimport { resolveCodeDefinitionForInstance } from './find-definition'\nimport {\n WORKFLOW_AGENT_OUTCOME_CONTEXT_KEY,\n buildAgentOutcomeContextEntry,\n mapDispositionToAgentOutcome,\n type AgentOutcomeKind,\n} from './outcome-routing'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst logger = createLogger('workflows')\n\nexport interface SendSignalOptions {\n /**\n * Workflow instance ID\n */\n instanceId: string\n\n /**\n * Signal name to match against WAIT_FOR_SIGNAL step config\n */\n signalName: string\n\n /**\n * Optional payload to merge into workflow context\n */\n payload?: Record<string, any>\n\n /** Engine-owned outcome metadata kept separate from author-visible mappings. */\n agentOutcome?: AgentOutcomeKind\n\n /** Proposal identifier associated with `agentOutcome`, when present. */\n agentProposalId?: string\n\n /**\n * User ID sending the signal\n */\n userId?: string\n\n /**\n * Step the caller observed the instance waiting on. When set, the signal is\n * refused with `WORKFLOW_NOT_PAUSED` unless the instance is still parked on\n * exactly this step, so a delivery addressed to one wait can never consume a\n * later wait the instance has since parked on.\n */\n expectedStepId?: string\n\n /**\n * `waitVersion` the caller observed while the instance was parked. Identifies\n * the OCCURRENCE of the wait, not just its step: every park and every claim\n * increments `waitVersion` in SQL, so a delivery addressed to one occurrence\n * is refused with `WORKFLOW_NOT_PAUSED` once the instance has looped back and\n * parked on the same step again.\n */\n expectedWaitVersion?: number\n\n /**\n * Tenant/org scope\n */\n tenantId: string\n organizationId: string\n}\n\nexport class SignalError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'SignalError'\n }\n}\n\n/**\n * Send signal to workflow instance and resume execution\n */\nexport async function sendSignal(\n em: EntityManager,\n container: AwilixContainer,\n options: SendSignalOptions\n): Promise<void> {\n const {\n instanceId,\n signalName,\n payload,\n agentOutcome,\n agentProposalId,\n expectedStepId,\n expectedWaitVersion,\n userId,\n tenantId,\n organizationId,\n } = options\n\n const eventLogger = container.resolve<typeof eventLoggerModule>('eventLogger')\n const stepHandler = container.resolve<typeof stepHandlerModule>('stepHandler')\n const transitionHandler = container.resolve<typeof transitionHandlerModule>('transitionHandler')\n const workflowExecutor = container.resolve<typeof workflowExecutorModule>('workflowExecutor')\n\n // Fetch workflow instance\n const instance = await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowInstance,\n {\n id: instanceId,\n tenantId,\n organizationId,\n },\n undefined,\n { tenantId, organizationId },\n )\n\n if (!instance) {\n throw new SignalError(\n 'Workflow instance not found',\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n // Branch-scoped signal: a FORKED instance routes the signal to the branch\n // paused at a matching WAIT_FOR_SIGNAL step.\n if (instance.status === 'FORKED') {\n const branchDefinition = (await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowDefinition,\n { id: instance.definitionId, tenantId: instance.tenantId, organizationId: instance.organizationId, deletedAt: null },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )) ?? resolveCodeDefinitionForInstance(instance)\n if (!branchDefinition) {\n throw new SignalError('Workflow definition not found', 'DEFINITION_NOT_FOUND', { definitionId: instance.definitionId })\n }\n\n const pausedBranches = await em.find(WorkflowBranchInstance, {\n workflowInstanceId: instanceId,\n status: 'PAUSED',\n tenantId,\n organizationId,\n })\n\n let targetBranch: WorkflowBranchInstance | null = null\n for (const candidate of pausedBranches) {\n const step = branchDefinition.definition.steps.find((s: any) => s.stepId === candidate.currentStepId)\n if (step?.stepType === 'WAIT_FOR_SIGNAL') {\n const candidateSignal = step.signalConfig?.signalName || step.stepId\n if (candidateSignal === signalName) {\n targetBranch = candidate\n break\n }\n }\n }\n\n if (!targetBranch) {\n throw new SignalError('No parallel branch awaiting this signal', 'NO_BRANCH_AWAITING_SIGNAL', { instanceId, signalName })\n }\n\n const branchStepInstance = await em.findOne(StepInstance, {\n workflowInstanceId: instanceId,\n branchInstanceId: targetBranch.id,\n stepId: targetBranch.currentStepId,\n status: 'ACTIVE',\n })\n\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instanceId,\n stepInstanceId: branchStepInstance?.id,\n branchInstanceId: targetBranch.id,\n eventType: 'SIGNAL_RECEIVED',\n eventData: { signalName, branch: true },\n userId,\n tenantId,\n organizationId,\n })\n\n const { resumeBranch } = await import('./parallel-handler')\n const resumed = await resumeBranch(em, {\n instanceId,\n branchInstanceId: targetBranch.id,\n tenantId,\n organizationId,\n contextMerge: payload,\n exitStepInstanceId: branchStepInstance?.id ?? null,\n exitOutput: { signalName, payload },\n })\n if (resumed) {\n await workflowExecutor.executeWorkflow(em, container, instanceId, { userId })\n }\n return\n }\n\n // Verify workflow is paused\n if (instance.status !== 'PAUSED') {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, status: instance.status }\n )\n }\n\n if (expectedStepId !== undefined && instance.currentStepId !== expectedStepId) {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, reason: 'step_changed', expectedStepId, currentStepId: instance.currentStepId }\n )\n }\n\n const observedWaitVersion = expectedWaitVersion ?? instance.waitVersion\n if (expectedWaitVersion !== undefined && instance.waitVersion !== expectedWaitVersion) {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, reason: 'wait_changed', currentStepId: instance.currentStepId }\n )\n }\n\n // Load workflow definition with tenant/org scope to check current step\n const definition = (await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowDefinition,\n {\n id: instance.definitionId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )) ?? resolveCodeDefinitionForInstance(instance)\n if (!definition) {\n throw new SignalError(\n 'Workflow definition not found',\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n // Find current step\n const currentStep = definition.definition.steps.find(\n (s: any) => s.stepId === instance.currentStepId\n )\n\n // A dedicated WAIT_FOR_SIGNAL step \u2014 OR any step that parked while declaring a\n // `signalConfig.signalName` (e.g. an AUTOMATED step whose INVOKE_AGENT activity\n // routed its proposal to a human) \u2014 can be resumed by a matching signal. The\n // resume path below (merge payload \u2192 exit step \u2192 run auto transitions) is\n // step-type-agnostic, so widening this guard is additive and safe.\n //\n // INVOKE_AGENT steps run their agent asynchronously (off the workflow\n // transaction) and park on `agent_orchestrator.proposal.ready`; recognize them\n // even when the definition omits an explicit `signalConfig.signalName` (e.g.\n // seeded blueprints not re-saved through the visual editor) so the activity\n // worker can resume them after the agent completes.\n const isInvokeAgentStep =\n !!currentStep &&\n Array.isArray(currentStep.activities) &&\n currentStep.activities.some((a: any) => a?.activityType === 'INVOKE_AGENT')\n // SUB_WORKFLOW steps park while their child instance runs its own async/agent\n // steps and resume on SUB_WORKFLOW_SIGNAL_NAME once the child terminates;\n // recognize them even without an explicit signalConfig.signalName.\n const isSubWorkflowStep = !!currentStep && currentStep.stepType === 'SUB_WORKFLOW'\n const stepCanReceiveSignal =\n !!currentStep &&\n (currentStep.stepType === 'WAIT_FOR_SIGNAL' ||\n !!currentStep.signalConfig?.signalName ||\n isInvokeAgentStep ||\n isSubWorkflowStep)\n if (!stepCanReceiveSignal) {\n throw new SignalError(\n 'Workflow is not waiting for signal',\n 'NOT_WAITING_FOR_SIGNAL',\n { instanceId, currentStepId: instance.currentStepId }\n )\n }\n\n // Check signal name matches\n const expectedSignalName =\n currentStep.signalConfig?.signalName ||\n (isInvokeAgentStep\n ? INVOKE_AGENT_SIGNAL_NAME\n : isSubWorkflowStep\n ? SUB_WORKFLOW_SIGNAL_NAME\n : currentStep.stepId)\n if (expectedSignalName !== signalName) {\n throw new SignalError(\n 'Signal name mismatch',\n 'SIGNAL_NAME_MISMATCH',\n { expected: expectedSignalName, received: signalName }\n )\n }\n\n const now = new Date()\n\n // Claim the wait before mutating anything (#7185). Every check above reads a\n // snapshot, so concurrent deliveries of the same signal all pass it; only the\n // conditional UPDATE is atomic, and exactly one delivery wins it. Pinning the\n // validated `currentStepId` stops a stale delivery from consuming a LATER wait\n // the winner has since parked on, and pinning the observed `waitVersion` stops\n // it from consuming a later occurrence of the SAME wait once a loop brings the\n // instance back to it: the claim increments `waitVersion` in SQL and every\n // re-park increments it again, whatever the wall clock says. Losers surface as\n // WORKFLOW_NOT_PAUSED, which the instance signal route already maps to 409.\n const claimed = await em.nativeUpdate(\n WorkflowInstance,\n {\n id: instance.id,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n status: 'PAUSED',\n currentStepId: instance.currentStepId,\n waitVersion: observedWaitVersion,\n },\n { status: 'RUNNING', updatedAt: now, waitVersion: raw('wait_version + 1') },\n )\n if (claimed === 0) {\n throw new SignalError(\n 'Workflow is not paused',\n 'WORKFLOW_NOT_PAUSED',\n { instanceId, reason: 'claimed_by_concurrent_delivery' }\n )\n }\n const claimedStepId = instance.currentStepId\n const preClaimContext = instance.context\n const preClaimUpdatedAt = instance.updatedAt\n // Mirror the claimed row onto the identity-mapped entity so later flushes\n // cannot write the pre-claim status back.\n instance.status = 'RUNNING'\n\n try {\n // Merge signal payload into workflow context\n if (payload) {\n instance.context = {\n ...instance.context,\n ...payload,\n [`signal_${signalName}_payload`]: payload,\n [`signal_${signalName}_receivedAt`]: now.toISOString(),\n }\n }\n\n // Outcome routing (spec 7.2). The signal is how EVERY resolved disposition\n // reaches a parked agent step \u2014 the activity worker's auto_approved and\n // researcher resumes and the human dispose path alike \u2014 so this is the one\n // place the disposition has to be translated into the engine-owned outcome\n // marker the executor routes on. Recorded regardless of who sent the signal;\n // the author-visible `disposition` key stays untouched and unread by routing.\n if (isInvokeAgentStep && instance.currentStepId) {\n const resolvedOutcome = agentOutcome ?? mapDispositionToAgentOutcome(\n (payload as Record<string, unknown> | undefined)?.disposition,\n )\n if (resolvedOutcome) {\n const proposalId = agentProposalId\n ?? (payload as Record<string, unknown> | undefined)?.agentProposalId\n ?? (payload as Record<string, unknown> | undefined)?.proposalId\n instance.context = {\n ...instance.context,\n [WORKFLOW_AGENT_OUTCOME_CONTEXT_KEY]: buildAgentOutcomeContextEntry(\n instance.currentStepId,\n resolvedOutcome,\n typeof proposalId === 'string' ? proposalId : undefined,\n ),\n }\n }\n }\n\n instance.updatedAt = now\n\n // Log signal received event. Its flush is the first write of this delivery\n // to commit (the payload, the outcome marker and the event land together).\n await eventLogger.logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'SIGNAL_RECEIVED',\n eventData: {\n signalName,\n payload,\n },\n userId,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n } catch (error) {\n // The claim committed on its own but nothing else of this delivery did, so\n // hand the wait back: otherwise every retry would be refused as a duplicate\n // of a delivery that never landed and the signal would be lost.\n await releaseSignalClaim(em, instance, claimedStepId, preClaimContext, preClaimUpdatedAt)\n throw error\n }\n\n // Find active step instance and exit it\n const stepInstance = await findOneWithDecryption(\n em as PostgreSqlEntityManager,\n StepInstance,\n {\n workflowInstanceId: instance.id,\n stepId: instance.currentStepId,\n status: 'ACTIVE',\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n },\n undefined,\n { tenantId: instance.tenantId, organizationId: instance.organizationId },\n )\n\n if (stepInstance) {\n await stepHandler.exitStep(em, stepInstance, {\n signalName,\n payload,\n })\n }\n\n // Outcome routing (spec 7.2). A resumed agent step is advanced HERE, not by\n // the executor loop, so the wired outcome route has to be honoured here too \u2014\n // routing it in only one of the two places would silently send every\n // human-dispositioned proposal down the happy path.\n //\n // Resume from the paused wait BEFORE dispatching, exactly as the ordinary\n // resume path below does. On this path the instance is PAUSED by definition \u2014\n // it is parked on the very signal being delivered \u2014 and two things depended on\n // that being cleared first: the executor's defence-in-depth PAUSED guard stops\n // a routed run at its first step, and `instance.status === 'PAUSED'` below\n // could never mean \"this dispatch parked the run\" while the pre-existing pause\n // was still set. Every routed outcome therefore returned early and the run sat\n // on its route target, PAUSED, forever (TC-WF-051, TC-WF-052).\n instance.status = 'RUNNING'\n await em.flush()\n\n // Imported lazily rather than read off the DI-resolved executor: the resolved\n // service is the module, and reaching for a named export on it couples this\n // path to every test double that stubs only the two methods it needed.\n const { dispatchAgentOutcomeForCurrentStep } = await import('./workflow-executor')\n const outcomeDispatch = await dispatchAgentOutcomeForCurrentStep(\n em,\n container,\n instance,\n definition.definition,\n { workflowContext: instance.context, userId },\n )\n if (outcomeDispatch && outcomeDispatch.kind !== 'default') {\n if (outcomeDispatch.kind === 'failed') {\n await workflowExecutor.completeWorkflow(em, container, instance.id, 'FAILED', {\n error: outcomeDispatch.error,\n })\n return\n }\n if (outcomeDispatch.kind === 'parked') return\n // `paused` is the dispatch's own report that IT parked the run (a\n // step-through release, a wait step on the far side of the route).\n if (outcomeDispatch.paused) return\n await em.flush()\n await workflowExecutor.executeWorkflow(em, container, instance.id, { userId })\n return\n }\n\n // Find automatic transitions from current step\n const autoTransitions = (definition.definition.transitions || []).filter(\n (t: any) => t.fromStepId === instance.currentStepId && t.trigger === 'auto'\n )\n\n if (autoTransitions.length === 0) {\n // No automatic transitions, mark as RUNNING but stay at current step\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n // Find valid transitions\n const transitionContext = {\n container,\n workflowContext: instance.context,\n userId,\n }\n\n const validTransitions = await transitionHandler.findValidTransitions(\n em,\n instance,\n instance.currentStepId,\n transitionContext\n )\n\n const firstValidTransition = validTransitions.find((t) => t.isValid)\n\n if (!firstValidTransition || !firstValidTransition.transition) {\n // No valid transitions, mark as RUNNING anyway\n instance.status = 'RUNNING'\n await em.flush()\n return\n }\n\n // Resume from the paused wait: flip to RUNNING before executing the transition\n // and re-entering executeWorkflow. Without this the executor's defense-in-depth\n // PAUSED check stops the run after the first traversed step, so an intermediate\n // AUTOMATED step (e.g. an emit-event \"flag\") between the waiting step and END\n // leaves the instance permanently parked \u2014 and any parent sub-workflow waiting on\n // its completion never resumes. The no-transition branches above already do this.\n instance.status = 'RUNNING'\n await em.flush()\n\n // Execute transition to next step\n const transitionResult = await transitionHandler.executeTransition(\n em,\n container,\n instance,\n instance.currentStepId,\n firstValidTransition.transition.toStepId,\n { ...transitionContext, transitionId: firstValidTransition.transition.transitionId },\n )\n\n if (!transitionResult.success) {\n const { handleTransitionFailure } = await import('./workflow-executor')\n const failure = await handleTransitionFailure(em, container, instance, transitionResult, {\n evalContext: transitionContext,\n fromStepId: firstValidTransition.transition.fromStepId,\n toStepId: firstValidTransition.transition.toStepId,\n source: 'signal',\n })\n if (failure.kind === 'parked') return\n if (failure.kind === 'failed') {\n throw new SignalError(\n 'Transition failed after signal',\n 'TRANSITION_FAILED',\n { error: transitionResult.error }\n )\n }\n }\n\n // Resume workflow execution\n await workflowExecutor.executeWorkflow(em, container, instance.id, { userId })\n}\n\nasync function releaseSignalClaim(\n em: EntityManager,\n instance: WorkflowInstance,\n claimedStepId: string,\n preClaimContext: WorkflowInstance['context'],\n preClaimUpdatedAt: WorkflowInstance['updatedAt'],\n): Promise<void> {\n instance.status = 'PAUSED'\n instance.context = preClaimContext\n instance.updatedAt = preClaimUpdatedAt\n try {\n await em.nativeUpdate(\n WorkflowInstance,\n {\n id: instance.id,\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n status: 'RUNNING',\n currentStepId: claimedStepId,\n },\n { status: 'PAUSED', updatedAt: new Date(), waitVersion: raw('wait_version + 1') },\n )\n } catch (releaseError) {\n logger.error('Failed to release signal claim', { instanceId: instance.id, err: releaseError })\n reportSignalError(releaseError, {\n code: 'workflows.signal_claim_release_failed',\n attributes: { instanceId: instance.id, stepId: claimedStepId },\n })\n }\n}\n\n// Reporting is best-effort: a throwing telemetry runtime must neither stop a\n// fan-out mid-loop nor replace the delivery error a caller is about to see.\nfunction reportSignalError(\n error: unknown,\n report: { code: string; attributes: Record<string, string | number | boolean | undefined> },\n): void {\n try {\n getTelemetryRuntime()?.reportError(error, { module: 'workflows', ...report })\n } catch (reportingError) {\n logger.warn('Failed to report signal error', { code: report.code, err: reportingError })\n }\n}\n\nexport type SendSignalByCorrelationKeyOptions = Omit<SendSignalOptions, 'instanceId'> & { correlationKey: string }\n\nexport interface SignalDeliveryFailure {\n instanceId: string\n code: string\n message: string\n}\n\nexport interface SendSignalByCorrelationKeyResult {\n count: number\n failures: SignalDeliveryFailure[]\n}\n\n/**\n * Send signal by correlation key (finds all waiting instances)\n *\n * Returns only the number of instances that were advanced; use\n * `sendSignalByCorrelationKeyWithResults` to learn which instances failed.\n */\nexport async function sendSignalByCorrelationKey(\n em: EntityManager,\n container: AwilixContainer,\n options: SendSignalByCorrelationKeyOptions\n): Promise<number> {\n const { count } = await sendSignalByCorrelationKeyWithResults(em, container, options)\n return count\n}\n\n/**\n * Send signal by correlation key and report every per-instance failure, so a\n * caller can tell which instances were not advanced (including deliveries that\n * lost the claim to a concurrent one, reported as `WORKFLOW_NOT_PAUSED`).\n */\nexport async function sendSignalByCorrelationKeyWithResults(\n em: EntityManager,\n container: AwilixContainer,\n options: SendSignalByCorrelationKeyOptions\n): Promise<SendSignalByCorrelationKeyResult> {\n const { correlationKey, signalName, payload, userId, tenantId, organizationId } = options\n\n // Find all paused instances with this correlation key\n const instances = await findWithDecryption(\n em as PostgreSqlEntityManager,\n WorkflowInstance,\n {\n correlationKey,\n status: 'PAUSED',\n tenantId,\n organizationId,\n },\n undefined,\n { tenantId, organizationId },\n )\n\n // Snapshot the wait each instance was listed on before delivering anything:\n // re-reads below refresh the identity-mapped entities, and a delivery must\n // only consume the wait it was addressed to, never a later one a concurrent\n // fan-out has already advanced the instance onto \u2014 nor a later occurrence of\n // the same wait it has looped back to, which only `waitVersion` tells apart.\n const targets = instances.map((instance) => ({\n id: instance.id,\n currentStepId: instance.currentStepId,\n waitVersion: instance.waitVersion,\n }))\n\n let signalsProcessed = 0\n const failures: SignalDeliveryFailure[] = []\n\n for (const instance of targets) {\n try {\n await sendSignal(em, container, {\n instanceId: instance.id,\n expectedStepId: instance.currentStepId,\n expectedWaitVersion: instance.waitVersion,\n signalName,\n payload,\n userId,\n tenantId,\n organizationId,\n })\n signalsProcessed++\n } catch (error) {\n // Log error but continue processing other instances\n logger.error('Failed to send signal to instance', { instanceId: instance.id, err: error })\n if (!isExpectedSignalRefusal(error)) {\n reportSignalError(error, {\n code: 'workflows.signal_fanout_delivery_failed',\n attributes: {\n instanceId: instance.id,\n stepId: instance.currentStepId,\n signalName,\n ...(error instanceof SignalError ? { signalErrorCode: error.code } : {}),\n },\n })\n }\n // Only a SignalError's message is a deliberate, caller-safe description;\n // anything else may carry internals and is reported generically.\n failures.push(\n error instanceof SignalError\n ? { instanceId: instance.id, code: error.code, message: error.message }\n : { instanceId: instance.id, code: SIGNAL_DELIVERY_FAILED_CODE, message: await resolveDeliveryFailedMessage() },\n )\n }\n }\n\n return { count: signalsProcessed, failures }\n}\n\nexport const SIGNAL_DELIVERY_FAILED_CODE = 'SIGNAL_DELIVERY_FAILED'\n\n// Refusals that describe the instance's state at delivery time (a concurrent\n// delivery won, the run moved on). They are outcomes, not faults, so they are\n// returned to the caller without reaching error reporting.\nconst EXPECTED_SIGNAL_REFUSAL_CODES = new Set([\n 'INSTANCE_NOT_FOUND',\n 'WORKFLOW_NOT_PAUSED',\n 'NOT_WAITING_FOR_SIGNAL',\n 'SIGNAL_NAME_MISMATCH',\n 'NO_BRANCH_AWAITING_SIGNAL',\n])\n\nfunction isExpectedSignalRefusal(error: unknown): boolean {\n return error instanceof SignalError && EXPECTED_SIGNAL_REFUSAL_CODES.has(error.code)\n}\n\nasync function resolveDeliveryFailedMessage(): Promise<string> {\n const { translate } = await resolveTranslations()\n return translate('workflows.signals.errors.deliveryFailed', 'Failed to deliver signal')\n}\n"],
5
+ "mappings": "AAMA,SAAwB,WAAW;AAGnC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,kBAAkB,wBAAwB,oBAAoB,oBAAoB;AAC3F,SAAS,0BAA0B,gCAAgC;AAKnE,SAAS,wCAAwC;AACjD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,WAAW;AAqDhC,MAAM,oBAAoB,MAAM;AAAA,EACrC,YACE,SACO,MACA,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAKA,eAAsB,WACpB,IACA,WACA,SACe;AACf,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,QAAM,cAAc,UAAU,QAAkC,aAAa;AAC7E,QAAM,cAAc,UAAU,QAAkC,aAAa;AAC7E,QAAM,oBAAoB,UAAU,QAAwC,mBAAmB;A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