@memberjunction/task-graph 6.2.1 → 6.3.0-edge.0

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 (39) hide show
  1. package/dist/TaskGraphDispatcher.d.ts +279 -2
  2. package/dist/TaskGraphDispatcher.d.ts.map +1 -1
  3. package/dist/TaskGraphDispatcher.js +1255 -330
  4. package/dist/TaskGraphDispatcher.js.map +1 -1
  5. package/dist/TaskGraphService.d.ts +57 -1
  6. package/dist/TaskGraphService.d.ts.map +1 -1
  7. package/dist/TaskGraphService.js +176 -24
  8. package/dist/TaskGraphService.js.map +1 -1
  9. package/dist/TaskGraphSubmitterImpl.d.ts +1 -0
  10. package/dist/TaskGraphSubmitterImpl.d.ts.map +1 -1
  11. package/dist/TaskGraphSubmitterImpl.js +5 -0
  12. package/dist/TaskGraphSubmitterImpl.js.map +1 -1
  13. package/dist/decision-node.d.ts +19 -0
  14. package/dist/decision-node.d.ts.map +1 -1
  15. package/dist/decision-node.js.map +1 -1
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +2 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/operations/TaskGraphDebugOperations.d.ts +23 -0
  21. package/dist/operations/TaskGraphDebugOperations.d.ts.map +1 -1
  22. package/dist/operations/TaskGraphDebugOperations.js +13 -13
  23. package/dist/operations/TaskGraphDebugOperations.js.map +1 -1
  24. package/dist/operations/TaskGraphOperations.d.ts.map +1 -1
  25. package/dist/operations/TaskGraphOperations.js +12 -7
  26. package/dist/operations/TaskGraphOperations.js.map +1 -1
  27. package/dist/saga-compensation.d.ts +167 -0
  28. package/dist/saga-compensation.d.ts.map +1 -0
  29. package/dist/saga-compensation.js +392 -0
  30. package/dist/saga-compensation.js.map +1 -0
  31. package/dist/task-security.d.ts +96 -0
  32. package/dist/task-security.d.ts.map +1 -0
  33. package/dist/task-security.js +187 -0
  34. package/dist/task-security.js.map +1 -0
  35. package/dist/types.d.ts +57 -1
  36. package/dist/types.d.ts.map +1 -1
  37. package/dist/types.js +1 -0
  38. package/dist/types.js.map +1 -1
  39. package/package.json +12 -12
@@ -17,8 +17,9 @@
17
17
  */
18
18
  import { IMetadataProvider, UserInfo } from '@memberjunction/core';
19
19
  import { MJTaskEntity } from '@memberjunction/core-entities';
20
- import { type TaskGraphInvocationEnvelope, type TaskGraphSpec, type TaskGraphSpecNode, type ForEachOperation, type WhileOperation } from '@memberjunction/ai-core-plus';
20
+ import { type TaskGraphFailurePolicy, type TaskGraphInvocationEnvelope, type TaskGraphSpec, type TaskGraphSpecNode, type TaskSecurityEnvelope, type ForEachOperation, type WhileOperation } from '@memberjunction/ai-core-plus';
21
21
  import { type DecisionTaskRow, type TaskStepConfiguration } from './decision-node.js';
22
+ import { type SagaExecutionState } from './saga-compensation.js';
22
23
  import { type EdgeOverrideVerdict, type StepTarget, type TaskGraphDebugState } from './debug-state.js';
23
24
  /**
24
25
  * Normalizes a caller-supplied reinvoke depth to a safe cap seed.
@@ -64,6 +65,12 @@ export type TaskGraphSubmitContext = {
64
65
  Debug?: {
65
66
  paused?: boolean;
66
67
  };
68
+ /**
69
+ * The submitting run's security envelope. Written to `Task.SecurityEnvelope` on the parent and on
70
+ * every child row at insert, never afterwards (`MJTaskEntityServer` refuses a change), and enforced
71
+ * by the dispatcher on every node.
72
+ */
73
+ SecurityEnvelope?: TaskSecurityEnvelope;
67
74
  };
68
75
  /**
69
76
  * What the parent Task row remembers about the graph beyond its tasks.
@@ -103,6 +110,13 @@ export type TaskGraphParentMetadata = {
103
110
  * run they are watching.
104
111
  */
105
112
  submittedByUserID?: string | null;
