@memberjunction/task-graph 6.2.0 → 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
@@ -31,7 +31,7 @@ import { TaskGraphSubmitOperation, TaskGraphCancelOperation, TaskGraphRetryTaskO
31
31
  import { ComputeParentRollup } from '@memberjunction/ai-core-plus';
32
32
  import { ClampReinvokeDepth, TaskGraphService } from '../TaskGraphService.js';
33
33
  import { LoadWorkflowDraftOperation } from './WorkflowDraftOperation.js';
34
- import { LoadTaskGraphDebugOperations } from './TaskGraphDebugOperations.js';
34
+ import { LoadTaskGraphDebugOperations, AuthorizeGraphControl, GraphOfTask } from './TaskGraphDebugOperations.js';
35
35
  /**
36
36
  * Builds the service context from the operation's provider + user.
37
37
  *
@@ -198,12 +198,17 @@ let TaskGraphRetryTaskServerOperation = class TaskGraphRetryTaskServerOperation
198
198
  input, provider, user) {
199
199
  if (!input?.taskID)
200
200
  throw new Error('taskID is required');
201
- const ok = await new TaskGraphService().Retry(input.taskID, submitContext(provider, user, ''), input.inputPayload);
202
- if (!ok) {
203
- return {
204
- success: false,
205
- errorMessage: 'Retry failed; the task may be neither Failed nor a Decision step holding an answer below its minConfidence.',
206
- };
201
+ // Only the run's owner retries its steps, as with the debug verbs: a retry can carry an edited input,
202
+ // and its save writes the step in the dispatcher's scope.
203
+ const graph = await GraphOfTask(input.taskID, provider, user);
204
+ if ('error' in graph)
205
+ return { success: false, errorMessage: graph.error };
206
+ const denied = await AuthorizeGraphControl(graph.parentTaskID, provider, user);
207
+ if (denied)
208
+ return { success: false, errorMessage: denied };
209
+ const outcome = await new TaskGraphService().RetryTask(input.taskID, submitContext(provider, user, ''), input.inputPayload);
210
+ if (!outcome.Success) {
211
+ return { success: false, errorMessage: outcome.ErrorMessage ?? 'The task could not be retried.' };
207
212
  }
208
213
  const task = await provider.GetEntityObject('MJ: Tasks', user);
209
214
  const loaded = await task.Load(input.taskID);
@@ -1 +1 @@
1
- {"version":3,"file":"Task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 * @fileoverview Pure saga-compensation rules for `TaskGraphDispatcher` (WS-4.3).
3
+ *
4
+ * When a task graph runs with `failurePolicy: 'CompensateCompleted'` and a forward step fails
5
+ * unhandled, the dispatcher undoes the completed `Action` steps that declare a compensation action
6
+ * (on the workflow node, {@link ActionCompensationSpec}, or on the `MJ: Actions` row), in **reverse
7
+ * topological order**, one at a time. Each compensation is a child `MJ: Tasks` row linked to the step
8
+ * it undoes through `CompensatesTaskID`, whose unique index is what makes materializing it a claim:
9
+ * two dispatchers can both decide to compensate a step, and only one insert succeeds.
10
+ *
11
+ * Everything here is pure (one log line aside); the dispatcher reads the rows, asks {@link NextSagaStep} what to do, and
12
+ * does it. Because the answer is computed from durable rows on every pass, any dispatcher can pick a
13
+ * saga up where another left it.
14
+ *
15
+ * @module @memberjunction/task-graph
16
+ */
17
+ import { type ActionCompensationFailurePolicy, type ActionCompensationSpec } from '@memberjunction/ai-core-plus';
18
+ import type { MJActionEntity, MJTaskEntity } from '@memberjunction/core-entities';
19
+ import { UUIDMap } from '@memberjunction/global';
20
+ /**
21
+ * Saga lifecycle state recorded on the parent workflow task's metadata (`InputPayload.sagaState`).
22
+ * Informational: every decision is recomputed from the rows, never read back from this.
23
+ */
24
+ export type SagaExecutionState = 'Running' | 'Compensating' | 'Compensated' | 'CompensationEscalated' | 'CompensationFailed';
25
+ /**
26
+ * Compensation settings persisted in `Task.Configuration.compensation`: on a forward step, how to undo
27
+ * it; on a compensation task, the policy for its own failure.
28
+ */
29
+ export interface TaskCompensationStepMetadata {
30
+ /** The `MJ: Actions` ID of the compensation action. */
31
+ compensationActionId?: string;
32
+ /** The compensation action's name, resolved to `compensationActionId` at submit or dispatch time. */
33
+ compensationActionName?: string;
34
+ /** Compensation parameter name → path into the forward run (`input.*`, `output.*`, `actionLogId`, `recordChanges`). */
35
+ inputMapping?: Readonly<Record<string, string>> | string;
36
+ /** What to do when the compensation itself fails after its retries. Default `'EscalateToHumanTask'`. */
37
+ onCompensationFailure?: ActionCompensationFailurePolicy;
38
+ /**
39
+ * On a forward step: `false` stops its action being retried automatically. It can only narrow
40
+ * `Action.IsIdempotent`, never widen it: `true` on a non-idempotent action changes nothing.
41
+ */
42
+ isIdempotent?: boolean;
43
+ /** How many times the compensation task retries, when its action is idempotent. */
44
+ retryCount?: number;
45
+ }
46
+ /** The `MJ: Actions` fields a saga reads, typed from the generated entity. */
47
+ export type CompensatableActionRow = Pick<MJActionEntity, 'ID' | 'CompensationActionID' | 'CompensationInputMapping' | 'IsIdempotent'>;
48
+ /** The `MJ: Tasks` columns the saga planner reads. */
49
+ export type SagaTaskRow = Pick<MJTaskEntity, 'ID' | 'Name' | 'Status' | 'StepType' | 'UserID' | 'ActionID' | 'CompletedAt' | 'Configuration' | 'CompensatesTaskID'>;
50
+ /** A completed forward step to undo, and how. */
51
+ export type CompensationPlanEntry<T extends SagaTaskRow> = {
52
+ Task: T;
53
+ Compensation: TaskCompensationStepMetadata;
54
+ };
55
+ /** What the dispatcher does next for a saga. */
56
+ export type SagaStep<T extends SagaTaskRow> =
57
+ /** A compensation or an escalation is still running, or a forward step is still finishing. */
58
+ {
59
+ Kind: 'Wait';
60
+ }
61
+ /** Create the compensation task for this forward step. */
62
+ | {
63
+ Kind: 'Compensate';
64
+ Forward: T;
65
+ Compensation: TaskCompensationStepMetadata;
66
+ }
67
+ /** Create the Human step that asks a person to undo this forward step by hand. */
68
+ | {
69
+ Kind: 'Escalate';
70
+ Forward: T;
71
+ FailedCompensation: T;
72
+ }
73
+ /** Nothing more to do; the saga ended in this state. */
74
+ | {
75
+ Kind: 'Finished';
76
+ State: SagaExecutionState;
77
+ };
78
+ /**
79
+ * Reads the compensation settings an `MJ: Actions` row declares through its typed columns:
80
+ * `CompensationActionID`, `CompensationInputMapping` (a JSON object of parameter → path) and
81
+ * `IsIdempotent`. `null` when the action names no compensation action.
82
+ */
83
+ export declare function ReadActionCompensationMetadata(action: CompensatableActionRow | null | undefined): TaskCompensationStepMetadata | null;
84
+ /**
85
+ * Combines an action's default compensation with a workflow node's own: every field the node sets
86
+ * wins. `null` when neither names a compensation action.
87
+ */
88
+ export declare function MergeActionCompensationSpecs(actionDefault: TaskCompensationStepMetadata | null | undefined, nodeOverride: TaskCompensationStepMetadata | null | undefined): TaskCompensationStepMetadata | null;
89
+ /**
90
+ * The compensation settings a workflow node's spec declares (`configuration.compensation`), in the
91
+ * shape a step stores. `inputMapping` and its alias `compensationInputMapping` are one setting.
92
+ */
93
+ export declare function CompensationFromSpec(spec: ActionCompensationSpec | undefined): TaskCompensationStepMetadata | undefined;
94
+ /**
95
+ * Reads `Task.Configuration.compensation` from a serialized `Configuration`.
96
+ */
97
+ export declare function ReadTaskCompensationMetadata(configurationJson: string | null | undefined): TaskCompensationStepMetadata | null;
98
+ /** True for a task that undoes another (a compensation task, or the Human step escalating a failed one). */
99
+ export declare function IsCompensationTask(row: Pick<MJTaskEntity, 'CompensatesTaskID'>): boolean;
100
+ /**
101
+ * The completed forward `Action` steps a saga undoes, in **reverse topological order**: deeper steps
102
+ * first (by the submit-time `sequence`, else the dependency depth), then later `CompletedAt`, then ID.
103
+ * A step is included when its node or its action names a compensation action.
104
+ *
105
+ * @param actionDefaults the compensation each action's own row declares, keyed by Action ID
106
+ */
107
+ export declare function SelectTasksToCompensate<T extends SagaTaskRow>(tasks: readonly T[], actionDefaults: UUIDMap<TaskCompensationStepMetadata>, dependencies?: ReadonlyArray<{
108
+ TaskID: string;
109
+ DependsOnTaskID: string;
110
+ }>): Array<CompensationPlanEntry<T>>;
111
+ /**
112
+ * What a saga does next, from the rows alone. Walks the plan in order:
113
+ *
114
+ * - no compensation task for a step yet → create it (`Compensate`), one at a time;
115
+ * - a compensation task still `Pending` or `In Progress` → `Wait`;
116
+ * - a compensation that `Complete`d → next step;
117
+ * - a compensation that failed, by its `onCompensationFailure`:
118
+ * - `'ContinueCompensation'` → next step (the saga ends `CompensationFailed`);
119
+ * - `'HaltSaga'` → stop: `Finished` with `CompensationFailed`;
120
+ * - `'EscalateToHumanTask'` (default) → create a Human step (`Escalate`) and wait on it. When the
121
+ * person completes it, they have undone the step by hand and the saga resumes with the next step;
122
+ * when the Human step ends any other way (cancelled, skipped, failed, expired), the saga stops:
123
+ * `Finished` with `CompensationEscalated`.
124
+ *
125
+ * @param compensationFor the task whose `CompensatesTaskID` is the forward step, if any
126
+ * @param escalationFor the Human step whose `CompensatesTaskID` is the failed compensation task, if any
127
+ */
128
+ export declare function NextSagaStep<T extends SagaTaskRow>(args: {
129
+ Plan: ReadonlyArray<CompensationPlanEntry<T>>;
130
+ CompensationFor: (forwardTaskID: string) => T | undefined;
131
+ EscalationFor: (compensationTaskID: string) => T | undefined;
132
+ }): SagaStep<T>;
133
+ /** Indexes the rows that undo another by the row they undo (`CompensatesTaskID`), split into tasks and Human escalations. */
134
+ export declare function IndexCompensationRows<T extends SagaTaskRow>(rows: readonly T[]): {
135
+ Compensations: UUIDMap<T>;
136
+ Escalations: UUIDMap<T>;
137
+ };
138
+ /** Exponential backoff before retry `attempt` (1-based): base, 2×base, 4×base…, capped at 30× base. */
139
+ export declare function RetryBackoffMs(attempt: number, baseMs: number): number;
140
+ /**
141
+ * Builds the `InputPayload` for a compensation task from the forward step's inputs, outputs,
142
+ * `ActionLogID`, and correlated `RecordChanges` rows.
143
+ */
144
+ export declare function BuildCompensationInputPayload(args: {
145
+ ForwardInput: Record<string, unknown>;
146
+ ForwardOutput: Record<string, unknown>;
147
+ ActionLogID?: string | null;
148
+ RecordChanges?: readonly Record<string, unknown>[];
149
+ InputMapping?: Readonly<Record<string, string>> | string | null;
150
+ }): Record<string, unknown>;
151
+ /**
152
+ * Formats the request a person sees when a compensation fails under
153
+ * `onCompensationFailure: 'EscalateToHumanTask'`.
154
+ */
155
+ export declare function BuildCompensationEscalationSummary(args: {
156
+ WorkflowName: string;
157
+ ForwardTask: Pick<MJTaskEntity, 'ID' | 'Name' | 'OutputPayload'>;
158
+ /** The parameters the forward step's action was given (`runtime.actionInput`). */
159
+ ForwardInput: Record<string, unknown>;
160
+ CompensationTask: Pick<MJTaskEntity, 'ID' | 'Name' | 'InputPayload' | 'ErrorMessage'>;
161
+ ActionLogID?: string | null;
162
+ RecordChanges?: readonly Record<string, unknown>[];
163
+ }): {
164
+ RequestText: string;
165
+ ContextData: Record<string, unknown>;
166
+ };
167
+ //# sourceMappingURL=saga-compensation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"saga-compensation.d.ts","sourceRoot":"","sources":["../src/saga-compensation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAEH,KAAK,+BAA+B,EACpC,KAAK,sBAAsB,EAC9B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,KAAK,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClF,OAAO,EAAE,OAAO,EAAW,MAAM,wBAAwB,CAAC;AAG1D;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GACxB,SAAS,GACT,cAAc,GACd,aAAa,GACb,uBAAuB,GACvB,oBAAoB,CAAC;AAE3B;;;GAGG;AACH,MAAM,WAAW,4BAA4B;IACzC,uDAAuD;IACvD,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,qGAAqG;IACrG,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,uHAAuH;IACvH,YAAY,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,MAAM,CAAC;IACzD,wGAAwG;IACxG,qBAAqB,CAAC,EAAE,+BAA+B,CAAC;IACxD;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,mFAAmF;IACnF,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,8EAA8E;AAC9E,MAAM,MAAM,sBAAsB,GAAG,IAAI,CAAC,cAAc,EAAE,IAAI,GAAG,sBAAsB,GAAG,0BAA0B,GAAG,cAAc,CAAC,CAAC;AAEvI,sDAAsD;AACtD,MAAM,MAAM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,CAAC,CAAC;IACtC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,aAAa,CAAC,EAAE,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IACnD,YAAY,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC;CACnE,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAoC1B;AAED;;;GAGG;AACH,wBAAgB,kCAAkC,CAAC,IAAI,EAAE;IACrD,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,GAAG,MAAM,GAAG,eAAe,CAAC,CAAC;IACjE,kFAAkF;IAClF,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACtC,gBAAgB,EAAE,IAAI,CAAC,YAAY,EAAE,IAAI,GAAG,MAAM,GAAG,cAAc,GAAG,cAAc,CAAC,CAAC;IACtF,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,aAAa,CAAC,EAAE,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;CACtD,GAAG;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,CAqBhE"}
@@ -0,0 +1,392 @@
1
+ /**
2
+ * @fileoverview Pure saga-compensation rules for `TaskGraphDispatcher` (WS-4.3).
3
+ *
4
+ * When a task graph runs with `failurePolicy: 'CompensateCompleted'` and a forward step fails
5
+ * unhandled, the dispatcher undoes the completed `Action` steps that declare a compensation action
6
+ * (on the workflow node, {@link ActionCompensationSpec}, or on the `MJ: Actions` row), in **reverse
7
+ * topological order**, one at a time. Each compensation is a child `MJ: Tasks` row linked to the step
8
+ * it undoes through `CompensatesTaskID`, whose unique index is what makes materializing it a claim:
9
+ * two dispatchers can both decide to compensate a step, and only one insert succeeds.
10
+ *
11
+ * Everything here is pure (one log line aside); the dispatcher reads the rows, asks {@link NextSagaStep} what to do, and
12
+ * does it. Because the answer is computed from durable rows on every pass, any dispatcher can pick a
13
+ * saga up where another left it.
14
+ *
15
+ * @module @memberjunction/task-graph
16
+ */
17
+ import { GetValueFromPath, } from '@memberjunction/ai-core-plus';
18
+ import { LogError } from '@memberjunction/core';
19
+ import { UUIDMap, UUIDSet } from '@memberjunction/global';
20
+ import { IsHumanTask } from './task-predicates.js';
21
+ /**
22
+ * Reads the compensation settings an `MJ: Actions` row declares through its typed columns:
23
+ * `CompensationActionID`, `CompensationInputMapping` (a JSON object of parameter → path) and
24
+ * `IsIdempotent`. `null` when the action names no compensation action.
25
+ */
26
+ export function ReadActionCompensationMetadata(action) {
27
+ const compensationActionId = asNonEmptyString(action?.CompensationActionID);
28
+ if (!action || !compensationActionId)
29
+ return null;
30
+ const inputMapping = parseMappingDictionary(action.CompensationInputMapping);
31
+ return {
32
+ compensationActionId,
33
+ ...(inputMapping ? { inputMapping } : {}),
34
+ ...(typeof action.IsIdempotent === 'boolean' ? { isIdempotent: action.IsIdempotent } : {}),
35
+ };
36
+ }
37
+ /**
38
+ * Combines an action's default compensation with a workflow node's own: every field the node sets
39
+ * wins. `null` when neither names a compensation action.
40
+ */
41
+ export function MergeActionCompensationSpecs(actionDefault, nodeOverride) {
42
+ const compensationActionId = asNonEmptyString(nodeOverride?.compensationActionId) ?? asNonEmptyString(actionDefault?.compensationActionId);
43
+ const compensationActionName = asNonEmptyString(nodeOverride?.compensationActionName) ?? asNonEmptyString(actionDefault?.compensationActionName);
44
+ if (!compensationActionId && !compensationActionName)
45
+ return null;
46
+ const inputMapping = nodeOverride?.inputMapping ?? actionDefault?.inputMapping;
47
+ const onCompensationFailure = nodeOverride?.onCompensationFailure ?? actionDefault?.onCompensationFailure;
48
+ const retryCount = nodeOverride?.retryCount ?? actionDefault?.retryCount;
49
+ return {
50
+ ...(compensationActionId ? { compensationActionId } : {}),
51
+ ...(compensationActionName ? { compensationActionName } : {}),
52
+ ...(inputMapping !== undefined ? { inputMapping } : {}),
53
+ onCompensationFailure: onCompensationFailure ?? 'EscalateToHumanTask',
54
+ ...(retryCount !== undefined ? { retryCount } : {}),
55
+ };
56
+ }
57
+ /**
58
+ * The compensation settings a workflow node's spec declares (`configuration.compensation`), in the
59
+ * shape a step stores. `inputMapping` and its alias `compensationInputMapping` are one setting.
60
+ */
61
+ export function CompensationFromSpec(spec) {
62
+ if (!spec)
63
+ return undefined;
64
+ const inputMapping = spec.inputMapping ?? spec.compensationInputMapping;
65
+ const retryCount = normalizeRetryCount(spec.retryCount);
66
+ return {
67
+ ...(asNonEmptyString(spec.compensationActionId) ? { compensationActionId: spec.compensationActionId } : {}),
68
+ ...(asNonEmptyString(spec.compensationActionName) ? { compensationActionName: spec.compensationActionName } : {}),
69
+ ...(inputMapping !== undefined ? { inputMapping } : {}),
70
+ ...(spec.onCompensationFailure ? { onCompensationFailure: spec.onCompensationFailure } : {}),
71
+ ...(typeof spec.isIdempotent === 'boolean' ? { isIdempotent: spec.isIdempotent } : {}),
72
+ ...(retryCount !== undefined ? { retryCount } : {}),
73
+ };
74
+ }
75
+ /**
76
+ * Reads `Task.Configuration.compensation` from a serialized `Configuration`.
77
+ */
78
+ export function ReadTaskCompensationMetadata(configurationJson) {
79
+ if (!configurationJson)
80
+ return null;
81
+ try {
82
+ const parsed = JSON.parse(configurationJson);
83
+ if (!isRecord(parsed) || !isRecord(parsed.compensation))
84
+ return null;
85
+ const comp = parsed.compensation;
86
+ const inputMapping = normalizeMappingField(comp.inputMapping ?? comp.compensationInputMapping);
87
+ const onFailure = normalizeFailurePolicy(comp.onCompensationFailure);
88
+ const retryCount = normalizeRetryCount(comp.retryCount);
89
+ return {
90
+ ...(asNonEmptyString(comp.compensationActionId) ? { compensationActionId: asNonEmptyString(comp.compensationActionId) } : {}),
91
+ ...(asNonEmptyString(comp.compensationActionName) ? { compensationActionName: asNonEmptyString(comp.compensationActionName) } : {}),
92
+ ...(inputMapping !== undefined ? { inputMapping } : {}),
93
+ ...(onFailure ? { onCompensationFailure: onFailure } : {}),
94
+ ...(typeof comp.isIdempotent === 'boolean' ? { isIdempotent: comp.isIdempotent } : {}),
95
+ ...(retryCount !== undefined ? { retryCount } : {}),
96
+ };
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
102
+ /** True for a task that undoes another (a compensation task, or the Human step escalating a failed one). */
103
+ export function IsCompensationTask(row) {
104
+ return !!row.CompensatesTaskID;
105
+ }
106
+ /**
107
+ * The completed forward `Action` steps a saga undoes, in **reverse topological order**: deeper steps
108
+ * first (by the submit-time `sequence`, else the dependency depth), then later `CompletedAt`, then ID.
109
+ * A step is included when its node or its action names a compensation action.
110
+ *
111
+ * @param actionDefaults the compensation each action's own row declares, keyed by Action ID
112
+ */
113
+ export function SelectTasksToCompensate(tasks, actionDefaults, dependencies = []) {
114
+ const depthByTask = computeTopologicalDepthByTaskId(tasks, dependencies);
115
+ const candidates = [];
116
+ for (const row of tasks) {
117
+ if (row.Status !== 'Complete' || IsCompensationTask(row) || !row.ActionID)
118
+ continue;
119
+ if (row.StepType && row.StepType !== 'Action')
120
+ continue;
121
+ const compensation = MergeActionCompensationSpecs(actionDefaults.Get(row.ActionID), ReadTaskCompensationMetadata(row.Configuration));
122
+ if (!compensation)
123
+ continue;
124
+ const sequence = readSequenceFromConfiguration(row.Configuration);
125
+ candidates.push({
126
+ Task: row,
127
+ Compensation: compensation,
128
+ Rank: sequence >= 0 ? sequence : depthByTask.Get(row.ID) ?? 0,
129
+ CompletedAtMs: parseTimestampMs(row.CompletedAt),
130
+ });
131
+ }
132
+ candidates.sort((a, b) => b.Rank - a.Rank || b.CompletedAtMs - a.CompletedAtMs || b.Task.ID.localeCompare(a.Task.ID));
133
+ return candidates.map(({ Task, Compensation }) => ({ Task, Compensation }));
134
+ }
135
+ /**
136
+ * What a saga does next, from the rows alone. Walks the plan in order:
137
+ *
138
+ * - no compensation task for a step yet → create it (`Compensate`), one at a time;
139
+ * - a compensation task still `Pending` or `In Progress` → `Wait`;
140
+ * - a compensation that `Complete`d → next step;
141
+ * - a compensation that failed, by its `onCompensationFailure`:
142
+ * - `'ContinueCompensation'` → next step (the saga ends `CompensationFailed`);
143
+ * - `'HaltSaga'` → stop: `Finished` with `CompensationFailed`;
144
+ * - `'EscalateToHumanTask'` (default) → create a Human step (`Escalate`) and wait on it. When the
145
+ * person completes it, they have undone the step by hand and the saga resumes with the next step;
146
+ * when the Human step ends any other way (cancelled, skipped, failed, expired), the saga stops:
147
+ * `Finished` with `CompensationEscalated`.
148
+ *
149
+ * @param compensationFor the task whose `CompensatesTaskID` is the forward step, if any
150
+ * @param escalationFor the Human step whose `CompensatesTaskID` is the failed compensation task, if any
151
+ */
152
+ export function NextSagaStep(args) {
153
+ let anyUnresolvedFailure = false;
154
+ for (const { Task: forward, Compensation } of args.Plan) {
155
+ const compensation = args.CompensationFor(forward.ID);
156
+ if (!compensation) {
157
+ return { Kind: 'Compensate', Forward: forward, Compensation };
158
+ }
159
+ if (isActive(compensation)) {
160
+ return { Kind: 'Wait' };
161
+ }
162
+ if (compensation.Status === 'Complete') {
163
+ continue;
164
+ }
165
+ const policy = ReadTaskCompensationMetadata(compensation.Configuration)?.onCompensationFailure ?? 'EscalateToHumanTask';
166
+ if (policy === 'ContinueCompensation') {
167
+ anyUnresolvedFailure = true;
168
+ continue;
169
+ }
170
+ if (policy === 'HaltSaga') {
171
+ return { Kind: 'Finished', State: 'CompensationFailed' };
172
+ }
173
+ const escalation = args.EscalationFor(compensation.ID);
174
+ if (!escalation) {
175
+ return { Kind: 'Escalate', Forward: forward, FailedCompensation: compensation };
176
+ }
177
+ if (isActive(escalation)) {
178
+ return { Kind: 'Wait' };
179
+ }
180
+ if (escalation.Status !== 'Complete') {
181
+ return { Kind: 'Finished', State: 'CompensationEscalated' };
182
+ }
183
+ }
184
+ return { Kind: 'Finished', State: anyUnresolvedFailure ? 'CompensationFailed' : 'Compensated' };
185
+ }
186
+ /** Indexes the rows that undo another by the row they undo (`CompensatesTaskID`), split into tasks and Human escalations. */
187
+ export function IndexCompensationRows(rows) {
188
+ const compensations = new UUIDMap();
189
+ const escalations = new UUIDMap();
190
+ for (const row of rows) {
191
+ if (!row.CompensatesTaskID)
192
+ continue;
193
+ (IsHumanTask(row) ? escalations : compensations).Set(row.CompensatesTaskID, row);
194
+ }
195
+ return { Compensations: compensations, Escalations: escalations };
196
+ }
197
+ /** Exponential backoff before retry `attempt` (1-based): base, 2×base, 4×base…, capped at 30× base. */
198
+ export function RetryBackoffMs(attempt, baseMs) {
199
+ return Math.min(baseMs * 30, baseMs * 2 ** Math.max(0, attempt - 1));
200
+ }
201
+ /**
202
+ * Builds the `InputPayload` for a compensation task from the forward step's inputs, outputs,
203
+ * `ActionLogID`, and correlated `RecordChanges` rows.
204
+ */
205
+ export function BuildCompensationInputPayload(args) {
206
+ const { ForwardInput, ForwardOutput, ActionLogID = null, RecordChanges = [], InputMapping } = args;
207
+ const envelope = {
208
+ input: ForwardInput,
209
+ output: ForwardOutput,
210
+ actionLogId: ActionLogID,
211
+ actionLogID: ActionLogID,
212
+ recordChanges: RecordChanges,
213
+ payload: { ...ForwardInput, ...ForwardOutput },
214
+ };
215
+ const mappingDict = parseMappingDictionary(InputMapping);
216
+ if (!mappingDict || Object.keys(mappingDict).length === 0) {
217
+ return {
218
+ ...ForwardInput,
219
+ ...ForwardOutput,
220
+ ...(ActionLogID ? { actionLogId: ActionLogID } : {}),
221
+ ...(RecordChanges.length > 0 ? { recordChanges: RecordChanges } : {}),
222
+ };
223
+ }
224
+ const mapped = {};
225
+ const unresolved = [];
226
+ for (const [paramName, rawSource] of Object.entries(mappingDict)) {
227
+ const value = resolveCompensationMappingExpression(rawSource, envelope);
228
+ if (value === undefined) {
229
+ unresolved.push(`${paramName} ← ${rawSource}`);
230
+ }
231
+ else {
232
+ mapped[paramName] = value;
233
+ }
234
+ }
235
+ if (unresolved.length > 0) {
236
+ LogError(`[TaskGraph] Compensation input mapping left out parameters whose path resolved to nothing: ${unresolved.join(', ')}.`);
237
+ }
238
+ return mapped;
239
+ }
240
+ /**
241
+ * Formats the request a person sees when a compensation fails under
242
+ * `onCompensationFailure: 'EscalateToHumanTask'`.
243
+ */
244
+ export function BuildCompensationEscalationSummary(args) {
245
+ const errorMessage = args.CompensationTask.ErrorMessage || 'Compensation action failed without an error message.';
246
+ const contextData = {
247
+ workflowName: args.WorkflowName,
248
+ forwardTaskID: args.ForwardTask.ID,
249
+ forwardTaskName: args.ForwardTask.Name,
250
+ forwardInput: args.ForwardInput,
251
+ forwardOutput: safeParseJsonObject(args.ForwardTask.OutputPayload),
252
+ actionLogID: args.ActionLogID ?? null,
253
+ recordChanges: args.RecordChanges ?? [],
254
+ compensationTaskID: args.CompensationTask.ID,
255
+ compensationTaskName: args.CompensationTask.Name,
256
+ compensationInput: safeParseJsonObject(args.CompensationTask.InputPayload),
257
+ compensationError: errorMessage,
258
+ };
259
+ const requestText = `Saga compensation failed in workflow "${args.WorkflowName}" while rolling back step ` +
260
+ `"${args.ForwardTask.Name}" (${args.ForwardTask.ID}).\n` +
261
+ `Compensation task "${args.CompensationTask.Name}" (${args.CompensationTask.ID}) failed with error: ${errorMessage}\n` +
262
+ 'Undo the step by hand, then complete this task to let the rollback continue; cancel it to stop the rollback here.';
263
+ return { RequestText: requestText, ContextData: contextData };
264
+ }
265
+ function isActive(row) {
266
+ return row.Status === 'Pending' || row.Status === 'In Progress' || row.Status === 'Deferred';
267
+ }
268
+ function resolveCompensationMappingExpression(rawExpression, envelope) {
269
+ const trimmed = rawExpression.trim();
270
+ if (trimmed.toLowerCase().startsWith('static:')) {
271
+ return rawExpression.substring(rawExpression.indexOf(':') + 1);
272
+ }
273
+ const unwrapped = trimmed.startsWith('{{') && trimmed.endsWith('}}') ? trimmed.slice(2, -2).trim() : trimmed;
274
+ if (['input', 'output', 'actionLogId', 'actionLogID', 'recordChanges', 'payload'].includes(unwrapped)) {
275
+ return envelope[unwrapped];
276
+ }
277
+ const dotIndex = unwrapped.indexOf('.');
278
+ if (dotIndex > 0) {
279
+ const prefix = unwrapped.slice(0, dotIndex);
280
+ if (prefix === 'input' || prefix === 'output' || prefix === 'recordChanges' || prefix === 'payload') {
281
+ return GetValueFromPath(envelope[prefix], unwrapped.slice(dotIndex + 1));
282
+ }
283
+ }
284
+ // A path that names nothing is left out, never passed on as its own text: a typo must not become a
285
+ // literal parameter value of a refund or cancel.
286
+ return GetValueFromPath(envelope, unwrapped);
287
+ }
288
+ function parseMappingDictionary(mapping) {
289
+ if (!mapping)
290
+ return null;
291
+ let raw = mapping;
292
+ if (typeof mapping === 'string') {
293
+ try {
294
+ raw = JSON.parse(mapping);
295
+ }
296
+ catch {
297
+ return null;
298
+ }
299
+ }
300
+ if (!isRecord(raw))
301
+ return null;
302
+ const out = {};
303
+ for (const [k, v] of Object.entries(raw)) {
304
+ if (typeof v === 'string')
305
+ out[k] = v;
306
+ }
307
+ return Object.keys(out).length > 0 ? out : null;
308
+ }
309
+ function normalizeMappingField(raw) {
310
+ if (typeof raw === 'string' && raw.trim().length > 0)
311
+ return raw.trim();
312
+ if (isRecord(raw)) {
313
+ const out = {};
314
+ for (const [k, v] of Object.entries(raw)) {
315
+ if (typeof v === 'string')
316
+ out[k] = v;
317
+ }
318
+ return Object.keys(out).length > 0 ? out : undefined;
319
+ }
320
+ return undefined;
321
+ }
322
+ function normalizeFailurePolicy(raw) {
323
+ return raw === 'EscalateToHumanTask' || raw === 'HaltSaga' || raw === 'ContinueCompensation' ? raw : undefined;
324
+ }
325
+ function normalizeRetryCount(raw) {
326
+ return typeof raw === 'number' && Number.isFinite(raw) ? Math.max(0, Math.floor(raw)) : undefined;
327
+ }
328
+ function readSequenceFromConfiguration(configurationJson) {
329
+ if (!configurationJson)
330
+ return -1;
331
+ try {
332
+ const parsed = JSON.parse(configurationJson);
333
+ return isRecord(parsed) && typeof parsed.sequence === 'number' && Number.isFinite(parsed.sequence) ? parsed.sequence : -1;
334
+ }
335
+ catch {
336
+ return -1;
337
+ }
338
+ }
339
+ function parseTimestampMs(value) {
340
+ if (!value)
341
+ return 0;
342
+ const ms = value instanceof Date ? value.getTime() : Date.parse(value);
343
+ return Number.isFinite(ms) ? ms : 0;
344
+ }
345
+ function safeParseJsonObject(raw) {
346
+ if (!raw)
347
+ return {};
348
+ try {
349
+ const parsed = JSON.parse(raw);
350
+ return isRecord(parsed) ? parsed : {};
351
+ }
352
+ catch {
353
+ return {};
354
+ }
355
+ }
356
+ function computeTopologicalDepthByTaskId(tasks, dependencies) {
357
+ const depths = new UUIDMap();
358
+ if (dependencies.length === 0)
359
+ return depths;
360
+ const dependsOnByTask = new UUIDMap();
361
+ for (const dep of dependencies) {
362
+ const existing = dependsOnByTask.Get(dep.TaskID) ?? [];
363
+ existing.push(dep.DependsOnTaskID);
364
+ dependsOnByTask.Set(dep.TaskID, existing);
365
+ }
366
+ const visiting = new UUIDSet();
367
+ const visit = (taskId) => {
368
+ const cached = depths.Get(taskId);
369
+ if (cached !== undefined)
370
+ return cached;
371
+ if (visiting.Has(taskId))
372
+ return 0;
373
+ visiting.Add(taskId);
374
+ let maxParentDepth = -1;
375
+ for (const parentId of dependsOnByTask.Get(taskId) ?? []) {
376
+ maxParentDepth = Math.max(maxParentDepth, visit(parentId));
377
+ }
378
+ visiting.Delete(taskId);
379
+ depths.Set(taskId, maxParentDepth + 1);
380
+ return maxParentDepth + 1;
381
+ };
382
+ for (const row of tasks)
383
+ visit(row.ID);
384
+ return depths;
385
+ }
386
+ function asNonEmptyString(value) {
387
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
388
+ }
389
+ function isRecord(value) {
390
+ return !!value && typeof value === 'object' && !Array.isArray(value);
391
+ }
392
+ //# sourceMappingURL=saga-compensation.js.map