@memberjunction/core-entities-server 6.2.2 → 6.3.0-edge.1

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 (200) hide show
  1. package/README.md +19 -0
  2. package/dist/custom/AnchoredConversationReadSecurityHook.d.ts +1 -14
  3. package/dist/custom/AnchoredConversationReadSecurityHook.d.ts.map +1 -1
  4. package/dist/custom/AnchoredConversationReadSecurityHook.js +43 -5
  5. package/dist/custom/AnchoredConversationReadSecurityHook.js.map +1 -1
  6. package/dist/custom/ArtifactSecurityHookHelpers.d.ts +223 -0
  7. package/dist/custom/ArtifactSecurityHookHelpers.d.ts.map +1 -0
  8. package/dist/custom/ArtifactSecurityHookHelpers.js +1402 -0
  9. package/dist/custom/ArtifactSecurityHookHelpers.js.map +1 -0
  10. package/dist/custom/ConversationAndCommentDrivers.d.ts +82 -0
  11. package/dist/custom/ConversationAndCommentDrivers.d.ts.map +1 -0
  12. package/dist/custom/ConversationAndCommentDrivers.js +543 -0
  13. package/dist/custom/ConversationAndCommentDrivers.js.map +1 -0
  14. package/dist/custom/FieldSuggestionRecordChangeHook.d.ts +17 -0
  15. package/dist/custom/FieldSuggestionRecordChangeHook.d.ts.map +1 -0
  16. package/dist/custom/FieldSuggestionRecordChangeHook.js +142 -0
  17. package/dist/custom/FieldSuggestionRecordChangeHook.js.map +1 -0
  18. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts +11 -0
  19. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.d.ts.map +1 -1
  20. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js +41 -0
  21. package/dist/custom/MJAIAgentUserPolicyEntityServer.server.js.map +1 -1
  22. package/dist/custom/MJAIBridgeAgentIdentityEntityServer.server.js +2 -2
  23. package/dist/custom/MJAIBridgeAgentIdentityEntityServer.server.js.map +1 -1
  24. package/dist/custom/MJAIPromptRunEntityServer.server.d.ts +21 -0
  25. package/dist/custom/MJAIPromptRunEntityServer.server.d.ts.map +1 -1
  26. package/dist/custom/MJAIPromptRunEntityServer.server.js +76 -5
  27. package/dist/custom/MJAIPromptRunEntityServer.server.js.map +1 -1
  28. package/dist/custom/MJArtifactEntityServer.server.d.ts +38 -0
  29. package/dist/custom/MJArtifactEntityServer.server.d.ts.map +1 -0
  30. package/dist/custom/MJArtifactEntityServer.server.js +436 -0
  31. package/dist/custom/MJArtifactEntityServer.server.js.map +1 -0
  32. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.d.ts +32 -0
  33. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.d.ts.map +1 -0
  34. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.js +434 -0
  35. package/dist/custom/MJArtifactGuestShareLinkEntityServer.server.js.map +1 -0
  36. package/dist/custom/MJArtifactPermissionEntityServer.server.d.ts +18 -0
  37. package/dist/custom/MJArtifactPermissionEntityServer.server.d.ts.map +1 -0
  38. package/dist/custom/MJArtifactPermissionEntityServer.server.js +194 -0
  39. package/dist/custom/MJArtifactPermissionEntityServer.server.js.map +1 -0
  40. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.d.ts +22 -0
  41. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.d.ts.map +1 -0
  42. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.js +312 -0
  43. package/dist/custom/MJArtifactVersionAttributeEntityServer.server.js.map +1 -0
  44. package/dist/custom/MJArtifactVersionEntityServer.server.d.ts +76 -12
  45. package/dist/custom/MJArtifactVersionEntityServer.server.d.ts.map +1 -1
  46. package/dist/custom/MJArtifactVersionEntityServer.server.js +934 -55
  47. package/dist/custom/MJArtifactVersionEntityServer.server.js.map +1 -1
  48. package/dist/custom/MJArtifactWorkingStateEntityServer.server.d.ts +42 -0
  49. package/dist/custom/MJArtifactWorkingStateEntityServer.server.d.ts.map +1 -0
  50. package/dist/custom/MJArtifactWorkingStateEntityServer.server.js +547 -0
  51. package/dist/custom/MJArtifactWorkingStateEntityServer.server.js.map +1 -0
  52. package/dist/custom/MJCollectionArtifactEntityServer.server.d.ts +36 -0
  53. package/dist/custom/MJCollectionArtifactEntityServer.server.d.ts.map +1 -0
  54. package/dist/custom/MJCollectionArtifactEntityServer.server.js +533 -0
  55. package/dist/custom/MJCollectionArtifactEntityServer.server.js.map +1 -0
  56. package/dist/custom/MJCollectionEntityServer.server.d.ts +23 -0
  57. package/dist/custom/MJCollectionEntityServer.server.d.ts.map +1 -0
  58. package/dist/custom/MJCollectionEntityServer.server.js +555 -0
  59. package/dist/custom/MJCollectionEntityServer.server.js.map +1 -0
  60. package/dist/custom/MJCollectionPermissionEntityServer.server.d.ts +18 -0
  61. package/dist/custom/MJCollectionPermissionEntityServer.server.d.ts.map +1 -0
  62. package/dist/custom/MJCollectionPermissionEntityServer.server.js +196 -0
  63. package/dist/custom/MJCollectionPermissionEntityServer.server.js.map +1 -0
  64. package/dist/custom/MJCommentEntityServer.server.d.ts +19 -0
  65. package/dist/custom/MJCommentEntityServer.server.d.ts.map +1 -0
  66. package/dist/custom/MJCommentEntityServer.server.js +137 -0
  67. package/dist/custom/MJCommentEntityServer.server.js.map +1 -0
  68. package/dist/custom/MJConversationEntityServer.server.d.ts +11 -4
  69. package/dist/custom/MJConversationEntityServer.server.d.ts.map +1 -1
  70. package/dist/custom/MJConversationEntityServer.server.js +75 -11
  71. package/dist/custom/MJConversationEntityServer.server.js.map +1 -1
  72. package/dist/custom/MJEntityEntityServer.server.d.ts +9 -0
  73. package/dist/custom/MJEntityEntityServer.server.d.ts.map +1 -1
  74. package/dist/custom/MJEntityEntityServer.server.js +31 -2
  75. package/dist/custom/MJEntityEntityServer.server.js.map +1 -1
  76. package/dist/custom/MJFieldSuggestionEntityServer.server.d.ts +29 -0
  77. package/dist/custom/MJFieldSuggestionEntityServer.server.d.ts.map +1 -0
  78. package/dist/custom/MJFieldSuggestionEntityServer.server.js +249 -0
  79. package/dist/custom/MJFieldSuggestionEntityServer.server.js.map +1 -0
  80. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts +197 -0
  81. package/dist/custom/MJGraphEdgeEntityServer.server.d.ts.map +1 -0
  82. package/dist/custom/MJGraphEdgeEntityServer.server.js +459 -0
  83. package/dist/custom/MJGraphEdgeEntityServer.server.js.map +1 -0
  84. package/dist/custom/MJGraphEdgeProviderEntityServer.server.d.ts +22 -0
  85. package/dist/custom/MJGraphEdgeProviderEntityServer.server.d.ts.map +1 -0
  86. package/dist/custom/MJGraphEdgeProviderEntityServer.server.js +85 -0
  87. package/dist/custom/MJGraphEdgeProviderEntityServer.server.js.map +1 -0
  88. package/dist/custom/MJGraphEdgeTypeEntityServer.server.d.ts +21 -0
  89. package/dist/custom/MJGraphEdgeTypeEntityServer.server.d.ts.map +1 -0
  90. package/dist/custom/MJGraphEdgeTypeEntityServer.server.js +88 -0
  91. package/dist/custom/MJGraphEdgeTypeEntityServer.server.js.map +1 -0
  92. package/dist/custom/MJListEntityServer.server.d.ts +26 -10
  93. package/dist/custom/MJListEntityServer.server.d.ts.map +1 -1
  94. package/dist/custom/MJListEntityServer.server.js +118 -20
  95. package/dist/custom/MJListEntityServer.server.js.map +1 -1
  96. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.d.ts +39 -0
  97. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.d.ts.map +1 -0
  98. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.js +124 -0
  99. package/dist/custom/MJMLEvaluationProtocolEntityServer.server.js.map +1 -0
  100. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts +124 -0
  101. package/dist/custom/MJMLPredictionUnitEntityServer.server.d.ts.map +1 -0
  102. package/dist/custom/MJMLPredictionUnitEntityServer.server.js +214 -0
  103. package/dist/custom/MJMLPredictionUnitEntityServer.server.js.map +1 -0
  104. package/dist/custom/MJMLTrainingPipelineEntityServer.server.d.ts +101 -1
  105. package/dist/custom/MJMLTrainingPipelineEntityServer.server.d.ts.map +1 -1
  106. package/dist/custom/MJMLTrainingPipelineEntityServer.server.js +266 -12
  107. package/dist/custom/MJMLTrainingPipelineEntityServer.server.js.map +1 -1
  108. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.d.ts +14 -0
  109. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.d.ts.map +1 -0
  110. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.js +42 -0
  111. package/dist/custom/MJMLTrainingSnapshotEntityServer.server.js.map +1 -0
  112. package/dist/custom/MJProjectEntityServer.server.d.ts +28 -2
  113. package/dist/custom/MJProjectEntityServer.server.d.ts.map +1 -1
  114. package/dist/custom/MJProjectEntityServer.server.js +115 -2
  115. package/dist/custom/MJProjectEntityServer.server.js.map +1 -1
  116. package/dist/custom/MJQueryEntityServer.server.d.ts +10 -6
  117. package/dist/custom/MJQueryEntityServer.server.d.ts.map +1 -1
  118. package/dist/custom/MJQueryEntityServer.server.js +27 -16
  119. package/dist/custom/MJQueryEntityServer.server.js.map +1 -1
  120. package/dist/custom/MJScheduledJobEntityServer.server.d.ts +27 -0
  121. package/dist/custom/MJScheduledJobEntityServer.server.d.ts.map +1 -0
  122. package/dist/custom/MJScheduledJobEntityServer.server.js +56 -0
  123. package/dist/custom/MJScheduledJobEntityServer.server.js.map +1 -0
  124. package/dist/custom/MJScopedNotificationConfigEntityServer.server.d.ts +15 -0
  125. package/dist/custom/MJScopedNotificationConfigEntityServer.server.d.ts.map +1 -0
  126. package/dist/custom/MJScopedNotificationConfigEntityServer.server.js +48 -0
  127. package/dist/custom/MJScopedNotificationConfigEntityServer.server.js.map +1 -0
  128. package/dist/custom/MJTagEntityServer.server.d.ts +11 -1
  129. package/dist/custom/MJTagEntityServer.server.d.ts.map +1 -1
  130. package/dist/custom/MJTagEntityServer.server.js +28 -3
  131. package/dist/custom/MJTagEntityServer.server.js.map +1 -1
  132. package/dist/custom/MJTaskDependencyEntityServer.server.d.ts +24 -0
  133. package/dist/custom/MJTaskDependencyEntityServer.server.d.ts.map +1 -0
  134. package/dist/custom/MJTaskDependencyEntityServer.server.js +75 -0
  135. package/dist/custom/MJTaskDependencyEntityServer.server.js.map +1 -0
  136. package/dist/custom/MJTaskEntityServer.server.d.ts +148 -0
  137. package/dist/custom/MJTaskEntityServer.server.d.ts.map +1 -0
  138. package/dist/custom/MJTaskEntityServer.server.js +413 -0
  139. package/dist/custom/MJTaskEntityServer.server.js.map +1 -0
  140. package/dist/custom/MJUserEntityServer.server.d.ts +2 -1
  141. package/dist/custom/MJUserEntityServer.server.d.ts.map +1 -1
  142. package/dist/custom/MJUserEntityServer.server.js +2 -1
  143. package/dist/custom/MJUserEntityServer.server.js.map +1 -1
  144. package/dist/custom/MJUserViewEntityServer.server.d.ts +8 -2
  145. package/dist/custom/MJUserViewEntityServer.server.d.ts.map +1 -1
  146. package/dist/custom/MJUserViewEntityServer.server.js +25 -12
  147. package/dist/custom/MJUserViewEntityServer.server.js.map +1 -1
  148. package/dist/custom/RestrictedFieldCommentClassifier.d.ts +9 -3
  149. package/dist/custom/RestrictedFieldCommentClassifier.d.ts.map +1 -1
  150. package/dist/custom/RestrictedFieldCommentClassifier.js +91 -15
  151. package/dist/custom/RestrictedFieldCommentClassifier.js.map +1 -1
  152. package/dist/custom/RestrictedFieldDecision.d.ts +121 -0
  153. package/dist/custom/RestrictedFieldDecision.d.ts.map +1 -0
  154. package/dist/custom/RestrictedFieldDecision.js +168 -0
  155. package/dist/custom/RestrictedFieldDecision.js.map +1 -0
  156. package/dist/custom/SpreadsheetWorkerEntry.d.ts +25 -0
  157. package/dist/custom/SpreadsheetWorkerEntry.d.ts.map +1 -0
  158. package/dist/custom/SpreadsheetWorkerEntry.js +37 -0
  159. package/dist/custom/SpreadsheetWorkerEntry.js.map +1 -0
  160. package/dist/custom/SpreadsheetWorkerRunner.d.ts +45 -0
  161. package/dist/custom/SpreadsheetWorkerRunner.d.ts.map +1 -0
  162. package/dist/custom/SpreadsheetWorkerRunner.js +243 -0
  163. package/dist/custom/SpreadsheetWorkerRunner.js.map +1 -0
  164. package/dist/custom/fieldPermissionDelta.d.ts +15 -1
  165. package/dist/custom/fieldPermissionDelta.d.ts.map +1 -1
  166. package/dist/custom/fieldPermissionDelta.js +28 -7
  167. package/dist/custom/fieldPermissionDelta.js.map +1 -1
  168. package/dist/custom/fieldPermissionReconciler.d.ts +4 -1
  169. package/dist/custom/fieldPermissionReconciler.d.ts.map +1 -1
  170. package/dist/custom/fieldPermissionReconciler.js +4 -2
  171. package/dist/custom/fieldPermissionReconciler.js.map +1 -1
  172. package/dist/custom/list-refresh/ListRefreshRoutine.d.ts +40 -0
  173. package/dist/custom/list-refresh/ListRefreshRoutine.d.ts.map +1 -0
  174. package/dist/custom/list-refresh/ListRefreshRoutine.js +114 -0
  175. package/dist/custom/list-refresh/ListRefreshRoutine.js.map +1 -0
  176. package/dist/custom/query-extraction/childRowWriter.d.ts +2 -2
  177. package/dist/custom/query-extraction/childRowWriter.d.ts.map +1 -1
  178. package/dist/custom/query-extraction/childRowWriter.js +7 -2
  179. package/dist/custom/query-extraction/childRowWriter.js.map +1 -1
  180. package/dist/custom/query-extraction/describeFacts.d.ts +2 -0
  181. package/dist/custom/query-extraction/describeFacts.d.ts.map +1 -1
  182. package/dist/custom/query-extraction/describeFacts.js +17 -10
  183. package/dist/custom/query-extraction/describeFacts.js.map +1 -1
  184. package/dist/custom/query-extraction/descriptionPass.d.ts.map +1 -1
  185. package/dist/custom/query-extraction/descriptionPass.js +4 -1
  186. package/dist/custom/query-extraction/descriptionPass.js.map +1 -1
  187. package/dist/custom/query-extraction/extractQuery.js +5 -3
  188. package/dist/custom/query-extraction/extractQuery.js.map +1 -1
  189. package/dist/custom/query-extraction/extractionTypes.d.ts +5 -0
  190. package/dist/custom/query-extraction/extractionTypes.d.ts.map +1 -1
  191. package/dist/custom/sessionConfigGuard.d.ts +7 -0
  192. package/dist/custom/sessionConfigGuard.d.ts.map +1 -1
  193. package/dist/custom/sessionConfigGuard.js +13 -1
  194. package/dist/custom/sessionConfigGuard.js.map +1 -1
  195. package/dist/index.d.ts +25 -0
  196. package/dist/index.d.ts.map +1 -1
  197. package/dist/index.js +34 -0
  198. package/dist/index.js.map +1 -1
  199. package/dist/tsconfig.tsbuildinfo +1 -0
  200. package/package.json +31 -30