113
+ /**
114
+ * Set on every graph submitted since steps record their output taint. The taint walk then reads a step that is
115
+ * Complete with nothing recorded, and no person recorded as completing it, as tainted: it did not finish through the
116
+ * dispatcher. A graph without it was submitted before the upgrade, when no step recorded taint, so its steps are
117
+ * read through to what fed them instead. Only the service writes this metadata, and it cannot be changed after.
118
+ */
119
+ recordsTaint?: boolean;
106
120
  /**
107
121
  * Set once the completion handler has delivered. Written with a compare-and-swap guard, which is
108
122
  * what turns at-least-once delivery into effectively-once: a crash between "graph complete" and
@@ -140,6 +154,14 @@ export type TaskGraphParentMetadata = {
140
154
  data?: unknown;
141
155
  context?: unknown;
142
156
  };
157
+ /**
158
+ * Workflow-level saga failure policy (`'Halt'` default, or `'CompensateCompleted'`).
159
+ */
160
+ failurePolicy?: TaskGraphFailurePolicy;
161
+ /**
162
+ * Current saga lifecycle state when `failurePolicy === 'CompensateCompleted'`.
163
+ */
164
+ sagaState?: SagaExecutionState;
143
165
  };
144
166
  /**
145
167
  * Continuation chains are bounded separately from graph nesting.
@@ -172,6 +194,8 @@ export declare function BuildTaskGraphParentInputPayload(args: {
172
194
  continuation: TaskGraphParentMetadata['continuation'];
173
195
  reinvokeDepth: number;
174
196
  failureSemantics: NonNullable<TaskGraphParentMetadata['failureSemantics']>;
197
+ failurePolicy?: TaskGraphFailurePolicy;
198
+ sagaState?: SagaExecutionState;
175
199
  submittedByAgentRunID: string | null;
176
200
  submittedByUserID: string | null;
177
201
  parentAgentHierarchy?: string[];
@@ -193,6 +217,12 @@ export type TaskGraphCancelResult = {
193
217
  };
194
218
  /** True when a continuation chain has gone as far as it may. */
195
219
  export declare function IsReinvokeCapReached(meta: TaskGraphParentMetadata): boolean;
220
+ /** The outcome of {@link TaskGraphService.RetryTask}. */
221
+ export type TaskGraphRetryOutcome = {
222
+ Success: boolean;
223
+ /** Why the retry was refused or failed, fit to show the person who asked. */
224
+ ErrorMessage?: string;
225
+ };
196
226
  export type TaskGraphSubmitResult = {
197
227
  Success: boolean;
198
228
  /** The parent task representing the whole graph — the handle for status, cancel and retry. */
@@ -295,6 +325,12 @@ export declare class TaskGraphService {
295
325
  * holds it.
296
326
  */
297
327
  private readonly claims;
328
+ /**
329
+ * Saves a row of a graph inside {@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}, bound to the caller: a workflow, its
330
+ * steps and its edges are written only by this service and the dispatcher (`MJTaskEntityServer`,
331
+ * `MJTaskDependencyEntityServer`), so a graph is created and changed through the service, never by an ordinary save.
332
+ */
333
+ private saveAsService;
298
334
  /**
299
335
  * Validates and persists a task graph, returning as soon as it is durable.
300
336
  *
@@ -386,6 +422,16 @@ export declare class TaskGraphService {
386
422
  * past this node.
387
423
  */
388
424
  Retry(taskID: string, context: TaskGraphSubmitContext, inputPayload?: unknown): Promise<boolean>;
425
+ /** {@link Retry}, with the reason when the retry is refused, for a caller that shows it to a person. */
426
+ RetryTask(taskID: string, context: TaskGraphSubmitContext, inputPayload?: unknown): Promise<TaskGraphRetryOutcome>;
427
+ /**
428
+ * Why no step of this graph may be retried, or null (S9): its rollback has started. A saga
429
+ * (`failurePolicy: 'CompensateCompleted'`) undoes the completed steps after a failure, so re-running
430
+ * the failed step would act on state the rollback has already reversed, and its dependents would
431
+ * run on top of that. Started means a compensation or escalation row exists, or the graph records
432
+ * a saga state.
433
+ */
434
+ private rollbackStartedRefusal;
389
435
  /**
390
436
  * Store for the guarded JSON_MODIFY writes. The instance identity and TTL are claim-protocol
391
437
  * concerns this class never exercises — the debug writes are instance-free.
@@ -513,6 +559,14 @@ export declare class TaskGraphService {
513
559
  * agents and actions — a name in JSON cannot be joined, checked, or survive a rename.
514
560
  */
515
561
  private resolvePrompts;
562
+ /**
563
+ * Refuses a graph whose node names a compensation action by an ID that is not an action (S7).
564
+ *
565
+ * The ID is written by the model and stays in the node's JSON until a rollback inserts the
566
+ * compensation task — the first point a foreign key sees it. There an unknown ID failed the insert
567
+ * on every pass, so the step was never undone. Checked here, as the caller, before anything is written.
568
+ */
569
+ private validateCompensationActionIDs;
516
570
  private resolveActions;
517
571
  /**
518
572
  * Finds or creates the task type used for orchestrated graphs — exactly one of it, ever.
@@ -539,6 +593,8 @@ export declare class TaskGraphService {
539
593
  * situation visible rather than merely survivable.
540
594
  */
541
595
  private findTaskTypeID;
596
+ /** Why the submitted envelope cannot be stored and enforced, or null when it can (or there is none). */
597
+ private envelopeRefusal;
542
598
  /** Writes the parent task that represents the graph as a whole. */
543
599
  private persistParent;
544
600
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"TaskGraphService.d.ts","sourceRoot":"","sources":["../src/TaskGraphService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EACH,iBAAiB,EAKjB,QAAQ,EAEX,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACH,YAAY,EAKf,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAMH,KAAK,2BAA2B,EAChC,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EAEtB,MAAM,8BAA8B,CAAC;AAMtC,OAAO,EAAuB,KAAK,eAAe,EAAE,KAAK,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAExG,OAAO,EAA4B,KAAK,mBAAmB,EAAE,KAAK,UAAU,EAAE,KAAK,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAG9H;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAIrE;AAED,4DAA4D;AAC5D,MAAM,MAAM,sBAAsB,GAAG;IACjC,uCAAuC;IACvC,aAAa,EAAE,MAAM,CAAC;IACtB,qFAAqF;IACrF,oBAAoB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,kDAAkD;IAClD,WAAW,EAAE,QAAQ,CAAC;IACtB,mCAAmC;IACnC,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,oFAAoF;IACpF,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAC;IAChC;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;;OAIG;IACH,UAAU,CAAC,EAAE,2BAA2B,CAAC;IACzC,yEAAyE;IACzE,KAAK,CAAC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,EAAE,MAAM,EACd,aAAa,EAAE,OAAO,EACtB,OAAO,EAAE,sBAAsB,GAChC,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAoBvD;;;;;;;;;;OAUG;IACU,eAAe,CACxB,MAAM,EAAE,MAAM,EACd,YAAY,EAAE,OAAO,EACrB,OAAO,EAAE,sBAAsB,GAChC,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAuBvD;;;;;OAKG;YACW,aAAa;IA+E3B;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAmC5B;;;;;OAKG;YACW,cAAc;IA+B5B;;;;;;OAMG;YACW,6BAA6B;YAsC7B,cAAc;IA6B5B;;;;;;;;;;;;;OAaG;YACW,cAAc;IAmB5B;;;;;;;;OAQG;YACW,cAAc;IAuB5B,wGAAwG;IACxG,OAAO,CAAC,eAAe;IAKvB,mEAAmE;YACrD,aAAa;IAwD3B;;;;;;;OAOG;YACW,eAAe;IAsJ7B;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,mBAAmB;IAI3B,qFAAqF;YACvE,mBAAmB;YA8CnB,YAAY;CAsB7B"}
@@ -15,14 +15,15 @@
15
15
  *
16
16
  * @module @memberjunction/task-graph
17
17
  */
18
- import { LogError, LogStatus, RunInEntityTransaction, RunView, } from '@memberjunction/core';
19
- import { FormatValidationErrors, NormalizeDependency, RankGraphNodes, SanitizeInvocationEnvelope, ValidateTaskGraphSpec, ConfigOf, } from '@memberjunction/ai-core-plus';
20
- import { EscapeSQLString, UUIDsEqual } from '@memberjunction/global';
18
+ import { LogError, LogStatus, RunInEntityTransaction, RunView, ServerOperationScopeManager, } from '@memberjunction/core';
19
+ import { FormatValidationErrors, NormalizeDependency, ParseTaskSecurityEnvelope, RankGraphNodes, SerializeTaskSecurityEnvelope, SanitizeInvocationEnvelope, TASK_GRAPH_RUNTIME_SECURITY_OPERATION, TASK_GRAPH_WORKFLOW_TYPE_NAME, ValidateTaskGraphSpec, ConfigOf, } from '@memberjunction/ai-core-plus';
20
+ import { EscapeSQLString, IsValidUUID, UUIDSet, UUIDsEqual } from '@memberjunction/global';
21
21
  import { AIAgentPermissionHelper } from '@memberjunction/ai-engine-base';
22
22
  import { AIEngine } from '@memberjunction/aiengine';
23
23
  import { AgentDecisionService } from '@memberjunction/ai-agents';
24
24
  import { ResolveRecordsByNameOrToolName } from './resolve-by-tool-name.js';
25
25
  import { HeldDecisionAnswers } from './decision-node.js';
26
+ import { CompensationFromSpec, IsCompensationTask } from './saga-compensation.js';
26
27
  import { TaskClaimStore } from './TaskClaimStore.js';
27
28
  import { ParseTaskGraphDebugState } from './debug-state.js';
28
29
  import { KickTaskGraphDispatchers } from './task-graph-kick.js';
@@ -59,6 +60,13 @@ const DEFAULT_PARENT_METADATA = {
59
60
  submittedByAgentRunID: null,
60
61
  submittedByUserID: null,
61
62
  };
63
+ const VALID_SAGA_STATES = new Set([
64
+ 'Running',
65
+ 'Compensating',
66
+ 'Compensated',
67
+ 'CompensationEscalated',
68
+ 'CompensationFailed',
69
+ ]);
62
70
  /**
63
71
  * Parses a parent Task's continuation metadata.
64
72
  *
@@ -83,7 +91,13 @@ export function ParseTaskGraphParentMetadata(raw) {
83
91
  .map((name) => name.trim())
84
92
  .filter((name) => name.length > 0)
85
93
  : undefined;
86
- return {
94
+ const failurePolicy = parsed.failurePolicy === 'CompensateCompleted' || parsed.failurePolicy === 'Halt'
95
+ ? parsed.failurePolicy
96
+ : undefined;
97
+ const sagaState = VALID_SAGA_STATES.has(parsed.sagaState)
98
+ ? parsed.sagaState
99
+ : undefined;
100
+ const out = {
87
101
  ...DEFAULT_PARENT_METADATA,
88
102
  ...parsed,
89
103
  // Guard the two fields the dispatcher branches on. A JSON round-trip, a hand edit, or a
@@ -102,7 +116,14 @@ export function ParseTaskGraphParentMetadata(raw) {
102
116
  parentAgentHierarchy: parentAgentHierarchy && parentAgentHierarchy.length > 0
103
117
  ? parentAgentHierarchy
104
118
  : undefined,
119
+ ...(failurePolicy !== undefined ? { failurePolicy } : {}),
120
+ ...(sagaState !== undefined ? { sagaState } : {}),
105
121
  };
122
+ if (failurePolicy === undefined)
123
+ delete out.failurePolicy;
124
+ if (sagaState === undefined)
125
+ delete out.sagaState;
126
+ return out;
106
127
  }
107
128
  catch {
108
129
  return { ...DEFAULT_PARENT_METADATA };
@@ -124,8 +145,11 @@ export function BuildTaskGraphParentInputPayload(args) {
124
145
  continuation: args.continuation,
125
146
  reinvokeDepth: args.reinvokeDepth,
126
147
  failureSemantics: args.failureSemantics,
148
+ ...(args.failurePolicy && args.failurePolicy !== 'Halt' ? { failurePolicy: args.failurePolicy } : {}),
149
+ ...(args.sagaState ? { sagaState: args.sagaState } : {}),
127
150
  submittedByAgentRunID: args.submittedByAgentRunID,
128
151
  submittedByUserID: args.submittedByUserID,
152
+ recordsTaint: true,
129
153
  ...(parentAgentHierarchy.length > 0 ? { parentAgentHierarchy } : {}),
130
154
  ...(args.invocation
131
155
  ? { invocation: { data: args.invocation.data, context: args.invocation.context } }
@@ -155,7 +179,7 @@ export function IsReinvokeCapReached(meta) {
155
179
  return meta.reinvokeDepth >= MAX_REINVOKE_DEPTH;
156
180
  }
157
181
  /** Name of the task type used for agent-orchestrated graphs. */
158
- export const TASK_TYPE_NAME = 'AI Workflow';
182
+ export const TASK_TYPE_NAME = TASK_GRAPH_WORKFLOW_TYPE_NAME;
159
183
  /**
160
184
  * The node kinds a `Task` row can actually represent, and therefore the ones the dispatcher can run.
161
185
  *
@@ -244,6 +268,11 @@ export function BuildStepConfiguration(node) {
244
268
  config.inputMapping = inputMapping;
245
269
  if (outputMapping)
246
270
  config.outputMapping = outputMapping;
271
+ // Every setting the spec's compensation names travels, `retryCount` and the `compensationInputMapping`
272
+ // alias included (folded into `inputMapping`): dropping them made a spec's retry and mapping vanish.
273
+ const compensation = CompensationFromSpec(action?.compensation);
274
+ if (compensation)
275
+ config.compensation = compensation;
247
276
  if (node.policy) {
248
277
  config.policy = {
249
278
  timeoutSeconds: node.policy.timeoutSeconds,
@@ -297,11 +326,25 @@ export function DecisionPromptNameOf(node) {
297
326
  return null;
298
327
  return decision.promptName?.trim() || AgentDecisionService.DEFAULT_PROMPT_NAME;
299
328
  }
300
- /** Every action name a node references, including the action(s) a loop repeats. */
329
+ /** The distinct non-blank IDs in `values`, compared as UUIDs, in first-seen order. */
330
+ function uniqueIDs(values) {
331
+ const seen = new UUIDSet();
332
+ const out = [];
333
+ for (const value of values) {
334
+ if (!value || seen.Has(value))
335
+ continue;
336
+ seen.Add(value);
337
+ out.push(value);
338
+ }
339
+ return out;
340
+ }
341
+ /** Every action name a node references, including the action(s) a loop repeats and any named compensation action. */
301
342
  function actionNamesIn(node) {
302
343
  const loopOp = LoopOperationOf(node);
344
+ const actionCfg = ConfigOf(node, 'Action');
303
345
  const names = [
304
- ConfigOf(node, 'Action')?.actionName,
346
+ actionCfg?.actionName,
347
+ actionCfg?.compensation?.compensationActionName,
305
348
  loopOp?.action?.name,
306
349
  ...(loopOp?.steps?.map((s) => s.name) ?? []),
307
350
  ];
@@ -443,6 +486,14 @@ export class TaskGraphService {
443
486
  */
444
487
  this.debugWrites = new TaskClaimStore('task-graph-service', 0);
445
488
  }
489
+ /**
490
+ * Saves a row of a graph inside {@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}, bound to the caller: a workflow, its
491
+ * steps and its edges are written only by this service and the dispatcher (`MJTaskEntityServer`,
492
+ * `MJTaskDependencyEntityServer`), so a graph is created and changed through the service, never by an ordinary save.
493
+ */
494
+ saveAsService(row, entityName, context) {
495
+ return ServerOperationScopeManager.Instance.RunWithAuthority({ operationKey: TASK_GRAPH_RUNTIME_SECURITY_OPERATION, source: 'ServerEngine', allowedEntities: [entityName], userId: context.ContextUser.ID }, () => row.Save());
496
+ }
446
497
  /**
447
498
  * Validates and persists a task graph, returning as soon as it is durable.
448
499
  *
@@ -490,6 +541,13 @@ export class TaskGraphService {
490
541
  LogError(`[TaskGraphService] ${message}`);
491
542
  return { Success: false, ErrorMessage: message };
492
543
  }
544
+ // 1d. The security envelope must read back as the one written, or every node would be refused
545
+ // after the graph is already persisted. Refused here, before anything is written.
546
+ const envelopeRefusal = this.envelopeRefusal(context.SecurityEnvelope);
547
+ if (envelopeRefusal) {
548
+ LogError(`[TaskGraphService] "${spec.workflowName}" was not started: ${envelopeRefusal}`);
549
+ return { Success: false, ErrorMessage: envelopeRefusal };
550
+ }
493
551
  try {
494
552
  // 2. Resolve every agent, action, and prompt in parallel BEFORE writing anything. An
495
553
  // unresolvable name is a hard error, not a skipped node: silently dropping a task
@@ -512,6 +570,11 @@ export class TaskGraphService {
512
570
  if (!promptIDsByName.Success) {
513
571
  return { Success: false, ErrorMessage: promptIDsByName.ErrorMessage };
514
572
  }
573
+ const compensationCheck = await this.validateCompensationActionIDs(spec, context);
574
+ if (!compensationCheck.Success) {
575
+ LogError(`[TaskGraphService] ${compensationCheck.ErrorMessage}`);
576
+ return { Success: false, ErrorMessage: compensationCheck.ErrorMessage };
577
+ }
515
578
  const taskTypeID = await this.ensureTaskType(context);
516
579
  // 3. Persist — ALL of it, or none of it.
517
580
  //
@@ -792,17 +855,27 @@ export class TaskGraphService {
792
855
  * past this node.
793
856
  */
794
857
  async Retry(taskID, context, inputPayload) {
858
+ return (await this.RetryTask(taskID, context, inputPayload)).Success;
859
+ }
860
+ /** {@link Retry}, with the reason when the retry is refused, for a caller that shows it to a person. */
861
+ async RetryTask(taskID, context, inputPayload) {
795
862
  try {
796
863
  const task = await context.Provider.GetEntityObject('MJ: Tasks', context.ContextUser);
797
864
  if (!(await task.Load(taskID)))
798
- return false;
865
+ return { Success: false, ErrorMessage: 'The task could not be loaded.' };
799
866
  const editedInput = inputPayload === undefined
800
867
  ? undefined
801
868
  : typeof inputPayload === 'string' ? inputPayload : JSON.stringify(inputPayload);
802
869
  const refusal = RetryRefusal(task, editedInput);
803
870
  if (refusal) {
804
871
  LogError(`[TaskGraphService] Cannot retry task ${taskID}: ${refusal}.`);
805
- return false;
872
+ return { Success: false, ErrorMessage: `The task cannot be retried: ${refusal}.` };
873
+ }
874
+ const siblings = task.ParentID ? await this.loadChildren(task.ParentID, context) : [];
875
+ const rollingBack = task.ParentID ? await this.rollbackStartedRefusal(task.ParentID, siblings, context) : null;
876
+ if (rollingBack) {
877
+ LogError(`[TaskGraphService] Cannot retry task ${taskID}: ${rollingBack}`);
878
+ return { Success: false, ErrorMessage: rollingBack };
806
879
  }
807
880
  const expectedStatus = task.Status === 'Complete' ? 'Complete' : 'Failed';
808
881
  // An edited input rides the retry: the operator saw WHY it failed and is re-running the
@@ -820,30 +893,49 @@ export class TaskGraphService {
820
893
  const wrote = await this.debugWrites.TryUpdateInputPayload(context.Provider, taskID, json, expectedStatus, typeID, context.ContextUser);
821
894
  if (!wrote) {
822
895
  LogError(`[TaskGraphService] Could not apply the edited input to task ${taskID}; retry refused rather than re-running the old brief.`);
823
- return false;
896
+ return { Success: false, ErrorMessage: 'The edited input could not be saved, so the task was not retried.' };
824
897
  }
825
898
  // Keep the in-memory row in step with what was just written, so the save below does
826
899
  // not put the old input back.
827
900
  task.InputPayload = json;
828
901
  }
829
902
  PrepareTaskForRetry(task);
830
- if (!(await task.Save()))
831
- return false;
832
- if (task.ParentID) {
833
- for (const sibling of await this.loadChildren(task.ParentID, context)) {
834
- if (sibling.Status === 'Blocked') {
835
- sibling.Status = 'Pending';
836
- await sibling.Save();
837
- }
903
+ // A workflow step's status and data are the dispatcher's (`MJTaskEntityServer`): this save carries the
904
+ // input the guarded statement above just wrote and a retried Decision's cleared output, and the
905
+ // unblocking below changes siblings' status, so they run in the service's scope.
906
+ if (!(await this.saveAsService(task, 'MJ: Tasks', context)))
907
+ return { Success: false, ErrorMessage: 'The task could not be saved.' };
908
+ for (const sibling of siblings) {
909
+ if (sibling.Status === 'Blocked') {
910
+ sibling.Status = 'Pending';
911
+ await this.saveAsService(sibling, 'MJ: Tasks', context);
838
912
  }
839
913
  }
840
- return true;
914
+ return { Success: true };
841
915
  }
842
916
  catch (e) {
843
917
  LogError(`[TaskGraphService] Retry failed for ${taskID}: ${e instanceof Error ? e.message : String(e)}`);
844
- return false;
918
+ return { Success: false, ErrorMessage: 'The retry failed.' };
845
919
  }
846
920
  }
921
+ /**
922
+ * Why no step of this graph may be retried, or null (S9): its rollback has started. A saga
923
+ * (`failurePolicy: 'CompensateCompleted'`) undoes the completed steps after a failure, so re-running
924
+ * the failed step would act on state the rollback has already reversed, and its dependents would
925
+ * run on top of that. Started means a compensation or escalation row exists, or the graph records
926
+ * a saga state.
927
+ */
928
+ async rollbackStartedRefusal(parentTaskID, siblings, context) {
929
+ const refusal = 'The workflow has started rolling back the steps that completed, so a step cannot be retried: ' +
930
+ 'it would run against state the rollback has undone. Submit the workflow again instead.';
931
+ if (siblings.some((t) => IsCompensationTask(t)))
932
+ return refusal;
933
+ const parent = await context.Provider.GetEntityObject('MJ: Tasks', context.ContextUser);
934
+ if (!(await parent.Load(parentTaskID)))
935
+ return null;
936
+ const sagaState = ParseTaskGraphParentMetadata(parent.InputPayload).sagaState;
937
+ return sagaState && sagaState !== 'Running' ? refusal : null;
938
+ }
847
939
  /** Result shape shared by the control verbs: what happened, and the state that now holds. */
848
940
  controlResult(success, debug, errorMessage) {
849
941
  return { Success: success, Debug: debug, ErrorMessage: errorMessage };
@@ -1242,6 +1334,44 @@ export class TaskGraphService {
1242
1334
  }
1243
1335
  return { Success: true, Map: found };
1244
1336
  }
1337
+ /**
1338
+ * Refuses a graph whose node names a compensation action by an ID that is not an action (S7).
1339
+ *
1340
+ * The ID is written by the model and stays in the node's JSON until a rollback inserts the
1341
+ * compensation task — the first point a foreign key sees it. There an unknown ID failed the insert
1342
+ * on every pass, so the step was never undone. Checked here, as the caller, before anything is written.
1343
+ */
1344
+ async validateCompensationActionIDs(spec, context) {
1345
+ const ids = uniqueIDs(spec.tasks.map((node) => ConfigOf(node, 'Action')?.compensation?.compensationActionId?.trim() ?? ''));
1346
+ if (ids.length === 0)
1347
+ return { Success: true };
1348
+ const notIDs = ids.filter((id) => !IsValidUUID(id));
1349
+ if (notIDs.length > 0) {
1350
+ return {
1351
+ Success: false,
1352
+ ErrorMessage: `Task graph "${spec.workflowName}" was not started: ${notIDs.length} compensationActionId value(s) are not action IDs (${notIDs.join(', ')}). Name the action with compensationActionName instead.`,
1353
+ };
1354
+ }
1355
+ const result = await RunView.FromMetadataProvider(context.Provider).RunView({
1356
+ EntityName: 'MJ: Actions',
1357
+ ExtraFilter: `ID IN (${ids.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`,
1358
+ Fields: ['ID'],
1359
+ ResultType: 'simple',
1360
+ }, context.ContextUser);
1361
+ if (!result.Success) {
1362
+ return { Success: false, ErrorMessage: `Task graph "${spec.workflowName}" was not started: its compensation actions could not be checked (${result.ErrorMessage}).` };
1363
+ }
1364
+ const found = new UUIDSet((result.Results ?? []).map((row) => row.ID));
1365
+ const missing = ids.filter((id) => !found.Has(id));
1366
+ if (missing.length > 0) {
1367
+ return {
1368
+ Success: false,
1369
+ ErrorMessage: `Task graph "${spec.workflowName}" was not started: it names ${missing.length} compensation action(s) that do not exist (${missing.join(', ')}). ` +
1370
+ `Its rollback could never run them.`,
1371
+ };
1372
+ }
1373
+ return { Success: true };
1374
+ }
1245
1375
  async resolveActions(spec, context) {
1246
1376
  // Includes a loop's repeated action(s) — see the note in resolveAgents.
1247
1377
  const names = [...new Set(spec.tasks.flatMap(actionNamesIn))];
@@ -1324,6 +1454,11 @@ export class TaskGraphService {
1324
1454
  }
1325
1455
  return rows[0]?.ID ?? null;
1326
1456
  }
1457
+ /** Why the submitted envelope cannot be stored and enforced, or null when it can (or there is none). */
1458
+ envelopeRefusal(envelope) {
1459
+ const parsed = ParseTaskSecurityEnvelope(SerializeTaskSecurityEnvelope(envelope));
1460
+ return parsed.Status === 'Invalid' ? parsed.Reason : null;
1461
+ }
1327
1462
  /** Writes the parent task that represents the graph as a whole. */
1328
1463
  async persistParent(spec, taskTypeID, context) {
1329
1464
  const parent = await context.Provider.GetEntityObject('MJ: Tasks', context.ContextUser);
@@ -1363,6 +1498,7 @@ export class TaskGraphService {
1363
1498
  continuation: spec.continuation ?? 'message',
1364
1499
  reinvokeDepth: context.ReinvokeDepth ?? 0,
1365
1500
  failureSemantics: spec.failureSemantics ?? 'block',
1501
+ failurePolicy: spec.failurePolicy ?? 'Halt',
1366
1502
  submittedByAgentRunID: context.AgentRunID ?? null,
1367
1503
  submittedByUserID: context.ContextUser?.ID ?? null,
1368
1504
  parentAgentHierarchy: context.ParentAgentHierarchy,
@@ -1371,7 +1507,8 @@ export class TaskGraphService {
1371
1507
  : null,
1372
1508
  startPaused: context.Debug?.paused === true,
1373
1509
  }));
1374
- if (!(await parent.Save())) {
1510
+ parent.SecurityEnvelope = SerializeTaskSecurityEnvelope(context.SecurityEnvelope);
1511
+ if (!(await this.saveAsService(parent, 'MJ: Tasks', context))) {
1375
1512
  throw new Error(`Could not create parent task: ${parent.LatestResult?.CompleteMessage ?? 'unknown error'}`);
1376
1513
  }
1377
1514
  return parent.ID;
@@ -1479,15 +1616,30 @@ export class TaskGraphService {
1479
1616
  .map((s) => [s.name, actionIDsByName.get(s.name)])
1480
1617
  .filter((entry) => typeof entry[1] === 'string' && entry[1].length > 0))
1481
1618
  : undefined;
1619
+ const builtConfig = buildStepConfiguration(node);
1620
+ const resolvedCompensation = builtConfig?.compensation
1621
+ ? {
1622
+ ...builtConfig.compensation,
1623
+ ...(!builtConfig.compensation.compensationActionId &&
1624
+ builtConfig.compensation.compensationActionName &&
1625
+ actionIDsByName.get(builtConfig.compensation.compensationActionName)
1626
+ ? { compensationActionId: actionIDsByName.get(builtConfig.compensation.compensationActionName) }
1627
+ : {}),
1628
+ }
1629
+ : undefined;
1482
1630
  const configuration = {
1483
- ...buildStepConfiguration(node),
1631
+ ...builtConfig,
1632
+ ...(resolvedCompensation ? { compensation: resolvedCompensation } : {}),
1484
1633
  ...(stepActionIds && Object.keys(stepActionIds).length > 0 ? { stepActionIds } : {}),
1485
1634
  sequence: ranks.get(node.tempId),
1486
1635
  };
1487
1636
  task.Configuration = JSON.stringify(configuration);
1637
+ // Every child carries the envelope, not only the parent: a node is enforced from its
1638
+ // own row too, so losing the parent row can never run it unconstrained.
1639
+ task.SecurityEnvelope = SerializeTaskSecurityEnvelope(context.SecurityEnvelope);
1488
1640
  // Input rides in its own column; Description stays human-readable.
1489
1641
  task.InputPayload = node.inputPayload ? JSON.stringify(node.inputPayload) : null;
1490
- if (!(await task.Save())) {
1642
+ if (!(await this.saveAsService(task, 'MJ: Tasks', context))) {
1491
1643
  throw new Error(`Could not create task "${node.name}": ${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
1492
1644
  }
1493
1645
  map.set(node.tempId, task.ID);
@@ -1543,7 +1695,7 @@ export class TaskGraphService {
1543
1695
  dep.ExclusiveGroup = edge.exclusiveGroup ?? null;
1544
1696
  dep.Priority = edge.priority ?? 0;
1545
1697
  dep.Sequence = edge.sequence ?? 0;
1546
- if (!(await dep.Save())) {
1698
+ if (!(await this.saveAsService(dep, 'MJ: Task Dependencies', context))) {
1547
1699
  throw new Error(`Could not create dependency ${node.tempId} -> ${edge.tempId}: ${dep.LatestResult?.CompleteMessage ?? 'unknown error'}`);
1548
1700
  }
1549
1701
  })());