@@ -0,0 +1,75 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseEntity, BaseEntityResult, ServerOperationScopeManager, } from '@memberjunction/core';
8
+ import { RegisterClass } from '@memberjunction/global';
9
+ import { MJTaskDependencyEntity } from '@memberjunction/core-entities';
10
+ import { TASK_GRAPH_RUNTIME_SECURITY_OPERATION } from '@memberjunction/ai-core-plus';
11
+ import { IsWorkflowStepTask, ResolveWorkflowTaskTypeID } from './MJTaskEntityServer.server.js';
12
+ /**
13
+ * Server-side `MJ: Task Dependencies` entity: a workflow's edges are the task-graph service's.
14
+ *
15
+ * An edge decides when a step may run and what it reads: deleting the one into a send step would release it without
16
+ * the approval step before it, and adding one would hand a step another's output. So an edge that gates a workflow
17
+ * step, before or after the write, is created, changed or deleted only inside the dispatcher's runtime-security scope
18
+ * ({@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}), where the task-graph service writes a graph's edges. An edge that gates no
19
+ * workflow step, an ordinary task waiting on one included, is left alone.
20
+ */
21
+ let MJTaskDependencyEntityServer = class MJTaskDependencyEntityServer extends MJTaskDependencyEntity {
22
+ async Save(options) {
23
+ if (!this.inDispatcherScope() && (await this.touchesWorkflowStep())) {
24
+ return this.refuse(this.IsSaved ? 'update' : 'create');
25
+ }
26
+ return super.Save(options);
27
+ }
28
+ async Delete(options) {
29
+ if (!this.inDispatcherScope() && (await this.touchesWorkflowStep())) {
30
+ return this.refuse('delete');
31
+ }
32
+ return super.Delete(options);
33
+ }
34
+ /**
35
+ * Whether the edge gates a step of a workflow: its `TaskID`, as stored or as this write leaves it, is one. That is the
36
+ * end the dispatcher reads (a step's prerequisites); an ordinary task waiting on a step changes nothing it runs.
37
+ */
38
+ async touchesWorkflowStep() {
39
+ const ends = new Set();
40
+ const entityField = this.GetFieldByName('TaskID');
41
+ for (const value of [entityField?.Value, this.IsSaved ? entityField?.OldValue : undefined]) {
42
+ if (typeof value === 'string' && value)
43
+ ends.add(value.toUpperCase());
44
+ }
45
+ if (ends.size === 0)
46
+ return false;
47
+ const provider = this.RunViewProviderToUse;
48
+ const user = this.ContextCurrentUser;
49
+ const workflowTypeID = await ResolveWorkflowTaskTypeID(provider, user);
50
+ for (const taskID of ends) {
51
+ if (await IsWorkflowStepTask(provider, user, taskID, workflowTypeID))
52
+ return true;
53
+ }
54
+ return false;
55
+ }
56
+ refuse(type) {
57
+ const result = new BaseEntityResult();
58
+ result.Success = false;
59
+ result.Type = type;
60
+ result.Message = "A workflow's dependencies are written only by the task-graph service: they decide when its steps run and what they read.";
61
+ result.StartedAt = new Date();
62
+ result.EndedAt = new Date();
63
+ this.ResultHistory.push(result);
64
+ return false;
65
+ }
66
+ /** Whether this write runs inside the dispatcher's runtime-security scope, bound to its user. */
67
+ inDispatcherScope() {
68
+ return this.ContextCurrentUser != null && ServerOperationScopeManager.Instance.IsOperationActive([TASK_GRAPH_RUNTIME_SECURITY_OPERATION], 'MJ: Task Dependencies', this.ContextCurrentUser);
69
+ }
70
+ };
71
+ MJTaskDependencyEntityServer = __decorate([
72
+ RegisterClass(BaseEntity, 'MJ: Task Dependencies')
73
+ ], MJTaskDependencyEntityServer);
74
+ export { MJTaskDependencyEntityServer };
75
+ //# sourceMappingURL=MJTaskDependencyEntityServer.server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MJTaskDependency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2BAA2B,CAAC,QAAQ,CAAC,iBAAiB,CAC5F,CAAC,qCAAqC,CAAC,EAAE,uBAAuB,EAAE,IAAI,CAAC,kBAAkB,CAC5F,CAAC;IACN,CAAC;CACJ,CAAA;AApDY,4BAA4B;IADxC,aAAa,CAAC,UAAU,EAAE,uBAAuB,CAAC;GACtC,4BAA4B,CAoDxC"}
@@ -0,0 +1,148 @@
1
+ import { EntitySaveOptions, IRunViewProvider, UserInfo, ValidationResult } from '@memberjunction/core';
2
+ import { MJTaskEntity } from '@memberjunction/core-entities';
3
+ /**
4
+ * Why a save must not write `Task.SecurityEnvelope`, or null when it may.
5
+ *
6
+ * The envelope holds the constraints of the agent run that submitted a task graph — its bound
7
+ * parameters, audience, tenant scope and taint — and the dispatcher enforces it on every node. It is
8
+ * written once, when the row is created (the server's own graph submission and its compensation
9
+ * tasks), and never changed: a later edit could only loosen what the submitting run was held to, so
10
+ * any change to it on an existing row is refused, whoever makes it.
11
+ */
12
+ export declare function SecurityEnvelopeChangeRefusal(isSaved: boolean, securityEnvelopeDirty: boolean): string | null;
13
+ /**
14
+ * Why a save must not write `Configuration` as given, or null when it may: it changes a key of its
15
+ * `runtime` object.
16
+ *
17
+ * Those keys record what happened when a step ran (whether its output was tainted, the parameters its
18
+ * action was given, who completed a Human step, which action log and prompt run it produced, the loop's
19
+ * iterations), and the dispatcher reads them back: for taint, and for what a compensation undoes (the
20
+ * action log names the record changes it reverts). Only the dispatcher writes them: through
21
+ * its guarded completion procedure, beneath the entity layer, or inside its server operation scope
22
+ * ({@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}, which `MJTaskEntityServer` checks before calling
23
+ * this). So any other change to them through the entity layer is refused, whoever makes it: a client,
24
+ * or server code such as the Update Record action a tainted agent calls on its own graph's rows.
25
+ * Setting `isOutputTainted` back to false would otherwise run every step downstream of an untrusted
26
+ * fetch clean. A create counts as a change from nothing, and a `Configuration` that does not parse
27
+ * reads as having none of them, so neither can slip one in.
28
+ *
29
+ * @param storedConfiguration the column before this save (`null` for a create)
30
+ * @param nextConfiguration the column being saved
31
+ * @param serverStamped keys this save's own server stamp sets ({@link MJTaskEntityServer.Save}), not compared
32
+ */
33
+ export declare function RuntimeSecurityChangeRefusal(storedConfiguration: string | null | undefined, nextConfiguration: string | null | undefined, serverStamped?: readonly string[]): string | null;
34
+ /**
35
+ * Whether a save changes what a step's `Configuration` tells it to do (input mapping, action, human step,
36
+ * compensation and the rest), as opposed to its `layout` or `runtime` keys. A `Configuration` that does not
37
+ * parse counts as changed.
38
+ */
39
+ export declare function ExecutableConfigurationChanged(stored: string | null | undefined, next: string | null | undefined): boolean;
40
+ /**
41
+ * Why a save must not change a workflow step this way, or null when it may.
42
+ *
43
+ * A workflow step (a task with a parent and a `StepType`) feeds what it produced into the steps after it,
44
+ * runs what its definition names, waits on whom it is assigned to, and its name and description become the
45
+ * question its Human step's request asks. The submitter's own code (an agent run calling Update Record, which
46
+ * runs as the submitter) could otherwise rewrite the output of a step that ran clean, the input or the action
47
+ * of a step waiting to run, the answer a Human step will carry before its person approves it, or who that
48
+ * person is; or rerun, skip or settle a step by its status. The graph would treat the result as trusted. So
49
+ * outside the dispatcher's scope those cannot change on a saved step, except that the person a Human step is
50
+ * assigned to may complete or reject it and give its output, their answer, in their own client request.
51
+ *
52
+ * @param changedFields the owned columns this save changes
53
+ * @param personCompletesOwnHumanStep this save is the assignee completing their Human step, as their own client request
54
+ */
55
+ export declare function WorkflowStepDataChangeRefusal(changedFields: readonly string[], personCompletesOwnHumanStep: boolean): string | null;
56
+ /**
57
+ * The ID of the `MJ: Task Types` row a workflow is filed under ({@link TASK_GRAPH_WORKFLOW_TYPE_NAME}), or null while it
58
+ * does not exist. Read as the system user, so a caller who cannot read task types cannot make the guards miss it.
59
+ */
60
+ export declare function ResolveWorkflowTaskTypeID(provider: IRunViewProvider, user: UserInfo | undefined): Promise<string | null>;
61
+ /**
62
+ * Whether `taskID` is a workflow: a task graph's parent, a parentless task of the workflow type. A task this user
63
+ * cannot read counts as one, so whatever hangs under it is judged as a workflow step (fail closed).
64
+ */
65
+ export declare function IsWorkflowTask(provider: IRunViewProvider, user: UserInfo | undefined, taskID: string, workflowTypeID: string | null): Promise<boolean>;
66
+ /**
67
+ * Whether `taskID` is a step of a workflow: a task with a parent and a `StepType` or the workflow type, or any task
68
+ * whose parent is a workflow. A task this user cannot read counts as one (fail closed).
69
+ */
70
+ export declare function IsWorkflowStepTask(provider: IRunViewProvider, user: UserInfo | undefined, taskID: string, workflowTypeID: string | null): Promise<boolean>;
71
+ /** What a save needs to know about workflow membership, resolved before it validates (the lookups are asynchronous). */
72
+ interface WorkflowFacts {
73
+ WorkflowTypeID: string | null;
74
+ StoredParentIsWorkflow: boolean;
75
+ NextParentIsWorkflow: boolean;
76
+ }
77
+ /**
78
+ * `configuration` with `runtime.completedByUserID` set to `userID` (removed when `null`). A
79
+ * `Configuration` that does not parse is returned unchanged: the step then records no completer, so its
80
+ * completion clears nothing.
81
+ */
82
+ export declare function WithCompletedByUserID(configuration: string | null, userID: string | null): string | null;
83
+ /**
84
+ * Server-side `MJ: Tasks` entity: keeps a task's security envelope immutable after insert
85
+ * ({@link SecurityEnvelopeChangeRefusal}), its runtime record, a workflow step's definition and data, and a
86
+ * workflow's metadata dispatcher-owned ({@link RuntimeSecurityChangeRefusal}, {@link WorkflowStepDataChangeRefusal}),
87
+ * and records who completes a Human step.
88
+ */
89
+ export declare class MJTaskEntityServer extends MJTaskEntity {
90
+ /**
91
+ * Records who completed a Human step (`runtime.completedByUserID`) when this save moves one to
92
+ * `Complete`, whatever the caller put there: the user the save runs as when it arrived as a direct
93
+ * client CRUD request (`ServerOperationScopeManager.IsInDirectClientCrud`), and nobody otherwise. A completed Human step
94
+ * clears taint only when the record names its assignee (`HumanReviewClearsTaint` in
95
+ * `@memberjunction/task-graph`). The assignee is the graph's submitter, and the graph's agents and
96
+ * actions run as that same user, so the user alone cannot tell a person's review from server code
97
+ * completing the step; where the save came from can. The dispatcher, settling a step from the
98
+ * answered request, records the request's responder itself, inside {@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}.
99
+ */
100
+ Save(options?: EntitySaveOptions): Promise<boolean>;
101
+ /**
102
+ * The workflow checks for a save that did not come through {@link Save} (a path that validates a row it then writes
103
+ * some other way): it resolves the facts itself. Within {@link Save} the synchronous {@link Validate} has already run
104
+ * them, with the facts {@link Save} resolved.
105
+ */
106
+ ValidateAsync(): Promise<ValidationResult>;
107
+ /**
108
+ * Workflow membership of this row before and after the save. Set only while a save (or {@link ValidateAsync})
109
+ * validates it: a bare {@link Validate} call (REST validates before it saves) has none, and skips the checks that
110
+ * need it, which the save that follows runs.
111
+ */
112
+ private workflowFacts;
113
+ /** Resolves {@link WorkflowFacts}: the workflow type, and whether the stored and the new parent are workflows. */
114
+ protected resolveWorkflowFacts(): Promise<WorkflowFacts>;
115
+ Validate(): ValidationResult;
116
+ /**
117
+ * The checks that need {@link workflowFacts}: a workflow, or a step of one, made by an ordinary save (created, or an
118
+ * existing task retyped or re-parented into one), and the freezes on a workflow step's and a workflow's own columns.
119
+ * Called only with the facts resolved, and outside the dispatcher's scope.
120
+ */
121
+ private applyWorkflowChecks;
122
+ /** The column's value before this save (its current value on a create). */
123
+ private stored;
124
+ /**
125
+ * Whether the row, as stored or as this save leaves it, is a step of a task graph: it has a parent, and a `StepType`,
126
+ * the workflow type (the dispatcher finds graphs by their steps' type), or a parent that is a workflow. Called only
127
+ * with {@link workflowFacts} resolved; without them it counts any task with a parent (fail closed).
128
+ */
129
+ private isWorkflowStep;
130
+ /**
131
+ * Whether the row, as stored or as this save leaves it, is a task graph's workflow (parent) task: no parent, no
132
+ * `StepType`, filed under the workflow type. Without resolved facts, the joined type name decides for the stored row,
133
+ * and a changed type counts (fail closed).
134
+ */
135
+ private isWorkflowParent;
136
+ /**
137
+ * Whether this save is the assignee settling their own Human step, as their own client request: completing it
138
+ * (approving) or failing it (rejecting) while it waits on them. A Human step waits in `Pending`; settling one that
139
+ * is Skipped, Cancelled or Blocked would undo the owner's choice or release steps past a failed prerequisite.
140
+ */
141
+ private personSettlesOwnHumanStep;
142
+ /** Whether this save moves a Human step to `Complete` (a create already `Complete` included). */
143
+ private completesHumanStep;
144
+ /** Whether this save runs inside the dispatcher's runtime-security scope, bound to this row's user. */
145
+ private inDispatcherScope;
146
+ }
147
+ export {};
148
+ //# sourceMappingURL=MJTaskEntityServer.server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"MJTaskEntityServer.server.d.ts","sourceRoot":"","sources":["../../src/custom/MJTaskEntityServer.server.ts"],"names":[],"mappings":"AAAA,OAAO,EAEH,iBAAiB,EACjB,gBAAgB,EAGhB,QAAQ,EAGR,gBAAgB,EACnB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAG7D;;;;;;;;GAQG;AACH,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,OAAO,EAAE,qBAAqB,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAM7G;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,4BAA4B,CACxC,mBAAmB,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC9C,iBAAiB,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAC5C,aAAa,GAAE,SAAS,MAAM,EAAO,GACtC,MAAM,GAAG,IAAI,CAWf;AA8CD;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAe1H;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,6BAA6B,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,EAAE,2BAA2B,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAOnI;AAKD;;;GAGG;AACH,wBAAsB,yBAAyB,CAAC,QAAQ,EAAE,gBAAgB,EAAE,IAAI,E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;IACH,OAAO,CAAC,gBAAgB;IAUxB;;;;OAIG;IACH,OAAO,CAAC,yBAAyB;IASjC,iGAAiG;IACjG,OAAO,CAAC,kBAAkB;IAK1B,uGAAuG;IACvG,OAAO,CAAC,iBAAiB;CAK5B"}
@@ -0,0 +1,413 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { BaseEntity, RunView, ServerOperationScopeManager, ValidationErrorInfo, ValidationErrorType, } from '@memberjunction/core';
8
+ import { IsValidUUID, RegisterClass, UUIDsEqual } from '@memberjunction/global';
9
+ import { UserCache } from '@memberjunction/generic-database-provider';
10
+ import { MJTaskEntity } from '@memberjunction/core-entities';
11
+ import { TASK_GRAPH_RUNTIME_SECURITY_OPERATION, TASK_GRAPH_WORKFLOW_TYPE_NAME } from '@memberjunction/ai-core-plus';
12
+ /**
13
+ * Why a save must not write `Task.SecurityEnvelope`, or null when it may.
14
+ *
15
+ * The envelope holds the constraints of the agent run that submitted a task graph — its bound
16
+ * parameters, audience, tenant scope and taint — and the dispatcher enforces it on every node. It is
17
+ * written once, when the row is created (the server's own graph submission and its compensation
18
+ * tasks), and never changed: a later edit could only loosen what the submitting run was held to, so
19
+ * any change to it on an existing row is refused, whoever makes it.
20
+ */
21
+ export function SecurityEnvelopeChangeRefusal(isSaved, securityEnvelopeDirty) {
22
+ if (!isSaved || !securityEnvelopeDirty) {
23
+ return null;
24
+ }
25
+ return 'SecurityEnvelope cannot be changed after the task is created: it holds the constraints of the run that ' +
26
+ 'submitted the workflow, and the dispatcher enforces it on every step.';
27
+ }
28
+ /**
29
+ * Why a save must not write `Configuration` as given, or null when it may: it changes a key of its
30
+ * `runtime` object.
31
+ *
32
+ * Those keys record what happened when a step ran (whether its output was tainted, the parameters its
33
+ * action was given, who completed a Human step, which action log and prompt run it produced, the loop's
34
+ * iterations), and the dispatcher reads them back: for taint, and for what a compensation undoes (the
35
+ * action log names the record changes it reverts). Only the dispatcher writes them: through
36
+ * its guarded completion procedure, beneath the entity layer, or inside its server operation scope
37
+ * ({@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}, which `MJTaskEntityServer` checks before calling
38
+ * this). So any other change to them through the entity layer is refused, whoever makes it: a client,
39
+ * or server code such as the Update Record action a tainted agent calls on its own graph's rows.
40
+ * Setting `isOutputTainted` back to false would otherwise run every step downstream of an untrusted
41
+ * fetch clean. A create counts as a change from nothing, and a `Configuration` that does not parse
42
+ * reads as having none of them, so neither can slip one in.
43
+ *
44
+ * @param storedConfiguration the column before this save (`null` for a create)
45
+ * @param nextConfiguration the column being saved
46
+ * @param serverStamped keys this save's own server stamp sets ({@link MJTaskEntityServer.Save}), not compared
47
+ */
48
+ export function RuntimeSecurityChangeRefusal(storedConfiguration, nextConfiguration, serverStamped = []) {
49
+ const stored = runtimeOf(storedConfiguration);
50
+ const next = runtimeOf(nextConfiguration);
51
+ const changed = [...new Set([...Object.keys(stored), ...Object.keys(next)])].find((key) => !serverStamped.includes(key) && JSON.stringify(stored[key]) !== JSON.stringify(next[key]));
52
+ if (!changed) {
53
+ return null;
54
+ }
55
+ return `Configuration.runtime.${changed} cannot be set or changed: only the task-graph dispatcher records what a step ` +
56
+ 'did when it ran, which decides how far its output is trusted and what its compensation undoes.';
57
+ }
58
+ /** The `runtime` object of a serialized `Task.Configuration`, or `{}` when it has none or does not parse. */
59
+ function runtimeOf(configuration) {
60
+ if (!configuration) {
61
+ return {};
62
+ }
63
+ try {
64
+ const parsed = JSON.parse(configuration);
65
+ const runtime = isRecord(parsed) ? parsed.runtime : undefined;
66
+ return isRecord(runtime) ? runtime : {};
67
+ }
68
+ catch {
69
+ return {};
70
+ }
71
+ }
72
+ function isRecord(value) {
73
+ return !!value && typeof value === 'object' && !Array.isArray(value);
74
+ }
75
+ /**
76
+ * The columns of a workflow step the dispatcher owns: its data (what it was given, what it produced, what a person
77
+ * is asked) and what it is (its kind, what it runs, where it sits). `Configuration` is checked separately, by
78
+ * {@link ExecutableConfigurationChanged}. Left writable: progress (status, timing, claim, errors), the assignee,
79
+ * and the rest, which decide nothing a step runs or reads.
80
+ */
81
+ const WORKFLOW_STEP_OWNED_FIELDS = [
82
+ 'InputPayload', 'OutputPayload', 'Name', 'Description', 'Status', 'UserID',
83
+ 'StepType', 'ActionID', 'AgentID', 'PromptID', 'ParentID', 'TypeID', 'CompensatesTaskID',
84
+ ];
85
+ /**
86
+ * The columns of a workflow (a task graph's parent task) the dispatcher owns: its metadata (`InputPayload`: who the
87
+ * graph runs as, the `data`/`context` its steps read, its continuation and saga state), its result, and what it is
88
+ * attached to. Its status and progress stay writable; the dispatcher settles it through guarded statements.
89
+ */
90
+ const WORKFLOW_PARENT_OWNED_FIELDS = [
91
+ 'InputPayload', 'OutputPayload', 'AgentRunID', 'UserID', 'ConversationDetailID', 'TypeID', 'EnvironmentID', 'StepType', 'ParentID',
92
+ ];
93
+ /** What the person settling their own Human step (completing or rejecting it) may set in that save: its status, and its output, their answer. */
94
+ const PERSON_COMPLETION_FIELDS = ['Status', 'OutputPayload'];
95
+ /** `Configuration` keys anyone may write: `layout` is presentation, and `runtime` has its own guard. */
96
+ const FREE_CONFIGURATION_KEYS = ['layout', 'runtime'];
97
+ /**
98
+ * Whether a save changes what a step's `Configuration` tells it to do (input mapping, action, human step,
99
+ * compensation and the rest), as opposed to its `layout` or `runtime` keys. A `Configuration` that does not
100
+ * parse counts as changed.
101
+ */
102
+ export function ExecutableConfigurationChanged(stored, next) {
103
+ const executable = (configuration) => {
104
+ if (!configuration)
105
+ return '[]';
106
+ try {
107
+ const parsed = JSON.parse(configuration);
108
+ if (!isRecord(parsed))
109
+ return undefined;
110
+ const kept = Object.keys(parsed).filter((key) => !FREE_CONFIGURATION_KEYS.includes(key)).sort();
111
+ return JSON.stringify(kept.map((key) => [key, parsed[key]]));
112
+ }
113
+ catch {
114
+ return undefined;
115
+ }
116
+ };
117
+ const before = executable(stored);
118
+ const after = executable(next);
119
+ return before === undefined || after === undefined || before !== after;
120
+ }
121
+ /**
122
+ * Why a save must not change a workflow step this way, or null when it may.
123
+ *
124
+ * A workflow step (a task with a parent and a `StepType`) feeds what it produced into the steps after it,
125
+ * runs what its definition names, waits on whom it is assigned to, and its name and description become the
126
+ * question its Human step's request asks. The submitter's own code (an agent run calling Update Record, which
127
+ * runs as the submitter) could otherwise rewrite the output of a step that ran clean, the input or the action
128
+ * of a step waiting to run, the answer a Human step will carry before its person approves it, or who that
129
+ * person is; or rerun, skip or settle a step by its status. The graph would treat the result as trusted. So
130
+ * outside the dispatcher's scope those cannot change on a saved step, except that the person a Human step is
131
+ * assigned to may complete or reject it and give its output, their answer, in their own client request.
132
+ *
133
+ * @param changedFields the owned columns this save changes
134
+ * @param personCompletesOwnHumanStep this save is the assignee completing their Human step, as their own client request
135
+ */
136
+ export function WorkflowStepDataChangeRefusal(changedFields, personCompletesOwnHumanStep) {
137
+ const refused = changedFields.filter((field) => !(personCompletesOwnHumanStep && PERSON_COMPLETION_FIELDS.includes(field)));
138
+ if (refused.length === 0) {
139
+ return null;
140
+ }
141
+ return `${refused.join(', ')} of a workflow step cannot be changed: only the task-graph dispatcher writes what a step is ` +
142
+ 'and the data it carries, which the steps after it trust as its result.';
143
+ }
144
+ /** The workflow task type's ID once found. Never cached while absent: the task-graph service creates the row on first use. */
145
+ let workflowTaskTypeIDCache;
146
+ /**
147
+ * The ID of the `MJ: Task Types` row a workflow is filed under ({@link TASK_GRAPH_WORKFLOW_TYPE_NAME}), or null while it
148
+ * does not exist. Read as the system user, so a caller who cannot read task types cannot make the guards miss it.
149
+ */
150
+ export async function ResolveWorkflowTaskTypeID(provider, user) {
151
+ if (workflowTaskTypeIDCache)
152
+ return workflowTaskTypeIDCache;
153
+ const result = await new RunView(provider).RunView(
154
+ // Ordered as the dispatcher orders it (oldest first), so both bind the same row should a second share the name.
155
+ { EntityName: 'MJ: Task Types', ExtraFilter: `Name='${TASK_GRAPH_WORKFLOW_TYPE_NAME}'`, Fields: ['ID'], OrderBy: '__mj_CreatedAt ASC, ID ASC', ResultType: 'simple', MaxRows: 1 }, UserCache.Instance.GetSystemUser() ?? user);
156
+ const id = result.Success ? result.Results?.[0]?.ID : undefined;
157
+ if (id)
158
+ workflowTaskTypeIDCache = id;
159
+ return id ?? null;
160
+ }
161
+ /** A task's membership columns, as stored. Undefined when the ID is not a readable task. */
162
+ async function loadTaskShape(provider, user, taskID) {
163
+ if (!IsValidUUID(taskID))
164
+ return undefined;
165
+ const result = await new RunView(provider).RunView({ EntityName: 'MJ: Tasks', ExtraFilter: `ID='${taskID}'`, Fields: ['ParentID', 'StepType', 'TypeID'], ResultType: 'simple', MaxRows: 1, BypassCache: true }, user);
166
+ return result.Success ? result.Results?.[0] : undefined;
167
+ }
168
+ /**
169
+ * Whether `taskID` is a workflow: a task graph's parent, a parentless task of the workflow type. A task this user
170
+ * cannot read counts as one, so whatever hangs under it is judged as a workflow step (fail closed).
171
+ */
172
+ export async function IsWorkflowTask(provider, user, taskID, workflowTypeID) {
173
+ const row = await loadTaskShape(provider, user, taskID);
174
+ if (!row)
175
+ return true;
176
+ return row.ParentID == null && workflowTypeID != null && UUIDsEqual(row.TypeID, workflowTypeID);
177
+ }
178
+ /**
179
+ * Whether `taskID` is a step of a workflow: a task with a parent and a `StepType` or the workflow type, or any task
180
+ * whose parent is a workflow. A task this user cannot read counts as one (fail closed).
181
+ */
182
+ export async function IsWorkflowStepTask(provider, user, taskID, workflowTypeID) {
183
+ const row = await loadTaskShape(provider, user, taskID);
184
+ if (!row)
185
+ return true;
186
+ if (row.ParentID == null)
187
+ return false;
188
+ if (row.StepType != null || (workflowTypeID != null && UUIDsEqual(row.TypeID, workflowTypeID)))
189
+ return true;
190
+ return IsWorkflowTask(provider, user, row.ParentID, workflowTypeID);
191
+ }
192
+ /**
193
+ * `configuration` with `runtime.completedByUserID` set to `userID` (removed when `null`). A
194
+ * `Configuration` that does not parse is returned unchanged: the step then records no completer, so its
195
+ * completion clears nothing.
196
+ */
197
+ export function WithCompletedByUserID(configuration, userID) {
198
+ let parsed = {};
199
+ if (configuration) {
200
+ try {
201
+ const value = JSON.parse(configuration);
202
+ if (!isRecord(value))
203
+ return configuration;
204
+ parsed = value;
205
+ }
206
+ catch {
207
+ return configuration;
208
+ }
209
+ }
210
+ const runtime = isRecord(parsed.runtime) ? { ...parsed.runtime } : {};
211
+ if (userID) {
212
+ runtime.completedByUserID = userID;
213
+ }
214
+ else {
215
+ delete runtime.completedByUserID;
216
+ }
217
+ return JSON.stringify({ ...parsed, runtime });
218
+ }
219
+ /**
220
+ * Server-side `MJ: Tasks` entity: keeps a task's security envelope immutable after insert
221
+ * ({@link SecurityEnvelopeChangeRefusal}), its runtime record, a workflow step's definition and data, and a
222
+ * workflow's metadata dispatcher-owned ({@link RuntimeSecurityChangeRefusal}, {@link WorkflowStepDataChangeRefusal}),
223
+ * and records who completes a Human step.
224
+ */
225
+ let MJTaskEntityServer = class MJTaskEntityServer extends MJTaskEntity {
226
+ /**
227
+ * Records who completed a Human step (`runtime.completedByUserID`) when this save moves one to
228
+ * `Complete`, whatever the caller put there: the user the save runs as when it arrived as a direct
229
+ * client CRUD request (`ServerOperationScopeManager.IsInDirectClientCrud`), and nobody otherwise. A completed Human step
230
+ * clears taint only when the record names its assignee (`HumanReviewClearsTaint` in
231
+ * `@memberjunction/task-graph`). The assignee is the graph's submitter, and the graph's agents and
232
+ * actions run as that same user, so the user alone cannot tell a person's review from server code
233
+ * completing the step; where the save came from can. The dispatcher, settling a step from the
234
+ * answered request, records the request's responder itself, inside {@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}.
235
+ */
236
+ async Save(options) {
237
+ if (!this.inDispatcherScope()) {
238
+ // Resolved here, before the base save validates, so the checks run in the synchronous Validate, which no
239
+ // save option skips (SkipAsyncValidation skips only ValidateAsync).
240
+ this.workflowFacts = await this.resolveWorkflowFacts();
241
+ if (this.completesHumanStep()) {
242
+ const completer = ServerOperationScopeManager.Instance.IsInDirectClientCrud() ? (this.ContextCurrentUser?.ID ?? null) : null;
243
+ this.Configuration = WithCompletedByUserID(this.Configuration, completer);
244
+ }
245
+ }
246
+ try {
247
+ return await super.Save(options);
248
+ }
249
+ finally {
250
+ this.workflowFacts = undefined;
251
+ }
252
+ }
253
+ /**
254
+ * The workflow checks for a save that did not come through {@link Save} (a path that validates a row it then writes
255
+ * some other way): it resolves the facts itself. Within {@link Save} the synchronous {@link Validate} has already run
256
+ * them, with the facts {@link Save} resolved.
257
+ */
258
+ async ValidateAsync() {
259
+ const result = await super.ValidateAsync();
260
+ if (this.workflowFacts || this.inDispatcherScope()) {
261
+ return result;
262
+ }
263
+ this.workflowFacts = await this.resolveWorkflowFacts();
264
+ try {
265
+ this.applyWorkflowChecks(result);
266
+ }
267
+ finally {
268
+ this.workflowFacts = undefined;
269
+ }
270
+ return result;
271
+ }
272
+ /** Resolves {@link WorkflowFacts}: the workflow type, and whether the stored and the new parent are workflows. */
273
+ async resolveWorkflowFacts() {
274
+ const provider = this.RunViewProviderToUse;
275
+ const user = this.ContextCurrentUser;
276
+ const workflowTypeID = await ResolveWorkflowTaskTypeID(provider, user);
277
+ const storedParent = this.stored('ParentID');
278
+ const nextParent = this.ParentID;
279
+ const storedParentIsWorkflow = storedParent ? await IsWorkflowTask(provider, user, storedParent, workflowTypeID) : false;
280
+ const nextParentIsWorkflow = !nextParent
281
+ ? false
282
+ : storedParent && UUIDsEqual(nextParent, storedParent)
283
+ ? storedParentIsWorkflow
284
+ : await IsWorkflowTask(provider, user, nextParent, workflowTypeID);
285
+ return { WorkflowTypeID: workflowTypeID, StoredParentIsWorkflow: storedParentIsWorkflow, NextParentIsWorkflow: nextParentIsWorkflow };
286
+ }
287
+ Validate() {
288
+ const result = super.Validate();
289
+ const refusal = SecurityEnvelopeChangeRefusal(this.IsSaved, this.GetFieldByName('SecurityEnvelope')?.Dirty ?? false);
290
+ if (refusal) {
291
+ result.Errors.push(new ValidationErrorInfo('SecurityEnvelope', refusal, this.SecurityEnvelope, ValidationErrorType.Failure));
292
+ result.Success = false;
293
+ }
294
+ if (!this.inDispatcherScope()) {
295
+ const storedConfiguration = this.IsSaved ? this.GetFieldByName('Configuration')?.OldValue : null;
296
+ const serverStamped = this.completesHumanStep() ? ['completedByUserID'] : [];
297
+ const runtimeRefusal = RuntimeSecurityChangeRefusal(storedConfiguration, this.Configuration, serverStamped);
298
+ if (runtimeRefusal) {
299
+ result.Errors.push(new ValidationErrorInfo('Configuration', runtimeRefusal, this.Configuration, ValidationErrorType.Failure));
300
+ result.Success = false;
301
+ }
302
+ if (this.workflowFacts) {
303
+ this.applyWorkflowChecks(result);
304
+ }
305
+ }
306
+ return result;
307
+ }
308
+ /**
309
+ * The checks that need {@link workflowFacts}: a workflow, or a step of one, made by an ordinary save (created, or an
310
+ * existing task retyped or re-parented into one), and the freezes on a workflow step's and a workflow's own columns.
311
+ * Called only with the facts resolved, and outside the dispatcher's scope.
312
+ */
313
+ applyWorkflowChecks(result) {
314
+ const storedConfiguration = this.IsSaved ? this.GetFieldByName('Configuration')?.OldValue : null;
315
+ const wasWorkflowRow = this.IsSaved && (this.isWorkflowStep('stored') || this.isWorkflowParent('stored'));
316
+ if (!wasWorkflowRow && (this.isWorkflowStep('next') || this.isWorkflowParent('next'))) {
317
+ // A workflow, or a step of one, made by an ordinary save: created, or an existing task retyped or
318
+ // re-parented into one. The dispatcher would run it as the user its metadata names.
319
+ const field = this.ParentID ? 'ParentID' : 'TypeID';
320
+ result.Errors.push(new ValidationErrorInfo(field, 'Only the task-graph service creates a workflow or adds a step to one: a workflow\'s steps run as the user it was submitted by.', null, ValidationErrorType.Failure));
321
+ result.Success = false;
322
+ }
323
+ else if (this.IsSaved && this.isWorkflowStep('stored')) {
324
+ const changed = WORKFLOW_STEP_OWNED_FIELDS.filter((field) => this.GetFieldByName(field)?.Dirty);
325
+ if (this.GetFieldByName('Configuration')?.Dirty && ExecutableConfigurationChanged(storedConfiguration, this.Configuration)) {
326
+ changed.push('Configuration');
327
+ }
328
+ const dataRefusal = WorkflowStepDataChangeRefusal(changed, this.personSettlesOwnHumanStep());
329
+ if (dataRefusal) {
330
+ result.Errors.push(new ValidationErrorInfo(changed[0], dataRefusal, null, ValidationErrorType.Failure));
331
+ result.Success = false;
332
+ }
333
+ }
334
+ else if (this.IsSaved && this.isWorkflowParent('stored')) {
335
+ const changed = WORKFLOW_PARENT_OWNED_FIELDS.filter((field) => this.GetFieldByName(field)?.Dirty);
336
+ if (changed.length > 0) {
337
+ const message = `${changed.join(', ')} of a workflow cannot be changed: only the task-graph dispatcher writes who it ` +
338
+ 'runs as, the data its steps read, and what it is attached to.';
339
+ result.Errors.push(new ValidationErrorInfo(changed[0], message, null, ValidationErrorType.Failure));
340
+ result.Success = false;
341
+ }
342
+ }
343
+ }
344
+ /** The column's value before this save (its current value on a create). */
345
+ stored(field) {
346
+ return this.IsSaved ? this.GetFieldByName(field)?.OldValue : this.GetFieldByName(field)?.Value;
347
+ }
348
+ /**
349
+ * Whether the row, as stored or as this save leaves it, is a step of a task graph: it has a parent, and a `StepType`,
350
+ * the workflow type (the dispatcher finds graphs by their steps' type), or a parent that is a workflow. Called only
351
+ * with {@link workflowFacts} resolved; without them it counts any task with a parent (fail closed).
352
+ */
353
+ isWorkflowStep(state) {
354
+ const parent = state === 'stored' ? this.stored('ParentID') : this.ParentID;
355
+ if (parent == null)
356
+ return false;
357
+ const stepType = state === 'stored' ? this.stored('StepType') : this.StepType;
358
+ if (stepType != null)
359
+ return true;
360
+ const facts = this.workflowFacts;
361
+ if (!facts)
362
+ return true;
363
+ const typeID = (state === 'stored' ? this.stored('TypeID') : this.TypeID);
364
+ if (facts.WorkflowTypeID != null && typeof typeID === 'string' && UUIDsEqual(typeID, facts.WorkflowTypeID))
365
+ return true;
366
+ return state === 'stored' ? facts.StoredParentIsWorkflow : facts.NextParentIsWorkflow;
367
+ }
368
+ /**
369
+ * Whether the row, as stored or as this save leaves it, is a task graph's workflow (parent) task: no parent, no
370
+ * `StepType`, filed under the workflow type. Without resolved facts, the joined type name decides for the stored row,
371
+ * and a changed type counts (fail closed).
372
+ */
373
+ isWorkflowParent(state) {
374
+ const parent = state === 'stored' ? this.stored('ParentID') : this.ParentID;
375
+ const stepType = state === 'stored' ? this.stored('StepType') : this.StepType;
376
+ if (parent != null || stepType != null)
377
+ return false;
378
+ const typeID = (state === 'stored' ? this.stored('TypeID') : this.TypeID);
379
+ const facts = this.workflowFacts;
380
+ if (facts)
381
+ return facts.WorkflowTypeID != null && typeof typeID === 'string' && UUIDsEqual(typeID, facts.WorkflowTypeID);
382
+ return state === 'stored' ? this.Type === TASK_GRAPH_WORKFLOW_TYPE_NAME : (this.GetFieldByName('TypeID')?.Dirty === true || this.Type === TASK_GRAPH_WORKFLOW_TYPE_NAME);
383
+ }
384
+ /**
385
+ * Whether this save is the assignee settling their own Human step, as their own client request: completing it
386
+ * (approving) or failing it (rejecting) while it waits on them. A Human step waits in `Pending`; settling one that
387
+ * is Skipped, Cancelled or Blocked would undo the owner's choice or release steps past a failed prerequisite.
388
+ */
389
+ personSettlesOwnHumanStep() {
390
+ const assignee = this.stored('UserID');
391
+ const settles = this.StepType === 'Human' && (this.Status === 'Complete' || this.Status === 'Failed') &&
392
+ this.stored('Status') === 'Pending';
393
+ return settles &&
394
+ ServerOperationScopeManager.Instance.IsInDirectClientCrud() &&
395
+ typeof assignee === 'string' && this.ContextCurrentUser != null && UUIDsEqual(assignee, this.ContextCurrentUser.ID);
396
+ }
397
+ /** Whether this save moves a Human step to `Complete` (a create already `Complete` included). */
398
+ completesHumanStep() {
399
+ const storedStatus = this.IsSaved ? this.GetFieldByName('Status')?.OldValue : null;
400
+ return this.StepType === 'Human' && this.Status === 'Complete' && storedStatus !== 'Complete';
401
+ }
402
+ /** Whether this save runs inside the dispatcher's runtime-security scope, bound to this row's user. */
403
+ inDispatcherScope() {
404
+ // No user, no scope: without one, IsOperationActive would match a frame bound to anybody.
405
+ return this.ContextCurrentUser != null &&
406
+ ServerOperationScopeManager.Instance.IsOperationActive([TASK_GRAPH_RUNTIME_SECURITY_OPERATION], 'MJ: Tasks', this.ContextCurrentUser);
407
+ }
408
+ };
409
+ MJTaskEntityServer = __decorate([
410
+ RegisterClass(BaseEntity, 'MJ: Tasks')
411
+ ], MJTaskEntityServer);
412
+ export { MJTaskEntityServer };
413
+ //# sourceMappingURL=MJTaskEntityServer.server.js.map