@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
@@ -18,9 +18,9 @@
18
18
  *
19
19
  * @module @memberjunction/task-graph
20
20
  */
21
- import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveLoopBodyParams, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, FinalizeAgentRunStep, InitAgentRunStep, DecisionReferencesIn, ResolveDecisionState, } from '@memberjunction/ai-core-plus';
22
- import { LogError, LogStatus, RunView } from '@memberjunction/core';
23
- import { ShutdownRegistry, UUIDsEqual } from '@memberjunction/global';
21
+ import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveLoopBodyParams, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, FinalizeAgentRunStep, InitAgentRunStep, DecisionReferencesIn, ResolveDecisionState, ApplyTaskSecurityEnvelopeToParams, SerializeTaskSecurityEnvelope, TAINTED_EGRESS_BLOCKED, TASK_GRAPH_RUNTIME_SECURITY_OPERATION, } from '@memberjunction/ai-core-plus';
22
+ import { LogError, LogStatus, RunView, ServerOperationScopeManager } from '@memberjunction/core';
23
+ import { EscapeSQLString, GroupByUUID, IndexByUUID, IsValidUUID, ShutdownRegistry, UUIDMap, UUIDSet, UUIDsEqual } from '@memberjunction/global';
24
24
  import { TaskClaimStore, TERMINAL_PARENT_STATUSES, TERMINAL_PARENT_STATUS_SQL } from './TaskClaimStore.js';
25
25
  import { BuildConditionContext, DecideGate, EvaluateCondition, IsBrokenGuard, ParseConditionOutput, } from './condition-gate.js';
26
26
  import { BuildDecisionStepOutput, DecisionStepOutputAnswers, DecisionsPayloadConflict, FailedDecisionIDs, KeptDecisionAnswers, PassOverFailedDecisionPaths, QuestionsToAsk, ReadsFailedDecision, ReadDecisionStepConfiguration, ResolveGraphDecisions, StillHoldingDecisionOutput, } from './decision-node.js';
@@ -32,6 +32,8 @@ import { DispatcherConditionEvaluator } from './DispatcherConditionEvaluator.js'
32
32
  import { DecideClaimGate, OverrideVerdictFor, ParseTaskGraphDebugState, } from './debug-state.js';
33
33
  import { RunForEachLoop, RunWhileLoop } from './TaskLoopExecutor.js';
34
34
  import { RegisterTaskGraphKick } from './task-graph-kick.js';
35
+ import { BuildCompensationEscalationSummary, BuildCompensationInputPayload, IndexCompensationRows, IsCompensationTask, NextSagaStep, ReadActionCompensationMetadata, ReadTaskCompensationMetadata, RetryBackoffMs, SelectTasksToCompensate, } from './saga-compensation.js';
36
+ import { CloneUserWithTenantContext, ComputeNodeInputTaint, EnvelopeConstrains, ResolveStoredNodeSecurity, UpstreamCarriesTaint, WithInputTaint, } from './task-security.js';
35
37
  import { NotificationEngine } from '@memberjunction/notifications';
36
38
  /** Metadata-seeded notification type for human tasks (metadata/notifications/.task-assignment-type.json). */
37
39
  const HUMAN_TASK_NOTIFICATION_TYPE = 'Task Assignment';
@@ -59,6 +61,20 @@ const STOP_DRAIN_TIMEOUT_MS = 30_000;
59
61
  * sweep, which is the wider net.
60
62
  */
61
63
  const MAX_SETTLEMENT_RETRY_PASSES = 20;
64
+ /**
65
+ * How long this instance leaves a graph alone after processing it threw (S6) — an inactive submitter,
66
+ * a row that will not read. Long enough that a graph that cannot be processed is not re-attempted and
67
+ * re-reported every poll; short enough that one that recovers (the user reactivated) moves on its own.
68
+ */
69
+ const FAILED_GRAPH_BACKOFF_MS = 5 * 60 * 1000;
70
+ /**
71
+ * How many passes in a row may fail to write one saga row (a compensation, or the Human step escalating a
72
+ * failed one) for a reason that may not repeat before that row is recorded as failed (T5). A deadlock, a
73
+ * timeout or a dropped connection fails one insert or lookup and the next pass usually succeeds, so one
74
+ * failure must not end a compensation for good. A cause that cannot change (the action does not exist, the
75
+ * envelope cannot be read) is recorded at once.
76
+ */
77
+ const SAGA_ROW_WRITE_ATTEMPTS = 3;
62
78
  /**
63
79
  * Written to a human task's `ClaimedBy` once its assignee has been told it is ready.
64
80
  *
@@ -269,6 +285,19 @@ export class TaskGraphDispatcher {
269
285
  * by the wide startup sweep, which is the durable backstop this leans on.
270
286
  */
271
287
  this.retryingSettlement = new Map();
288
+ /**
289
+ * Graphs whose processing threw on this instance, and when it may try each again (S6). Reported
290
+ * once per failure streak, not once per poll; cleared the first time the graph processes cleanly,
291
+ * or once the graph is no longer active (settled elsewhere).
292
+ */
293
+ this.failedGraphs = new UUIDMap();
294
+ /**
295
+ * Saga rows this instance failed to write on its last passes, by the task each would compensate
296
+ * (`CompensatesTaskID`), with the graph it belongs to and how many passes in a row failed
297
+ * ({@link SAGA_ROW_WRITE_ATTEMPTS}). Cleared when the row lands, when another dispatcher's row is
298
+ * found, or once the graph is no longer active.
299
+ */
300
+ this.sagaRowWriteFailures = new UUIDMap();
272
301
  /**
273
302
  * Graphs whose settled-branch ANNOUNCEMENTS have already been made by this process.
274
303
  *
@@ -573,7 +602,8 @@ export class TaskGraphDispatcher {
573
602
  // against a host that believed the dispatcher had stopped.
574
603
  this.activePasses++;
575
604
  try {
576
- await this.sweepUnsettledGraphs(UNSETTLED_STARTUP_WINDOW_HOURS);
605
+ // Server work, like every pass: see `pollOnce`.
606
+ await ServerOperationScopeManager.Instance.RunAsServerWork(() => this.sweepUnsettledGraphs(UNSETTLED_STARTUP_WINDOW_HOURS));
577
607
  }
578
608
  finally {
579
609
  this.activePasses--;
@@ -692,7 +722,8 @@ export class TaskGraphDispatcher {
692
722
  async Reconcile() {
693
723
  this.activePasses++;
694
724
  try {
695
- await this.reconcileOnce();
725
+ // Server work, like every pass: see `pollOnce`.
726
+ await ServerOperationScopeManager.Instance.RunAsServerWork(() => this.reconcileOnce());
696
727
  }
697
728
  finally {
698
729
  this.activePasses--;
@@ -764,8 +795,16 @@ export class TaskGraphDispatcher {
764
795
  *
765
796
  * Overlap-guarded — a pass that runs long simply skips the next tick rather than stacking, which
766
797
  * would otherwise let a slow database multiply in-flight work past the cap.
798
+ *
799
+ * Always server work (`ServerOperationScopeManager.RunAsServerWork`). {@link Kick} runs a pass in its
800
+ * caller's async scope, and a caller inside a client's own CRUD request (a graph submitted from one)
801
+ * would otherwise hand that request's boundary to every node the pass runs, so a node's save of a
802
+ * Human step or an agent request would read as that person's own act.
767
803
  */
768
- async pollOnce() {
804
+ pollOnce() {
805
+ return ServerOperationScopeManager.Instance.RunAsServerWork(() => this.runPass());
806
+ }
807
+ async runPass() {
769
808
  if (!this.running || this.polling)
770
809
  return;
771
810
  this.polling = true;
@@ -926,11 +965,16 @@ export class TaskGraphDispatcher {
926
965
  ClaimEvent: 'claimed', ClaimedBy: this.config.InstanceID,
927
966
  ClaimExpiresAt: new Date(Date.now() + this.config.ClaimTTLSeconds * 1000).toISOString(),
928
967
  });
929
- const dependencyOutputs = hydrated?.dependencyOutputs instanceof Map
930
- ? hydrated.dependencyOutputs
931
- : hydrated?.dependencyOutputs
932
- ? new Map(Object.entries(hydrated.dependencyOutputs))
933
- : await this.loadDependencyOutputs(provider, taskID);
968
+ const dependencies = hydrated?.dependencyOutputs
969
+ ? {
970
+ Outputs: hydrated.dependencyOutputs instanceof Map
971
+ ? hydrated.dependencyOutputs
972
+ : new Map(Object.entries(hydrated.dependencyOutputs)),
973
+ Upstream: hydrated.upstreamTasks ?? [],
974
+ }
975
+ : await this.loadDependencies(provider, taskID);
976
+ const dependencyOutputs = dependencies.Outputs;
977
+ const nodeHydration = { ...hydrated, upstreamTasks: dependencies.Upstream };
934
978
  const parsed = ParseTaskInputPayload(taskID, task.InputPayload);
935
979
  let result;
936
980
  if ('ErrorMessage' in parsed) {
@@ -941,7 +985,7 @@ export class TaskGraphDispatcher {
941
985
  }
942
986
  else {
943
987
  const onProgress = this.nodeProgressEmitter(graphID, ownerUserID, taskID, task.Name);
944
- result = await this.runTaskBody(task, provider, parsed.Payload, dependencyOutputs, onProgress, hydrated);
988
+ result = await this.runTaskBody(task, provider, parsed.Payload, dependencyOutputs, onProgress, nodeHydration);
945
989
  }
946
990
  // ONLY THE CONFIRMED OWNER MUTATES THE GRAPH (R2-10).
947
991
  //
@@ -958,7 +1002,7 @@ export class TaskGraphDispatcher {
958
1002
  OutputPayload: result.Output != null ? JSON.stringify(result.Output) : null,
959
1003
  ErrorMessage: result.ErrorMessage ?? null,
960
1004
  AgentRunID: result.AgentRunID ?? null,
961
- Configuration: this.configurationWithRuntime(task, result.PromptRunID, result.ActionLogID, result.Iterations, result.PayloadAtStart),
1005
+ Configuration: this.configurationWithRuntime(task, result.PromptRunID, result.ActionLogID, result.Iterations, result.PayloadAtStart, result.IsOutputTainted, result.ActionInput),
962
1006
  }, this.contextUser);
963
1007
  if (!recorded) {
964
1008
  // The guarded write refused: the row changed underneath us (cancelled, reassigned,
@@ -1010,266 +1054,320 @@ export class TaskGraphDispatcher {
1010
1054
  */
1011
1055
  async propagateAndRollup(provider, graphIDs) {
1012
1056
  const graphs = graphIDs ?? await this.findActiveGraphIDs(provider);
1057
+ if (!graphIDs) {
1058
+ // A set-aside graph that left the active set (another instance settled it) is never processed
1059
+ // here again, so its back-off entry would never clear.
1060
+ const active = new UUIDSet(graphs);
1061
+ for (const id of [...this.failedGraphs.Keys()]) {
1062
+ if (!active.Has(id))
1063
+ this.failedGraphs.Delete(id);
1064
+ }
1065
+ for (const [id, failure] of [...this.sagaRowWriteFailures]) {
1066
+ if (!active.Has(failure.GraphID))
1067
+ this.sagaRowWriteFailures.Delete(id);
1068
+ }
1069
+ }
1013
1070
  const survivingGraphs = [];
1014
1071
  for (const parentID of graphs) {
1015
- // Edge overrides apply to propagation exactly as they apply to claiming — a branch the
1016
- // operator answered 'false' must cascade its skips here, not merely stop being claimed.
1017
- // `loadGraphState` loads the parent row once and populates `debugStateByGraph` and
1018
- // `ownerByParentID` from it, avoiding a separate `primeDebugStates` RunView round-trip.
1019
- let graph = await this.loadGraphState(provider, parentID);
1020
- if (graph.nodes.length === 0)
1072
+ // ONE GRAPH'S FAILURE IS ITS OWN (S6). Anything this throws (an inactive submitter in the
1073
+ // saga's user resolution, an unreadable row) used to escape the loop and abort the whole
1074
+ // pass, on every instance, every poll: no graph anywhere settled, skipped or claimed.
1075
+ if (this.isBackingOffFailedGraph(parentID))
1021
1076
  continue;
1022
- const debug = await this.readDebugState(provider, parentID);
1023
- // Human steps are only swept when the loaded graph actually contains at least one
1024
- // non-terminal Human task. When a graph has 0 pending human tasks (99% of graphs), this
1025
- // check short-circuits in memory with 0 DB queries instead of running 3 RunViews per graph.
1026
- const pendingHumanTasks = [...graph.entityById.values()].filter((t) => t.Status === 'Pending' && IsHumanTask(t));
1027
- if (pendingHumanTasks.length > 0) {
1028
- await this.expireOverdueRequests(provider, parentID, pendingHumanTasks);
1029
- const settledHumanCount = await this.settleAnsweredHumanTasks(provider, parentID, pendingHumanTasks);
1030
- await this.reconcileWaitingHumanTasks(provider, parentID, pendingHumanTasks);
1031
- if (settledHumanCount > 0) {
1032
- // Re-evaluate conditional edges and skip/block cascades now that a human step's
1033
- // answer and status have landed, reusing the already-loaded parent task.
1034
- graph = await this.loadGraphState(provider, parentID, debug, graph.parent);
1035
- if (graph.nodes.length === 0)
1036
- continue;
1037
- }
1077
+ try {
1078
+ const live = await this.propagateAndRollupGraph(provider, parentID);
1079
+ this.failedGraphs.Delete(parentID);
1080
+ if (live)
1081
+ survivingGraphs.push(live);
1038
1082
  }
1039
- // SKIPS FIRST — before blocking, before eligibility. A task whose gating predecessors
1040
- // are all Skipped is simultaneously "eligible" (Skipped satisfies a prerequisite) and
1041
- // "to be skipped"; deciding eligibility first would dispatch the branch nobody took.
1042
- //
1043
- // `unreachableTaskIDs` seeds this too, and that is a correction (R6). A target whose only
1044
- // route in was an ordinary conditional edge that evaluated DEFINITELY FALSE is a branch
1045
- // that was not taken — semantically identical to an XOR loser — yet it used to settle
1046
- // `Blocked`. That made `Blocked` mean two unrelated things: "the workflow chose another
1047
- // route" and "something upstream broke". A reader cannot tell those apart, so every
1048
- // conditional workflow looked half-failed and people went hunting for bugs that did not
1049
- // exist. `Blocked` is now reserved for FAILURE-driven unsatisfiability.
1050
- // Computed once in `loadGraphState` so the claim filter sees the same set this pass is
1051
- // about to write — see R2-14 there.
1052
- const toSkip = graph.cascadeSkipTaskIDs;
1053
- const skippedByRoute = [];
1054
- for (const taskID of toSkip) {
1055
- const entity = graph.entityById.get(taskID);
1056
- if (!entity || entity.Status !== 'Pending')
1057
- continue;
1058
- // The in-memory check above is a cheap pre-filter; the guard that matters is IN the
1059
- // statement (R3-1's audit item). This snapshot was loaded at the top of the pass and
1060
- // a task can be claimed and started before its skip write lands — R2-14 closed that
1061
- // window for the claim filter, and this closes it for the write itself.
1062
- const skipTypeID = await this.workflowTaskTypeID(provider);
1063
- if (skipTypeID && await this.claims.TrySkipPending(provider, taskID, skipTypeID, this.contextUser)) {
1064
- entity.Status = 'Skipped';
1065
- skippedByRoute.push(taskID);
1066
- LogStatus(`[TaskGraphDispatcher] Skipped '${entity.Name}' (${taskID}) — another branch was taken.`);
1067
- // Announced separately from TaskBlocked because it means something different to
1068
- // a viewer: nothing went wrong, this route simply was not the one chosen.
1069
- this.emit({
1070
- Kind: 'TaskSkipped',
1071
- ParentTaskID: parentID,
1072
- OwnerUserID: await this.resolveOwner(provider, parentID),
1073
- TaskID: taskID,
1074
- TaskName: entity.Name,
1075
- Status: 'Skipped',
1076
- });
1077
- // Keep the in-memory graph consistent so the blocking pass below and the rollup
1078
- // both see the skip rather than a stale Pending.
1079
- const node = graph.nodes.find((n) => n.id === taskID);
1080
- if (node)
1081
- node.status = 'Skipped';
1082
- }
1083
+ catch (e) {
1084
+ this.backOffFailedGraph(parentID, e);
1083
1085
  }
1084
- // A human step reached by a route the workflow did not take has the same zombie request
1085
- // as one skipped by an early finish (R2-10): notified, `Requested` forever, and invisible
1086
- // to the settle and expiry sweeps because they filter on Pending tasks and this one is
1087
- // not Pending any more. Same treatment, different reason.
1088
- await this.withdrawOpenRequests(provider, skippedByRoute, 'The workflow took a different route, so this step is no longer needed.');
1089
- // Only failure-driven unsatisfiability reaches here now; not-taken branches were skipped
1090
- // above. A task already Skipped is left alone rather than overwritten — the two passes
1091
- // must not fight over the same row.
1092
- const toBlock = [...ComputeTasksToBlock(graph.nodes, graph.edges, graph.handledFailureIDs)]
1093
- .filter((id) => !toSkip.has(id));
1094
- for (const taskID of toBlock) {
1095
- const entity = graph.entityById.get(taskID);
1096
- if (!entity)
1097
- continue;
1098
- entity.Status = 'Blocked';
1099
- if (await entity.Save()) {
1100
- const node = graph.nodes.find((n) => n.id === taskID);
1101
- if (node)
1102
- node.status = 'Blocked';
1103
- LogStatus(`[TaskGraphDispatcher] Blocked '${entity.Name}' (${taskID}) — a dependency can never be satisfied.`);
1104
- // Worth announcing on its own: a blocked step is the one outcome a viewer would
1105
- // otherwise see as a task that simply never starts.
1106
- this.emit({
1107
- Kind: 'TaskBlocked',
1108
- ParentTaskID: parentID,
1109
- OwnerUserID: await this.resolveOwner(provider, parentID),
1110
- TaskID: taskID,
1111
- TaskName: entity.Name,
1112
- Status: 'Blocked',
1113
- });
1114
- }
1086
+ }
1087
+ return survivingGraphs;
1088
+ }
1089
+ /** Whether a graph that threw is still inside its back-off on this instance. */
1090
+ isBackingOffFailedGraph(parentID) {
1091
+ const failed = this.failedGraphs.Get(parentID);
1092
+ return failed !== undefined && Date.now() < failed.RetryAt;
1093
+ }
1094
+ /**
1095
+ * Sets a graph whose processing threw aside for {@link FAILED_GRAPH_BACKOFF_MS}, so the other graphs
1096
+ * go on settling and claiming. Logged on the first failure of a streak only.
1097
+ */
1098
+ backOffFailedGraph(parentID, error) {
1099
+ const alreadyFailing = this.failedGraphs.Has(parentID);
1100
+ this.failedGraphs.Set(parentID, { RetryAt: Date.now() + FAILED_GRAPH_BACKOFF_MS });
1101
+ if (alreadyFailing)
1102
+ return;
1103
+ LogError(`[TaskGraphDispatcher] Graph ${parentID} could not be processed and is set aside for ` +
1104
+ `${FAILED_GRAPH_BACKOFF_MS / 1000}s; the other graphs continue. ${error instanceof Error ? error.message : String(error)}`);
1105
+ }
1106
+ /**
1107
+ * {@link propagateAndRollup} for one graph: returns the graph when it is still live (so claiming can
1108
+ * reuse it), or `undefined` when it settled, emptied or is waiting on a retry.
1109
+ */
1110
+ async propagateAndRollupGraph(provider, parentID) {
1111
+ // Edge overrides apply to propagation exactly as they apply to claiming — a branch the
1112
+ // operator answered 'false' must cascade its skips here, not merely stop being claimed.
1113
+ // `loadGraphState` loads the parent row once and populates `debugStateByGraph` and
1114
+ // `ownerByParentID` from it, avoiding a separate `primeDebugStates` RunView round-trip.
1115
+ let graph = await this.loadGraphState(provider, parentID);
1116
+ if (graph.nodes.length === 0)
1117
+ return undefined;
1118
+ const debug = await this.readDebugState(provider, parentID);
1119
+ // Human steps are only swept when the loaded graph actually contains at least one
1120
+ // non-terminal Human task. When a graph has 0 pending human tasks (99% of graphs), this
1121
+ // check short-circuits in memory with 0 DB queries instead of running 3 RunViews per graph.
1122
+ const pendingHumanTasks = [...graph.entityById.values()].filter((t) => t.Status === 'Pending' && IsHumanTask(t));
1123
+ if (pendingHumanTasks.length > 0) {
1124
+ await this.expireOverdueRequests(provider, parentID, pendingHumanTasks);
1125
+ const settledHumanCount = await this.settleAnsweredHumanTasks(provider, parentID, pendingHumanTasks);
1126
+ await this.reconcileWaitingHumanTasks(provider, parentID, pendingHumanTasks);
1127
+ if (settledHumanCount > 0) {
1128
+ // Re-evaluate conditional edges and skip/block cascades now that a human step's
1129
+ // answer and status have landed, reusing the already-loaded parent task.
1130
+ graph = await this.loadGraphState(provider, parentID, debug, graph.parent);
1131
+ if (graph.nodes.length === 0)
1132
+ return undefined;
1115
1133
  }
1116
- // Holds are passed in, or the detector reports a held graph as healthy: a held target's
1117
- // gating edge is still live and its origin Complete, so ComputeEligibleTasks counts it
1118
- // as eligible and "something is eligible" reads as "not stalled". A graph waiting
1119
- // forever on a broken condition then produced no diagnostics at all.
1120
- if (IsGraphStalled(graph.nodes, graph.edges, graph.holdTaskIDs)) {
1121
- LogError(`[TaskGraphDispatcher] Graph ${parentID} is stalled: pending work with no satisfiable path.`);
1134
+ }
1135
+ // SKIPS FIRST — before blocking, before eligibility. A task whose gating predecessors
1136
+ // are all Skipped is simultaneously "eligible" (Skipped satisfies a prerequisite) and
1137
+ // "to be skipped"; deciding eligibility first would dispatch the branch nobody took.
1138
+ //
1139
+ // `unreachableTaskIDs` seeds this too, and that is a correction (R6). A target whose only
1140
+ // route in was an ordinary conditional edge that evaluated DEFINITELY FALSE is a branch
1141
+ // that was not taken — semantically identical to an XOR loser — yet it used to settle
1142
+ // `Blocked`. That made `Blocked` mean two unrelated things: "the workflow chose another
1143
+ // route" and "something upstream broke". A reader cannot tell those apart, so every
1144
+ // conditional workflow looked half-failed and people went hunting for bugs that did not
1145
+ // exist. `Blocked` is now reserved for FAILURE-driven unsatisfiability.
1146
+ // Computed once in `loadGraphState` so the claim filter sees the same set this pass is
1147
+ // about to write — see R2-14 there.
1148
+ const toSkip = graph.cascadeSkipTaskIDs;
1149
+ const skippedByRoute = [];
1150
+ for (const taskID of toSkip) {
1151
+ const entity = graph.entityById.get(taskID);
1152
+ if (!entity || entity.Status !== 'Pending')
1153
+ continue;
1154
+ // The in-memory check above is a cheap pre-filter; the guard that matters is IN the
1155
+ // statement (R3-1's audit item). This snapshot was loaded at the top of the pass and
1156
+ // a task can be claimed and started before its skip write lands — R2-14 closed that
1157
+ // window for the claim filter, and this closes it for the write itself.
1158
+ const skipTypeID = await this.workflowTaskTypeID(provider);
1159
+ if (skipTypeID && await this.claims.TrySkipPending(provider, taskID, skipTypeID, this.contextUser)) {
1160
+ entity.Status = 'Skipped';
1161
+ skippedByRoute.push(taskID);
1162
+ LogStatus(`[TaskGraphDispatcher] Skipped '${entity.Name}' (${taskID}) — another branch was taken.`);
1163
+ // Announced separately from TaskBlocked because it means something different to
1164
+ // a viewer: nothing went wrong, this route simply was not the one chosen.
1165
+ this.emit({
1166
+ Kind: 'TaskSkipped',
1167
+ ParentTaskID: parentID,
1168
+ OwnerUserID: await this.resolveOwner(provider, parentID),
1169
+ TaskID: taskID,
1170
+ TaskName: entity.Name,
1171
+ Status: 'Skipped',
1172
+ });
1173
+ // Keep the in-memory graph consistent so the blocking pass below and the rollup
1174
+ // both see the skip rather than a stale Pending.
1175
+ const node = graph.nodes.find((n) => n.id === taskID);
1176
+ if (node)
1177
+ node.status = 'Skipped';
1122
1178
  }
1123
- // Reuse the in-memory `graph` (whose `nodes` and `entityById` were updated in-place as
1124
- // skips and blocks landed) and its pre-loaded `graph.parent` instead of reloading the
1125
- // graph state and parent task a second time.
1126
- const rollup = ComputeParentRollup(graph.nodes, graph.handledFailureIDs);
1127
- let parent = graph.parent;
1128
- if (!parent) {
1129
- const fallbackParent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
1130
- if (!(await fallbackParent.Load(parentID)))
1131
- continue;
1132
- parent = fallbackParent;
1133
- graph.parent = parent;
1179
+ }
1180
+ // A human step reached by a route the workflow did not take has the same zombie request
1181
+ // as one skipped by an early finish (R2-10): notified, `Requested` forever, and invisible
1182
+ // to the settle and expiry sweeps because they filter on Pending tasks and this one is
1183
+ // not Pending any more. Same treatment, different reason.
1184
+ await this.withdrawOpenRequests(provider, skippedByRoute, 'The workflow took a different route, so this step is no longer needed.');
1185
+ // Only failure-driven unsatisfiability reaches here now; not-taken branches were skipped
1186
+ // above. A task already Skipped is left alone rather than overwritten — the two passes
1187
+ // must not fight over the same row.
1188
+ const toBlock = [...ComputeTasksToBlock(graph.nodes, graph.edges, graph.handledFailureIDs)]
1189
+ .filter((id) => !toSkip.has(id));
1190
+ for (const taskID of toBlock) {
1191
+ const entity = graph.entityById.get(taskID);
1192
+ if (!entity)
1193
+ continue;
1194
+ entity.Status = 'Blocked';
1195
+ // A workflow step's status is the dispatcher's (`MJTaskEntityServer`), so the write runs in its scope.
1196
+ if (await this.saveWithRuntimeAuthority(entity)) {
1197
+ const node = graph.nodes.find((n) => n.id === taskID);
1198
+ if (node)
1199
+ node.status = 'Blocked';
1200
+ LogStatus(`[TaskGraphDispatcher] Blocked '${entity.Name}' (${taskID}) — a dependency can never be satisfied.`);
1201
+ // Worth announcing on its own: a blocked step is the one outcome a viewer would
1202
+ // otherwise see as a task that simply never starts.
1203
+ this.emit({
1204
+ Kind: 'TaskBlocked',
1205
+ ParentTaskID: parentID,
1206
+ OwnerUserID: await this.resolveOwner(provider, parentID),
1207
+ TaskID: taskID,
1208
+ TaskName: entity.Name,
1209
+ Status: 'Blocked',
1210
+ });
1134
1211
  }
1135
- // A graph starts when its first step does.
1136
- //
1137
- // `StartedAt` is stamped by the CLAIM, and a parent is never claimed — it is a container,
1138
- // not a unit of work — so the graph row carried no start time even after it completed.
1139
- // A settled workflow therefore reported a CompletedAt with no beginning: it sorted as
1140
- // "not started" in the run tree, showed no timestamp, and no duration could be computed
1141
- // for the thing whose duration people actually ask about.
1142
- //
1143
- // Taken from the earliest child rather than from the clock, because that is when work
1144
- // genuinely began — a graph can sit Pending for a long time between submission (already
1145
- // recorded as CreatedAt) and a dispatcher picking up its first task.
1146
- // Column-scoped for the same reason the terminal write is: a full-row save here would
1147
- // carry this instance's `InputPayload` snapshot and could erase a continuation marker
1148
- // another instance had just claimed. Guarded on `StartedAt IS NULL`, so calling it on
1149
- // every pass is free.
1150
- const earliestChildStart = this.earliestStart(graph.entityById);
1151
- if (parent.StartedAt == null && earliestChildStart != null) {
1152
- await this.claims.TryStampParentStart(provider, parentID, earliestChildStart, this.contextUser);
1153
- parent.StartedAt = earliestChildStart;
1212
+ }
1213
+ const saga = await this.coordinateSagaCompensation(provider, parentID, graph, debug);
1214
+ graph = saga.Graph;
1215
+ // Holds are passed in, or the detector reports a held graph as healthy: a held target's
1216
+ // gating edge is still live and its origin Complete, so ComputeEligibleTasks counts it
1217
+ // as eligible and "something is eligible" reads as "not stalled". A graph waiting
1218
+ // forever on a broken condition then produced no diagnostics at all.
1219
+ if (IsGraphStalled(graph.nodes, graph.edges, graph.holdTaskIDs)) {
1220
+ LogError(`[TaskGraphDispatcher] Graph ${parentID} is stalled: pending work with no satisfiable path.`);
1221
+ }
1222
+ // Reuse the in-memory `graph` (whose `nodes` and `entityById` were updated in-place as
1223
+ // skips and blocks landed) and its pre-loaded `graph.parent` instead of reloading the
1224
+ // graph state and parent task a second time.
1225
+ const rollup = this.rollupWhileCompensating(ComputeParentRollup(graph.nodes, graph.handledFailureIDs), saga.Pending);
1226
+ let parent = graph.parent;
1227
+ if (!parent) {
1228
+ const fallbackParent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
1229
+ if (!(await fallbackParent.Load(parentID)))
1230
+ return undefined;
1231
+ parent = fallbackParent;
1232
+ graph.parent = parent;
1233
+ }
1234
+ // A graph starts when its first step does.
1235
+ //
1236
+ // `StartedAt` is stamped by the CLAIM, and a parent is never claimed — it is a container,
1237
+ // not a unit of work — so the graph row carried no start time even after it completed.
1238
+ // A settled workflow therefore reported a CompletedAt with no beginning: it sorted as
1239
+ // "not started" in the run tree, showed no timestamp, and no duration could be computed
1240
+ // for the thing whose duration people actually ask about.
1241
+ //
1242
+ // Taken from the earliest child rather than from the clock, because that is when work
1243
+ // genuinely began — a graph can sit Pending for a long time between submission (already
1244
+ // recorded as CreatedAt) and a dispatcher picking up its first task.
1245
+ // Column-scoped for the same reason the terminal write is: a full-row save here would
1246
+ // carry this instance's `InputPayload` snapshot and could erase a continuation marker
1247
+ // another instance had just claimed. Guarded on `StartedAt IS NULL`, so calling it on
1248
+ // every pass is free.
1249
+ const earliestChildStart = this.earliestStart(graph.entityById);
1250
+ if (parent.StartedAt == null && earliestChildStart != null) {
1251
+ await this.claims.TryStampParentStart(provider, parentID, earliestChildStart, this.contextUser);
1252
+ parent.StartedAt = earliestChildStart;
1253
+ }
1254
+ // THE TERMINAL WRITE IS GUARDED AND COLUMN-SCOPED, not a full-row save.
1255
+ //
1256
+ // `GenerateSaveSQL` sends every updateable column on every save, so a full-row save
1257
+ // carries the whole in-memory snapshot — including `InputPayload`, where the continuation
1258
+ // marker lives. Two instances both compute the terminal rollup; if one claims the marker
1259
+ // and the other then saves its pre-marker snapshot, the marker is ERASED and the
1260
+ // settlement delivers twice. For `reinvoke` that is a second billed agent turn.
1261
+ //
1262
+ // Guarding on "not already terminal" also makes the write idempotent across the
1263
+ // re-entrant settle path below, and replaces an unchecked `Save()` whose failure left the
1264
+ // graph active — re-emitting frames and recomputing cost every poll, forever.
1265
+ if (rollup.outcome === 'settled') {
1266
+ const settled = await this.claims.TrySettleParent(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
1267
+ if (!settled && !TERMINAL_TASK_STATUSES.has(parent.Status)) {
1268
+ // Neither "already terminal" nor a successful write: the statement failed. Leave
1269
+ // the graph active so the next pass retries rather than settling on a status the
1270
+ // database never accepted. Re-queued explicitly, because a failed write is
1271
+ // exactly the case where the row's own timestamp does not advance.
1272
+ LogError(`[TaskGraphDispatcher] Could not write terminal status for graph ${parentID}; leaving it active to retry.`);
1273
+ this.keepRetryingSettlement(parentID);
1274
+ return undefined;
1154
1275
  }
1155
- // THE TERMINAL WRITE IS GUARDED AND COLUMN-SCOPED, not a full-row save.
1276
+ parent.Status = rollup.status;
1277
+ }
1278
+ else {
1279
+ if (parent.Status !== rollup.status || parent.PercentComplete !== rollup.percentComplete) {
1280
+ // Guarded and column-scoped for the same reason the terminal write is — and the race
1281
+ // here needs no exotic timing. This instance may have computed a non-terminal rollup
1282
+ // from a snapshot taken before another instance settled the graph; a full-row save
1283
+ // would then REVERT the status and erase the continuation marker with it, and the
1284
+ // next pass would settle and deliver a second time. See TryUpdateParentProgress.
1285
+ await this.claims.TryUpdateParentProgress(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
1286
+ }
1287
+ return graph;
1288
+ }
1289
+ if (rollup.outcome === 'settled') {
1290
+ // ANNOUNCE ONCE PER PROCESS, RETRY THE REST (R2-12). Layout and the frame are
1291
+ // idempotent facts about a finished graph; the cost, lifecycle and delivery writes
1292
+ // below are the ones re-entry exists to retry. Without this split, a graph that keeps
1293
+ // failing to settle re-persisted geometry and re-emitted the same frame every poll
1294
+ // for the whole rescue window.
1295
+ if (!this.announcedSettlements.has(parentID)) {
1296
+ // Geometry is settled once, here, so every viewer of this run agrees on it.
1297
+ await this.persistComputedLayout(graph);
1298
+ // Emitted before the continuation is delivered, and outside its once-only guard: a
1299
+ // viewer watching the run should learn it finished whether or not this instance is
1300
+ // the one that wins the delivery CAS.
1301
+ this.emit({
1302
+ Kind: 'GraphSettled',
1303
+ ParentTaskID: parentID,
1304
+ OwnerUserID: await this.resolveOwner(provider, parentID),
1305
+ Status: rollup.status,
1306
+ CompletedCount: graph.nodes.filter((n) => n.status === 'Complete').length,
1307
+ TotalCount: graph.nodes.length,
1308
+ });
1309
+ this.announcedSettlements.add(parentID);
1310
+ }
1311
+ // READ-ONLY GATE, before any write to the submitting run's half (R2-2).
1156
1312
  //
1157
- // `GenerateSaveSQL` sends every updateable column on every save, so a full-row save
1158
- // carries the whole in-memory snapshot — including `InputPayload`, where the continuation
1159
- // marker lives. Two instances both compute the terminal rollup; if one claims the marker
1160
- // and the other then saves its pre-marker snapshot, the marker is ERASED and the
1161
- // settlement delivers twice. For `reinvoke` that is a second billed agent turn.
1313
+ // A graph can settle before the run that submitted it has parked at all. `BaseAgent`
1314
+ // sets `Paused` in `finalizeAgentRun`, AFTER the graph is durable and dispatchable —
1315
+ // so a fast graph finishes first, and both writes below then land wrong: the
1316
+ // lifecycle write silently returns (its guard is `Status === 'Paused'`), and the cost
1317
+ // write is overwritten moments later by finalize's own full-row save, which carries
1318
+ // the in-memory nulls it had before the dispatcher wrote anything.
1162
1319
  //
1163
- // Guarding on "not already terminal" also makes the write idempotent across the
1164
- // re-entrant settle path below, and replaces an unchecked `Save()` whose failure left the
1165
- // graph active — re-emitting frames and recomputing cost every poll, forever.
1166
- if (rollup.outcome === 'settled') {
1167
- const settled = await this.claims.TrySettleParent(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
1168
- if (!settled && !TERMINAL_TASK_STATUSES.has(parent.Status)) {
1169
- // Neither "already terminal" nor a successful write: the statement failed. Leave
1170
- // the graph active so the next pass retries rather than settling on a status the
1171
- // database never accepted. Re-queued explicitly, because a failed write is
1172
- // exactly the case where the row's own timestamp does not advance.
1173
- LogError(`[TaskGraphDispatcher] Could not write terminal status for graph ${parentID}; leaving it active to retry.`);
1174
- this.keepRetryingSettlement(parentID);
1175
- continue;
1176
- }
1177
- parent.Status = rollup.status;
1320
+ // Deferring the whole half — rather than doing the parts that happen to work — is
1321
+ // what keeps the marker honest: nothing below claims it, so the graph stays
1322
+ // terminal-and-undelivered and the rescue sweep brings it back next pass, by which
1323
+ // time finalize has parked the run and both writes land.
1324
+ const readiness = await this.submittingRunReadiness(provider, parent);
1325
+ if (readiness.Verdict === 'defer') {
1326
+ this.keepRetryingSettlement(parentID);
1327
+ return undefined;
1178
1328
  }
1179
- else {
1180
- if (parent.Status !== rollup.status || parent.PercentComplete !== rollup.percentComplete) {
1181
- // Guarded and column-scoped for the same reason the terminal write is — and the race
1182
- // here needs no exotic timing. This instance may have computed a non-terminal rollup
1183
- // from a snapshot taken before another instance settled the graph; a full-row save
1184
- // would then REVERT the status and erase the continuation marker with it, and the
1185
- // next pass would settle and deliver a second time. See TryUpdateParentProgress.
1186
- await this.claims.TryUpdateParentProgress(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
1187
- }
1188
- survivingGraphs.push(graph);
1329
+ // A settled graph will not produce another verdict, claim or progress report, so the
1330
+ // per-graph observability caches for it are dead weight from here. Unbounded, they
1331
+ // are a slow leak in a process that runs for weeks — one that grows with every
1332
+ // workflow the server has ever seen rather than with anything live. (A deferred
1333
+ // settlement below repopulates them naturally on the retry pass.)
1334
+ this.forgetGraphObservability(parentID);
1335
+ // R3-8: the rollup gets a verdict, and a TRANSIENT failure defers exactly as a
1336
+ // failed lifecycle write does. Continuing past one would settle the run and claim
1337
+ // the marker, which permanently excludes the graph from the rescue sweep — making
1338
+ // the rollup's own "retrying on a later settlement" log a promise it could not keep.
1339
+ // Permanent refusals (truncated tree, graph not in the tree) proceed as before:
1340
+ // those do not clear on their own, and deferring on them would stall forever.
1341
+ if (await this.rollUpCostToSubmittingRun(provider, parent) === 'failed-transient') {
1342
+ this.keepRetryingSettlement(parentID);
1343
+ return undefined;
1189
1344
  }
1190
- if (rollup.outcome === 'settled') {
1191
- // ANNOUNCE ONCE PER PROCESS, RETRY THE REST (R2-12). Layout and the frame are
1192
- // idempotent facts about a finished graph; the cost, lifecycle and delivery writes
1193
- // below are the ones re-entry exists to retry. Without this split, a graph that keeps
1194
- // failing to settle re-persisted geometry and re-emitted the same frame every poll
1195
- // for the whole rescue window.
1196
- if (!this.announcedSettlements.has(parentID)) {
1197
- // Geometry is settled once, here, so every viewer of this run agrees on it.
1198
- await this.persistComputedLayout(graph);
1199
- // Emitted before the continuation is delivered, and outside its once-only guard: a
1200
- // viewer watching the run should learn it finished whether or not this instance is
1201
- // the one that wins the delivery CAS.
1202
- this.emit({
1203
- Kind: 'GraphSettled',
1204
- ParentTaskID: parentID,
1205
- OwnerUserID: await this.resolveOwner(provider, parentID),
1206
- Status: rollup.status,
1207
- CompletedCount: graph.nodes.filter((n) => n.status === 'Complete').length,
1208
- TotalCount: graph.nodes.length,
1209
- });
1210
- this.announcedSettlements.add(parentID);
1211
- }
1212
- // READ-ONLY GATE, before any write to the submitting run's half (R2-2).
1213
- //
1214
- // A graph can settle before the run that submitted it has parked at all. `BaseAgent`
1215
- // sets `Paused` in `finalizeAgentRun`, AFTER the graph is durable and dispatchable —
1216
- // so a fast graph finishes first, and both writes below then land wrong: the
1217
- // lifecycle write silently returns (its guard is `Status === 'Paused'`), and the cost
1218
- // write is overwritten moments later by finalize's own full-row save, which carries
1219
- // the in-memory nulls it had before the dispatcher wrote anything.
1220
- //
1221
- // Deferring the whole half — rather than doing the parts that happen to work — is
1222
- // what keeps the marker honest: nothing below claims it, so the graph stays
1223
- // terminal-and-undelivered and the rescue sweep brings it back next pass, by which
1224
- // time finalize has parked the run and both writes land.
1225
- const readiness = await this.submittingRunReadiness(provider, parent);
1226
- if (readiness.Verdict === 'defer') {
1227
- this.keepRetryingSettlement(parentID);
1228
- continue;
1229
- }
1230
- // A settled graph will not produce another verdict, claim or progress report, so the
1231
- // per-graph observability caches for it are dead weight from here. Unbounded, they
1232
- // are a slow leak in a process that runs for weeks — one that grows with every
1233
- // workflow the server has ever seen rather than with anything live. (A deferred
1234
- // settlement below repopulates them naturally on the retry pass.)
1235
- this.forgetGraphObservability(parentID);
1236
- // R3-8: the rollup gets a verdict, and a TRANSIENT failure defers exactly as a
1237
- // failed lifecycle write does. Continuing past one would settle the run and claim
1238
- // the marker, which permanently excludes the graph from the rescue sweep — making
1239
- // the rollup's own "retrying on a later settlement" log a promise it could not keep.
1240
- // Permanent refusals (truncated tree, graph not in the tree) proceed as before:
1241
- // those do not clear on their own, and deferring on them would stall forever.
1242
- if (await this.rollUpCostToSubmittingRun(provider, parent) === 'failed-transient') {
1243
- this.keepRetryingSettlement(parentID);
1244
- continue;
1245
- }
1246
- // Deliberately AFTER the rollup and OUTSIDE its refusal paths. The rollup declines
1247
- // to write a number it cannot stand behind — a truncated tree, an unreachable graph
1248
- // — and every one of those returns early. If the run's lifecycle were settled in
1249
- // there, a refused rollup would strand the run parked forever, which is a far worse
1250
- // failure than a missing cost figure. Cost and lifecycle are separate concerns with
1251
- // separate failure modes, so they get separate writes.
1252
- if (await this.settleSubmittingRun(provider, parent, rollup.status) === 'defer') {
1253
- // The lifecycle write did not land. Delivering now would claim the marker and
1254
- // make this the LAST pass to look at the graph — leaving the run Paused forever,
1255
- // which is the exact permanence R2-2 removes. Leave the marker unset and retry.
1256
- this.keepRetryingSettlement(parentID);
1257
- continue;
1258
- }
1259
- if (await this.deliverContinuation(provider, parent, graph, readiness.SubmitterCancelled)) {
1260
- // Delivered, expired, or lost the CAS to a peer — every one of those means this
1261
- // graph is somebody's finished business and needs nothing further from here.
1262
- this.retryingSettlement.delete(parentID);
1263
- this.announcedSettlements.delete(parentID);
1264
- }
1265
- else {
1266
- // This instance cannot deliver. Stay quiet about it — the frame is already out —
1267
- // and leave the graph for a capable peer via the sweep.
1268
- this.keepRetryingSettlement(parentID);
1269
- }
1345
+ // Deliberately AFTER the rollup and OUTSIDE its refusal paths. The rollup declines
1346
+ // to write a number it cannot stand behind — a truncated tree, an unreachable graph
1347
+ // — and every one of those returns early. If the run's lifecycle were settled in
1348
+ // there, a refused rollup would strand the run parked forever, which is a far worse
1349
+ // failure than a missing cost figure. Cost and lifecycle are separate concerns with
1350
+ // separate failure modes, so they get separate writes.
1351
+ if (await this.settleSubmittingRun(provider, parent, rollup.status) === 'defer') {
1352
+ // The lifecycle write did not land. Delivering now would claim the marker and
1353
+ // make this the LAST pass to look at the graph — leaving the run Paused forever,
1354
+ // which is the exact permanence R2-2 removes. Leave the marker unset and retry.
1355
+ this.keepRetryingSettlement(parentID);
1356
+ return undefined;
1357
+ }
1358
+ if (await this.deliverContinuation(provider, parent, graph, readiness.SubmitterCancelled)) {
1359
+ // Delivered, expired, or lost the CAS to a peer — every one of those means this
1360
+ // graph is somebody's finished business and needs nothing further from here.
1361
+ this.retryingSettlement.delete(parentID);
1362
+ this.announcedSettlements.delete(parentID);
1363
+ }
1364
+ else {
1365
+ // This instance cannot deliver. Stay quiet about it — the frame is already out —
1366
+ // and leave the graph for a capable peer via the sweep.
1367
+ this.keepRetryingSettlement(parentID);
1270
1368
  }
1271
1369
  }
1272
- return survivingGraphs;
1370
+ return undefined;
1273
1371
  }
1274
1372
  /**
1275
1373
  * Credits a finished graph's spending back to the agent run that submitted it.
@@ -1550,6 +1648,10 @@ export class TaskGraphDispatcher {
1550
1648
  let invocation = {};
1551
1649
  let submittedByUserID = task.UserID;
1552
1650
  let parentAgentHierarchy = undefined;
1651
+ // The parent's stored envelope. Every child carries its own copy too, so a parent that cannot
1652
+ // be read still leaves the node constrained by its own row.
1653
+ let parentEnvelopeColumn = null;
1654
+ let recordsTaint = true;
1553
1655
  if (task.ParentID && prehydrated && (prehydrated.parentMetadata || prehydrated.parentTask)) {
1554
1656
  const parent = prehydrated.parentTask ?? null;
1555
1657
  const meta = (prehydrated.parentMetadata && typeof prehydrated.parentMetadata.reinvokeDepth === 'number')
@@ -1557,8 +1659,11 @@ export class TaskGraphDispatcher {
1557
1659
  : ParseTaskGraphParentMetadata(parent?.InputPayload ?? null);
1558
1660
  depth = meta.reinvokeDepth + 1;
1559
1661
  submittingAgentRunID = parent?.AgentRunID ?? meta.submittedByAgentRunID ?? null;
1662
+ parentAgentHierarchy = meta.parentAgentHierarchy;
1560
1663
  invocation = { data: meta.invocation?.data, context: meta.invocation?.context };
1561
1664
  submittedByUserID = meta.submittedByUserID ?? parent?.UserID ?? task.UserID;
1665
+ parentEnvelopeColumn = parent?.SecurityEnvelope ?? null;
1666
+ recordsTaint = meta.recordsTaint === true;
1562
1667
  }
1563
1668
  else if (task.ParentID && typeof provider?.GetEntityObject === 'function') {
1564
1669
  try {
@@ -1573,6 +1678,8 @@ export class TaskGraphDispatcher {
1573
1678
  parentAgentHierarchy = meta.parentAgentHierarchy;
1574
1679
  invocation = { data: meta.invocation?.data, context: meta.invocation?.context };
1575
1680
  submittedByUserID = meta.submittedByUserID ?? parent.UserID ?? task.UserID;
1681
+ parentEnvelopeColumn = parent.SecurityEnvelope;
1682
+ recordsTaint = meta.recordsTaint === true;
1576
1683
  }
1577
1684
  }
1578
1685
  catch (e) {
@@ -1581,13 +1688,20 @@ export class TaskGraphDispatcher {
1581
1688
  LogError(`[TaskGraphDispatcher] Task ${task.ID}: reading parent ${task.ParentID} failed; running at depth 0 with no invocation data/context: ${e instanceof Error ? e.message : String(e)}`);
1582
1689
  }
1583
1690
  }
1584
- const executionUser = await this.resolveGraphExecutionUser(submittedByUserID, task.ParentID ?? task.ID);
1691
+ const security = ResolveStoredNodeSecurity(parentEnvelopeColumn, task.SecurityEnvelope);
1692
+ const submitter = await this.resolveGraphExecutionUser(submittedByUserID, task.ParentID ?? task.ID);
1693
+ // The submitter resolves to the process-wide UserCache instance (or this dispatcher's own
1694
+ // user), which every other task shares: the caller's tenant goes on a per-task clone, never
1695
+ // on that instance (see CloneUserWithTenantContext).
1696
+ const tenant = 'Envelope' in security ? security.Envelope?.CallerTenantContext : undefined;
1585
1697
  return {
1586
1698
  Depth: depth,
1587
1699
  SubmittingAgentRunID: submittingAgentRunID,
1588
1700
  ParentAgentHierarchy: parentAgentHierarchy,
1589
1701
  Invocation: invocation,
1590
- ExecutionUser: executionUser,
1702
+ ExecutionUser: tenant ? CloneUserWithTenantContext(submitter, tenant, provider) : submitter,
1703
+ Security: security,
1704
+ RecordsTaint: recordsTaint,
1591
1705
  };
1592
1706
  }
1593
1707
  /**
@@ -1630,13 +1744,21 @@ export class TaskGraphDispatcher {
1630
1744
  * as a recovery path; they are ordinary sequencing, and treating them as recovery would let a
1631
1745
  * graph sail past a failure it never anticipated.
1632
1746
  */
1633
- computeHandledFailures(failureSemantics, nodes, edges) {
1747
+ computeHandledFailures(failureSemantics, nodes, edges, entityById) {
1634
1748
  const handled = new Set();
1635
- if (failureSemantics !== 'edges')
1636
- return handled;
1637
1749
  for (const node of nodes) {
1638
1750
  if (node.status !== 'Failed')
1639
1751
  continue;
1752
+ const entity = entityById?.get(node.id);
1753
+ if (entity && IsCompensationTask(entity)) {
1754
+ const compMeta = ReadTaskCompensationMetadata(entity.Configuration);
1755
+ if (compMeta?.onCompensationFailure === 'ContinueCompensation') {
1756
+ handled.add(node.id);
1757
+ continue;
1758
+ }
1759
+ }
1760
+ if (failureSemantics !== 'edges')
1761
+ continue;
1640
1762
  // "Has somewhere to go" is the test. An edge out of a failed step that survived condition
1641
1763
  // evaluation IS the drawn recovery route; a failed step with no outgoing edges has none,
1642
1764
  // and stays terminal.
@@ -1737,6 +1859,7 @@ export class TaskGraphDispatcher {
1737
1859
  return true;
1738
1860
  const summary = this.buildContinuationSummary(parent, graph);
1739
1861
  LogStatus(`[TaskGraphDispatcher] Graph ${parent.ID} finished — ${summary}`);
1862
+ const security = this.continuationEnvelope(parent, graph);
1740
1863
  const params = {
1741
1864
  ParentTaskID: parent.ID,
1742
1865
  WorkflowName: parent.Name,
@@ -1744,6 +1867,7 @@ export class TaskGraphDispatcher {
1744
1867
  SubmittedByAgentRunID: meta.submittedByAgentRunID,
1745
1868
  SubmittedByUserID: meta.submittedByUserID ?? null,
1746
1869
  ReinvokeDepth: meta.reinvokeDepth,
1870
+ ...('Envelope' in security && security.Envelope ? { SecurityEnvelope: security.Envelope } : {}),
1747
1871
  Tasks: [...graph.entityById.values()].map((t) => ({
1748
1872
  TaskID: t.ID,
1749
1873
  Name: t.Name,
@@ -1759,11 +1883,15 @@ export class TaskGraphDispatcher {
1759
1883
  // Reinvoke degrades to a message when the host cannot start agent turns. Degrading is
1760
1884
  // right rather than throwing: the work genuinely ran, and the user losing the results
1761
1885
  // because nobody could start a follow-up turn would be the worse outcome.
1762
- if (mode === 'reinvoke' && this.continuationDeliverer.Reinvoke) {
1886
+ const reinvokeRefusal = mode === 'reinvoke' ? this.reinvokeRefusal(security) : null;
1887
+ if (mode === 'reinvoke' && this.continuationDeliverer.Reinvoke && !reinvokeRefusal) {
1763
1888
  await this.continuationDeliverer.Reinvoke(params);
1764
1889
  }
1765
1890
  else {
1766
- if (mode === 'reinvoke') {
1891
+ if (reinvokeRefusal) {
1892
+ LogError(`[TaskGraphDispatcher] Graph ${parent.ID}: not starting a continuation turn (${reinvokeRefusal}); delivering as a message.`);
1893
+ }
1894
+ else if (mode === 'reinvoke') {
1767
1895
  LogStatus(`[TaskGraphDispatcher] Graph ${parent.ID}: host cannot reinvoke; delivering as a message.`);
1768
1896
  }
1769
1897
  await this.continuationDeliverer.PostMessage(params);
@@ -1781,6 +1909,37 @@ export class TaskGraphDispatcher {
1781
1909
  // wasted pass per settlement and a retry counter measuring the wrong thing.
1782
1910
  return true;
1783
1911
  }
1912
+ /**
1913
+ * What a `reinvoke` continuation turn runs under (B1): the graph's stored envelope, tainted when the
1914
+ * submitting run was or when any step's output carries taint — the turn reads every step's outcome,
1915
+ * so a completed Human step clears only what it reviewed. A stored envelope that cannot be read is a
1916
+ * refusal: the turn is then not started at all.
1917
+ */
1918
+ continuationEnvelope(parent, graph) {
1919
+ const stored = ResolveStoredNodeSecurity(parent.SecurityEnvelope, null);
1920
+ if ('Refusal' in stored) {
1921
+ return stored;
1922
+ }
1923
+ const graphTainted = stored.Envelope?.IsRunTainted === true;
1924
+ const lookup = this.upstreamLookupInGraph(graph);
1925
+ const outputsTainted = [...graph.entityById.values()].some((task) => UpstreamCarriesTaint(task, graphTainted, lookup, graph.parentMetadata?.recordsTaint === true));
1926
+ return { Envelope: WithInputTaint(stored.Envelope, graphTainted || outputsTainted) };
1927
+ }
1928
+ /**
1929
+ * Why a `reinvoke` turn must not start, or null. A fresh agent turn that ran without the graph's
1930
+ * constraints would search without its tenant and readers and post into a shared conversation, so a
1931
+ * graph whose envelope cannot be read, or that constrains anything on a host whose deliverer does not
1932
+ * enforce envelopes, is delivered as a message instead.
1933
+ */
1934
+ reinvokeRefusal(security) {
1935
+ if ('Refusal' in security) {
1936
+ return security.Refusal;
1937
+ }
1938
+ if (EnvelopeConstrains(security.Envelope) && this.continuationDeliverer?.EnforcesSecurityEnvelope !== true) {
1939
+ return 'the graph carries security constraints and this host\'s deliverer does not start a turn under them';
1940
+ }
1941
+ return null;
1942
+ }
1784
1943
  /** Reads the parent's durable continuation metadata through the shared parser. */
1785
1944
  readParentMetadata(parent) {
1786
1945
  return ParseTaskGraphParentMetadata(parent.InputPayload);
@@ -2033,9 +2192,30 @@ export class TaskGraphDispatcher {
2033
2192
  // will eventually stop finding them — which would turn a retry into a silent abandonment.
2034
2193
  for (const id of this.retryingSettlement.keys())
2035
2194
  ids.add(id);
2036
- for (const r of (withPendingWork?.Results ?? [])) {
2037
- if (r.ParentID)
2038
- ids.add(r.ParentID);
2195
+ // A parent counts only when it is a workflow (a parentless task of the workflow type): the first arm finds parents
2196
+ // by their steps' type alone, and a workflow-typed row under any other task must not turn that task into a graph
2197
+ // whose metadata the dispatcher would trust. The other two arms prove most of them; the rest (a step retried in a
2198
+ // run that settled before the sweep window) are checked with one read, whatever their status or age.
2199
+ const workflowParents = new Set([
2200
+ ...(unsettledParents?.Results ?? []).map((r) => r.ID?.toUpperCase()),
2201
+ ...(terminalRecent?.Results ?? []).map((r) => r.ID?.toUpperCase()),
2202
+ ]);
2203
+ const pendingParents = (withPendingWork?.Results ?? []).map((r) => r.ParentID).filter(Boolean);
2204
+ const unproven = [...new Set(pendingParents.map((id) => id.toUpperCase()))].filter((id) => !workflowParents.has(id) && IsValidUUID(id));
2205
+ if (unproven.length > 0) {
2206
+ const proven = await rv.RunView({
2207
+ EntityName: 'MJ: Tasks',
2208
+ ExtraFilter: `${ofWorkflowType} AND ParentID IS NULL AND ID IN (${unproven.map((id) => `'${id}'`).join(',')})`,
2209
+ Fields: ['ID'],
2210
+ ResultType: 'simple',
2211
+ BypassCache: true,
2212
+ }, this.contextUser);
2213
+ for (const r of (proven.Success ? proven.Results : []) ?? [])
2214
+ workflowParents.add(r.ID.toUpperCase());
2215
+ }
2216
+ for (const parentID of pendingParents) {
2217
+ if (workflowParents.has(parentID.toUpperCase()))
2218
+ ids.add(parentID);
2039
2219
  }
2040
2220
  // Childless tasks match the second query too; propagateAndRollup skips anything with no
2041
2221
  // nodes, so they cost one empty load and nothing else.
@@ -2158,12 +2338,17 @@ export class TaskGraphDispatcher {
2158
2338
  continue;
2159
2339
  }
2160
2340
  }
2341
+ // A graph rolling back starts no new forward work, on any instance: the same rows decide it
2342
+ // everywhere (sagaHoldsForwardWork), so no dispatcher claims a step another is skipping.
2343
+ const sagaHolds = this.sagaHoldsForwardWork(graph);
2161
2344
  for (const node of eligible) {
2162
2345
  if (allowedTaskIDs && !allowedTaskIDs.has(node.id))
2163
2346
  continue;
2164
2347
  const entity = graph.entityById.get(node.id);
2165
2348
  if (!entity)
2166
2349
  continue;
2350
+ if (sagaHolds && !IsCompensationTask(entity))
2351
+ continue;
2167
2352
  // Human tasks are never dispatched — a person completes them. But "eligible" is the
2168
2353
  // moment that person can finally act, and nothing else in the system knows it has
2169
2354
  // arrived: the task sat Pending behind prerequisites, and no save touched it when
@@ -2219,6 +2404,8 @@ export class TaskGraphDispatcher {
2219
2404
  parentTask: graph.parent ?? null,
2220
2405
  parentMetadata: graph.parentMetadata,
2221
2406
  dependencyOutputs: this.extractDependencyOutputsFromGraph(entity.ID, graph),
2407
+ upstreamTasks: this.upstreamTasksInGraph(entity.ID, graph),
2408
+ upstreamOf: this.upstreamLookupInGraph(graph),
2222
2409
  });
2223
2410
  if (claimable.length >= limit)
2224
2411
  break;
@@ -2375,7 +2562,7 @@ export class TaskGraphDispatcher {
2375
2562
  if (expiresInHours && expiresInHours > 0) {
2376
2563
  request.ExpiresAt = new Date(Date.now() + expiresInHours * 60 * 60 * 1000);
2377
2564
  }
2378
- if (await request.Save()) {
2565
+ if (await this.saveWithRuntimeAuthority(request, 'MJ: AI Agent Requests')) {
2379
2566
  // INSERT-THEN-RESELECT (R3-5). The check above is read-then-write in a system whose
2380
2567
  // every other cross-instance write is a CAS, and there is no unique index behind it —
2381
2568
  // so two overlapping instances both read "none open", both insert, and both ping the
@@ -2507,7 +2694,12 @@ export class TaskGraphDispatcher {
2507
2694
  // this whole path exists to avoid, and a give-up edge can now route around it.
2508
2695
  task.ErrorMessage = 'Nobody answered this step before its request expired.';
2509
2696
  }
2510
- if (!(await task.Save())) {
2697
+ else {
2698
+ // Who answered: the step's review clears taint only when its assignee gave it
2699
+ // (HumanReviewClearsTaint). The request records its responder server-side when answered.
2700
+ task.Configuration = this.configurationWithCompletedBy(task, request.ResponseByUserID);
2701
+ }
2702
+ if (!(await this.saveWithRuntimeAuthority(task))) {
2511
2703
  LogError(`[TaskGraphDispatcher] Could not settle human task ${task.ID}: ` +
2512
2704
  `${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
2513
2705
  continue;
@@ -2592,6 +2784,26 @@ export class TaskGraphDispatcher {
2592
2784
  }
2593
2785
  }
2594
2786
  }
2787
+ /** The step's Configuration with `runtime.completedByUserID` set to `userID` (removed when there is none). */
2788
+ configurationWithCompletedBy(task, userID) {
2789
+ const existing = this.parseConfiguration(task);
2790
+ const { completedByUserID: _previous, ...runtime } = existing?.runtime ?? {};
2791
+ return JSON.stringify({ ...existing, runtime: { ...runtime, ...(userID ? { completedByUserID: userID } : {}) } });
2792
+ }
2793
+ /**
2794
+ * Saves a row inside {@link TASK_GRAPH_RUNTIME_SECURITY_OPERATION}, bound to this dispatcher's user and to
2795
+ * the row's entity: the one scope in which `MJTaskEntityServer` accepts a write of a task's runtime
2796
+ * security fields, and `MJAIAgentRequestEntityServer` accepts a new request for a workflow step. Only
2797
+ * the save runs inside it.
2798
+ */
2799
+ saveWithRuntimeAuthority(row, entityName = 'MJ: Tasks') {
2800
+ return ServerOperationScopeManager.Instance.RunWithAuthority({
2801
+ operationKey: TASK_GRAPH_RUNTIME_SECURITY_OPERATION,
2802
+ source: 'ServerEngine',
2803
+ allowedEntities: [entityName],
2804
+ userId: this.contextUser.ID,
2805
+ }, () => row.Save());
2806
+ }
2595
2807
  /** The answered (or expired) request for a task, if any. */
2596
2808
  async answeredRequestFor(provider, taskID) {
2597
2809
  const result = await RunView.FromMetadataProvider(provider).RunView({
@@ -2662,6 +2874,19 @@ export class TaskGraphDispatcher {
2662
2874
  }
2663
2875
  }
2664
2876
  /** Loads a graph's children and edges in the shapes both the algorithms and mutation need. */
2877
+ /** A graph state with no steps: what a parent with no children, or one that is not a workflow, loads as. */
2878
+ emptyGraphState(parentTaskID, parent) {
2879
+ return {
2880
+ parentTaskID,
2881
+ parent,
2882
+ parentMetadata: ParseTaskGraphParentMetadata(parent?.InputPayload ?? null),
2883
+ nodes: [], edges: [], entityById: new Map(),
2884
+ rawDependencies: [],
2885
+ unreachableTaskIDs: new Set(), cascadeSkipTaskIDs: new Set(),
2886
+ skipSeedTaskIDs: new Set(), holdTaskIDs: new Set(),
2887
+ handledFailureIDs: new Set(),
2888
+ };
2889
+ }
2665
2890
  async loadGraphState(provider, parentTaskID, debug, preloadedParent) {
2666
2891
  const rv = RunView.FromMetadataProvider(provider);
2667
2892
  // BypassCache throughout: task status is written by the claim protocol's direct SQL, which
@@ -2669,16 +2894,7 @@ export class TaskGraphDispatcher {
2669
2894
  const childrenResult = await rv.RunView({ EntityName: 'MJ: Tasks', ExtraFilter: `ParentID='${parentTaskID}'`, ResultType: 'entity_object', BypassCache: true }, this.contextUser);
2670
2895
  const children = (childrenResult.Success ? childrenResult.Results : []) ?? [];
2671
2896
  if (children.length === 0) {
2672
- return {
2673
- parentTaskID,
2674
- parent: preloadedParent ?? null,
2675
- parentMetadata: ParseTaskGraphParentMetadata(preloadedParent?.InputPayload ?? null),
2676
- nodes: [], edges: [], entityById: new Map(),
2677
- rawDependencies: [],
2678
- unreachableTaskIDs: new Set(), cascadeSkipTaskIDs: new Set(),
2679
- skipSeedTaskIDs: new Set(), holdTaskIDs: new Set(),
2680
- handledFailureIDs: new Set(),
2681
- };
2897
+ return this.emptyGraphState(parentTaskID, preloadedParent ?? null);
2682
2898
  }
2683
2899
  const idList = children.map((c) => `'${c.ID}'`).join(',');
2684
2900
  const depsResult = await rv.RunView({ EntityName: 'MJ: Task Dependencies', ExtraFilter: `TaskID IN (${idList})`, ResultType: 'entity_object', BypassCache: true }, this.contextUser);
@@ -2690,6 +2906,13 @@ export class TaskGraphDispatcher {
2690
2906
  const parent = preloadedParent !== undefined
2691
2907
  ? preloadedParent
2692
2908
  : await this.loadParentTask(provider, parentTaskID);
2909
+ // Only a workflow's steps run: its metadata names the user they run as, and a graph is trusted on that alone. A
2910
+ // missing parent, or one that is not a parentless task of the workflow type, runs nothing.
2911
+ const workflowTypeID = await this.workflowTaskTypeID(provider);
2912
+ if (!parent || parent.ParentID != null || !workflowTypeID || !UUIDsEqual(parent.TypeID, workflowTypeID)) {
2913
+ LogError(`[TaskGraphDispatcher] ${parentTaskID} has workflow steps but is not a workflow; its steps are not run.`);
2914
+ return this.emptyGraphState(parentTaskID, parent ?? null);
2915
+ }
2693
2916
  const parentMeta = parent
2694
2917
  ? ParseTaskGraphParentMetadata(parent.InputPayload)
2695
2918
  : ParseTaskGraphParentMetadata(null);
@@ -2909,7 +3132,7 @@ export class TaskGraphDispatcher {
2909
3132
  // Exclusive holds and ordinary-condition holds are the same state and share one set:
2910
3133
  // "we cannot tell yet, so nothing may claim this."
2911
3134
  holdTaskIDs: new Set([...resolution.holdTaskIDs, ...heldByCondition]),
2912
- handledFailureIDs: this.computeHandledFailures(failureSemantics, nodes, liveEdges),
3135
+ handledFailureIDs: this.computeHandledFailures(failureSemantics, nodes, liveEdges, entityById),
2913
3136
  };
2914
3137
  }
2915
3138
  /**
@@ -3074,6 +3297,85 @@ export class TaskGraphDispatcher {
3074
3297
  }
3075
3298
  }).catch(() => { });
3076
3299
  }
3300
+ /** The task rows `taskID` depends on, from the loaded graph (no query). */
3301
+ upstreamTasksInGraph(taskID, graph) {
3302
+ const upstream = [];
3303
+ for (const dep of this.dependencyRowsOf(taskID, graph)) {
3304
+ const row = graph.entityById.get(dep.DependsOnTaskID);
3305
+ if (row)
3306
+ upstream.push(row);
3307
+ }
3308
+ return upstream;
3309
+ }
3310
+ /**
3311
+ * Every task's prerequisites in the loaded graph, for the taint check to follow past a
3312
+ * prerequisite that recorded no taint. A dependency whose row is not in the graph makes that
3313
+ * task's prerequisites unknown, which the check reads as tainted.
3314
+ */
3315
+ upstreamLookupInGraph(graph) {
3316
+ return (taskID) => {
3317
+ const rows = [];
3318
+ for (const dep of this.dependencyRowsOf(taskID, graph)) {
3319
+ const row = graph.entityById.get(dep.DependsOnTaskID);
3320
+ if (!row)
3321
+ return undefined;
3322
+ rows.push(row);
3323
+ }
3324
+ return rows;
3325
+ };
3326
+ }
3327
+ /**
3328
+ * The graph's dependency rows of `taskID`. Indexed once per graph load: callers ask for every
3329
+ * claimable task in turn, and scanning all edges per task made a pass O(tasks × edges).
3330
+ */
3331
+ dependencyRowsOf(taskID, graph) {
3332
+ graph.dependenciesByTask ??= GroupByUUID(graph.rawDependencies ?? [], (dep) => dep.TaskID);
3333
+ return graph.dependenciesByTask.Get(taskID) ?? [];
3334
+ }
3335
+ /**
3336
+ * The envelope a node's runners receive: its stored constraints ({@link GraphContext.Security})
3337
+ * with `IsRunTainted` set to the node's input taint (`ComputeNodeInputTaint`), or why the node
3338
+ * must not run.
3339
+ */
3340
+ nodeEnvelope(task, context, prehydrated) {
3341
+ if ('Refusal' in context.Security) {
3342
+ return context.Security;
3343
+ }
3344
+ const stored = context.Security.Envelope;
3345
+ const inputTainted = ComputeNodeInputTaint({
3346
+ EnvelopeTainted: stored?.IsRunTainted === true,
3347
+ IsCompensation: IsCompensationTask(task),
3348
+ Upstream: prehydrated?.upstreamTasks ?? [],
3349
+ UpstreamOf: prehydrated?.upstreamOf,
3350
+ RecordsTaint: context.RecordsTaint,
3351
+ });
3352
+ return { Envelope: WithInputTaint(stored, inputTainted) };
3353
+ }
3354
+ /** Whether a node's input is tainted; a node refused on security grounds counts as tainted. */
3355
+ inputTaintOf(envelope) {
3356
+ return 'Refusal' in envelope || envelope.Envelope?.IsRunTainted === true;
3357
+ }
3358
+ /**
3359
+ * The failed outcome for a node refused on security grounds, or null when it may run. A node whose
3360
+ * envelope constrains anything runs only on a runner that enforces envelopes: the dispatcher
3361
+ * cannot apply a run scope, an audience or the taint gate itself, so a runner that does not
3362
+ * declare it would run the node unconstrained.
3363
+ */
3364
+ securityRefusal(task, envelope, runnerEnforces) {
3365
+ if ('Refusal' in envelope) {
3366
+ return this.refusedNode(task, envelope.Refusal);
3367
+ }
3368
+ if (EnvelopeConstrains(envelope.Envelope) && runnerEnforces !== true) {
3369
+ return this.refusedNode(task, 'This host\'s runner for the step does not enforce task security envelopes, and the workflow was ' +
3370
+ 'submitted by a run with an audience, a scope, a tenant, bound parameters or tainted content.');
3371
+ }
3372
+ return null;
3373
+ }
3374
+ /** A node refused on security grounds: failed, never run, and its output counted as tainted. */
3375
+ refusedNode(task, message) {
3376
+ LogError(`[TaskGraphDispatcher] Task '${task.Name}' (${task.ID}) refused: ${message}`);
3377
+ return { Success: false, AgentRunID: null, ErrorMessage: message, IsOutputTainted: true };
3378
+ }
3077
3379
  /**
3078
3380
  * Extracts parsed `OutputPayload` values for all dependencies of `taskID` directly from the
3079
3381
  * already-loaded `GraphState`, avoiding any additional database round-trips when claiming and
@@ -3081,10 +3383,7 @@ export class TaskGraphDispatcher {
3081
3383
  */
3082
3384
  extractDependencyOutputsFromGraph(taskID, graph) {
3083
3385
  const outputs = new Map();
3084
- const deps = graph.rawDependencies ?? [];
3085
- for (const dep of deps) {
3086
- if (!UUIDsEqual(dep.TaskID, taskID))
3087
- continue;
3386
+ for (const dep of this.dependencyRowsOf(taskID, graph)) {
3088
3387
  const upstream = graph.entityById.get(dep.DependsOnTaskID);
3089
3388
  if (!upstream?.OutputPayload)
3090
3389
  continue;
@@ -3097,9 +3396,14 @@ export class TaskGraphDispatcher {
3097
3396
  }
3098
3397
  return outputs;
3099
3398
  }
3100
- /** Parsed `OutputPayload` of each completed dependency, keyed by that task's ID. */
3101
- async loadDependencyOutputs(provider, taskID) {
3399
+ /**
3400
+ * The task rows `taskID` depends on, and the parsed `OutputPayload` of each, keyed by that task's
3401
+ * ID. The path for a task claimed without a graph load; `findClaimableTasks` reads both from the
3402
+ * graph it already holds.
3403
+ */
3404
+ async loadDependencies(provider, taskID) {
3102
3405
  const outputs = new Map();
3406
+ const upstreamRows = [];
3103
3407
  const rv = RunView.FromMetadataProvider(provider);
3104
3408
  // BypassCache: an upstream task's OutputPayload is written on the completion path, so a
3105
3409
  // cached read here can hand a dependent task the previous run's output — or none at all.
@@ -3108,6 +3412,7 @@ export class TaskGraphDispatcher {
3108
3412
  const upstream = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
3109
3413
  if (!(await upstream.Load(dep.DependsOnTaskID)))
3110
3414
  continue;
3415
+ upstreamRows.push(upstream);
3111
3416
  if (!upstream.OutputPayload)
3112
3417
  continue;
3113
3418
  try {
@@ -3117,7 +3422,7 @@ export class TaskGraphDispatcher {
3117
3422
  LogError(`[TaskGraphDispatcher] Task ${dep.DependsOnTaskID} has malformed OutputPayload: ${e}`);
3118
3423
  }
3119
3424
  }
3120
- return outputs;
3425
+ return { Outputs: outputs, Upstream: upstreamRows };
3121
3426
  }
3122
3427
  /**
3123
3428
  * Runs one task's body, whatever kind of step it is.
@@ -3129,6 +3434,10 @@ export class TaskGraphDispatcher {
3129
3434
  *
3130
3435
  * Every branch is normalized to one shape so the recording path above stays single: an action has
3131
3436
  * no agent run to point at, because its forensics live in `ActionExecutionLog` instead.
3437
+ *
3438
+ * **Every kind records its output taint here, as its input taint OR its own** (a Decision, a loop,
3439
+ * a failure and a refusal included). A kind that returned none — a Decision did, before — let its
3440
+ * output read as clean, so Fetch → Decision → Send Email ran the egress action ungated.
3132
3441
  */
3133
3442
  async runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress, prehydrated) {
3134
3443
  // A node's input is a name → value object (`TaskGraphSpecNode.inputPayload: Record<string, unknown>`).
@@ -3146,23 +3455,38 @@ export class TaskGraphDispatcher {
3146
3455
  LogError(`[TaskGraphDispatcher] ${message}`);
3147
3456
  return { Success: false, ErrorMessage: message };
3148
3457
  }
3149
- const payload = this.mergedPayload(inputPayload, dependencyOutputs);
3458
+ const rawPayload = this.mergedPayload(inputPayload, dependencyOutputs);
3459
+ // `data.*` / `context.*` resolve against the invocation that submitted the graph, exactly as
3460
+ // the in-run walker resolves them and as branch conditions already see them (R3-3). Without
3461
+ // it a mapping like `RecordID: data.ID` reached the action as the literal "data.ID".
3462
+ const context = await this.graphContext(provider, task, prehydrated);
3463
+ const nodeEnvelope = this.nodeEnvelope(task, context, prehydrated);
3464
+ const outcome = await this.runTaskBodyOfKind(task, provider, rawPayload, dependencyOutputs, context, nodeEnvelope, onProgress);
3465
+ return { ...outcome, IsOutputTainted: this.inputTaintOf(nodeEnvelope) || outcome.IsOutputTainted === true };
3466
+ }
3467
+ /** {@link runTaskBody} for one step kind, with the node's context and envelope already resolved. */
3468
+ async runTaskBodyOfKind(task, provider, rawPayload, dependencyOutputs, context, nodeEnvelope, onProgress) {
3150
3469
  const config = task.ConfigurationObject;
3151
3470
  // A loop's own step type decides how many times its body runs; the body itself is dispatched
3152
3471
  // through the very same runners as a one-shot step.
3153
3472
  if (task.StepType === 'ForEach' || task.StepType === 'While') {
3154
- return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs, prehydrated), PayloadAtStart: payload };
3473
+ return {
3474
+ ...await this.runLoopTask(task, provider, rawPayload, dependencyOutputs, context, nodeEnvelope),
3475
+ PayloadAtStart: rawPayload,
3476
+ };
3155
3477
  }
3156
3478
  // Routed on StepType before the mappings below: a Decision reads its state from the merged
3157
3479
  // payload by path and writes its answers back under `decisions`, so it has no mapping of its
3158
3480
  // own. And it carries a PromptID, so the Prompt branch would otherwise take it.
3159
3481
  if (task.StepType === 'Decision') {
3160
- return { ...await this.runDecisionNode(task, provider, payload, onProgress, prehydrated), PayloadAtStart: payload };
3482
+ return { ...await this.runDecisionNode(task, provider, rawPayload, context, onProgress), PayloadAtStart: rawPayload };
3161
3483
  }
3162
- // `data.*` / `context.*` resolve against the invocation that submitted the graph, exactly as
3163
- // the in-run walker resolves them and as branch conditions already see them (R3-3). Without
3164
- // it a mapping like `RecordID: data.ID` reached the action as the literal "data.ID".
3165
- const context = await this.graphContext(provider, task, prehydrated);
3484
+ if ('Refusal' in nodeEnvelope) {
3485
+ return { ...this.refusedNode(task, nodeEnvelope.Refusal), PayloadAtStart: rawPayload };
3486
+ }
3487
+ const effectiveEnvelope = nodeEnvelope.Envelope;
3488
+ const inputTainted = effectiveEnvelope?.IsRunTainted === true;
3489
+ const payload = rawPayload;
3166
3490
  const invocation = config?.inputMapping ? context.Invocation : {};
3167
3491
  const { params, errors } = BuildMappedInput(config?.inputMapping, { payload, ...invocation });
3168
3492
  for (const e of errors)
@@ -3180,7 +3504,16 @@ export class TaskGraphDispatcher {
3180
3504
  // which was TRUE of what it had been handed while twenty research results sat in the
3181
3505
  // dependency outputs beside it, and the reviewer then rejected the draft for saying so.
3182
3506
  // Every layer looked like it was working.
3183
- const effectiveInput = Object.keys(params).length > 0 ? params : payload;
3507
+ const rawEffectiveInput = Object.keys(params).length > 0 ? params : payload;
3508
+ const inputEnforcement = task.ActionID
3509
+ ? ApplyTaskSecurityEnvelopeToParams(rawEffectiveInput, effectiveEnvelope, task.ActionID)
3510
+ : { Params: rawEffectiveInput, OverriddenKeys: [] };
3511
+ const effectiveInput = inputEnforcement.Params;
3512
+ if (inputEnforcement.OverriddenKeys.length > 0) {
3513
+ const overridden = [...new Set(inputEnforcement.OverriddenKeys)];
3514
+ LogStatus(`[TaskGraphDispatcher] Task '${task.Name}' (${task.ID}): restored ${overridden.length} bound parameter(s) ` +
3515
+ `(${overridden.join(', ')}) from TaskSecurityEnvelope.`);
3516
+ }
3184
3517
  if (task.StepType === 'Prompt') {
3185
3518
  if (!this.promptRunner) {
3186
3519
  // Not a failure: "nobody here can run this" is not "this ran and did not work".
@@ -3195,6 +3528,7 @@ export class TaskGraphDispatcher {
3195
3528
  Provider: provider,
3196
3529
  ContextUser: context.ExecutionUser,
3197
3530
  OnProgress: onProgress,
3531
+ ...(effectiveEnvelope ? { SecurityEnvelope: effectiveEnvelope } : {}),
3198
3532
  });
3199
3533
  // A prompt's response is DEEP-MERGED into the payload rather than replacing it. A prompt
3200
3534
  // answers one question; replacing the payload with its answer would discard everything
@@ -3213,24 +3547,556 @@ export class TaskGraphDispatcher {
3213
3547
  // cost rollup that silently omits failures under-reports exactly the runs someone
3214
3548
  // is most likely to be investigating.
3215
3549
  PromptRunID: promptResult.PromptRunID,
3550
+ // Monotonic: a prompt fed tainted input writes tainted output.
3551
+ IsOutputTainted: inputTainted || promptResult.IsOutputTainted === true,
3216
3552
  };
3217
3553
  }
3554
+ const refusal = this.securityRefusal(task, nodeEnvelope, task.ActionID ? this.actionRunner?.EnforcesSecurityEnvelope : this.agentRunner.EnforcesSecurityEnvelope);
3555
+ if (refusal) {
3556
+ return { ...refusal, PayloadAtStart: payload };
3557
+ }
3218
3558
  const raw = task.ActionID
3219
- ? { ...await this.actionRunner.RunActionForTask({
3220
- TaskID: task.ID,
3221
- ActionID: task.ActionID,
3222
- InputPayload: effectiveInput,
3223
- DependencyOutputs: dependencyOutputs,
3224
- Provider: provider,
3225
- ContextUser: context.ExecutionUser,
3226
- OnProgress: onProgress,
3227
- }), AgentRunID: null }
3228
- : await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, context);
3559
+ ? {
3560
+ ...await this.invokeActionWithRetry(task, provider, effectiveInput, dependencyOutputs, context.ExecutionUser, onProgress, effectiveEnvelope),
3561
+ AgentRunID: null,
3562
+ }
3563
+ : await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, context, effectiveEnvelope);
3229
3564
  return {
3230
3565
  ...raw,
3231
3566
  Output: this.applyStepOutputMapping(task, payload, raw.Output, config?.outputMapping),
3232
3567
  PayloadAtStart: payload,
3568
+ ...(task.ActionID ? { ActionInput: effectiveInput } : {}),
3569
+ // Monotonic: tainted input taints the output, and so does an action or agent that read
3570
+ // untrusted content (the runner reports that from the action's trust level or the run's
3571
+ // tainted sources).
3572
+ IsOutputTainted: inputTainted || raw.IsOutputTainted === true,
3573
+ };
3574
+ }
3575
+ /**
3576
+ * Runs an action task, retrying a failure up to the step's `retryCount` — but only when running the
3577
+ * action again is safe: only when the action's `IsIdempotent` column says so. A forward step's node may
3578
+ * turn that off (`compensation.isIdempotent: false`) but never on, because the node is written by a
3579
+ * model and the column by whoever owns the action; a compensation task retries when its compensation
3580
+ * action is idempotent. A non-idempotent action is never re-run: a payment that failed after charging
3581
+ * must not charge again. Retries back off exponentially (`RetryBackoffBaseMs`, doubling, capped at 30×).
3582
+ */
3583
+ async invokeActionWithRetry(task, provider, effectiveInput, dependencyOutputs, executionUser, onProgress, effectiveEnvelope) {
3584
+ const run = () => this.actionRunner.RunActionForTask({
3585
+ TaskID: task.ID,
3586
+ ActionID: task.ActionID,
3587
+ InputPayload: effectiveInput,
3588
+ DependencyOutputs: dependencyOutputs,
3589
+ Provider: provider,
3590
+ ContextUser: executionUser,
3591
+ OnProgress: onProgress,
3592
+ ...(effectiveEnvelope ? { SecurityEnvelope: effectiveEnvelope } : {}),
3593
+ });
3594
+ let result = await run();
3595
+ if (result.Success || result.ResultCode === TAINTED_EGRESS_BLOCKED) {
3596
+ return result;
3597
+ }
3598
+ const retries = await this.allowedRetries(provider, task);
3599
+ for (let attempt = 1; !result.Success && attempt <= retries; attempt++) {
3600
+ const delay = RetryBackoffMs(attempt, this.config.RetryBackoffBaseMs);
3601
+ LogStatus(`[TaskGraphDispatcher] Retrying idempotent action task '${task.Name}' (${task.ID}) in ${delay}ms, attempt ${attempt}/${retries}.`);
3602
+ await new Promise((resolve) => setTimeout(resolve, delay));
3603
+ result = await run();
3604
+ }
3605
+ return result;
3606
+ }
3607
+ /**
3608
+ * How many times a failed action step may be retried: its `retryCount`, or 0 when the action is not
3609
+ * idempotent. Effective idempotency is `Action.IsIdempotent && node !== false`.
3610
+ */
3611
+ async allowedRetries(provider, task) {
3612
+ const config = this.parseConfiguration(task);
3613
+ const compensation = ReadTaskCompensationMetadata(task.Configuration);
3614
+ const requested = Math.max(0, Math.floor(config?.policy?.retryCount ?? compensation?.retryCount ?? 0));
3615
+ if (requested === 0 || !task.ActionID) {
3616
+ return 0;
3617
+ }
3618
+ // The action's own column decides. A forward step's node can only narrow it: a model-written
3619
+ // `isIdempotent: true` must not make a payment retryable that its action says is not.
3620
+ const actionIdempotent = (await this.actionRows(provider, [task.ActionID])).Get(task.ActionID)?.IsIdempotent === true;
3621
+ const nodeOptsOut = !IsCompensationTask(task) && compensation?.isIdempotent === false;
3622
+ const idempotent = actionIdempotent && !nodeOptsOut;
3623
+ if (!idempotent) {
3624
+ LogStatus(`[TaskGraphDispatcher] Not retrying '${task.Name}' (${task.ID}): its action is not marked idempotent.`);
3625
+ return 0;
3626
+ }
3627
+ return requested;
3628
+ }
3629
+ /**
3630
+ * The saga columns of the given actions (`CompensationActionID`, `CompensationInputMapping`,
3631
+ * `IsIdempotent`), read through their typed fields.
3632
+ */
3633
+ async actionRows(provider, actionIDs) {
3634
+ const byID = new UUIDMap();
3635
+ if (actionIDs.length === 0)
3636
+ return byID;
3637
+ const result = await RunView.FromMetadataProvider(provider).RunView({
3638
+ EntityName: 'MJ: Actions',
3639
+ ExtraFilter: `ID IN (${actionIDs.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`,
3640
+ Fields: ['ID', 'CompensationActionID', 'CompensationInputMapping', 'IsIdempotent'],
3641
+ ResultType: 'simple',
3642
+ }, this.contextUser);
3643
+ if (!result.Success) {
3644
+ LogError(`[TaskGraphDispatcher] Could not read action saga settings: ${result.ErrorMessage}`);
3645
+ return byID;
3646
+ }
3647
+ for (const row of result.Results ?? [])
3648
+ byID.Set(row.ID, row);
3649
+ return byID;
3650
+ }
3651
+ /**
3652
+ * The parent rollup while a saga still has work (S7): every forward step can be terminal while a
3653
+ * compensation is yet to be created or run, and settling then would mark the graph `Failed` (and
3654
+ * announce it) with the rollback unfinished, or never started. Such a graph stays `In Progress`.
3655
+ */
3656
+ rollupWhileCompensating(rollup, sagaPending) {
3657
+ if (!sagaPending || rollup.outcome !== 'settled') {
3658
+ return rollup;
3659
+ }
3660
+ return { status: 'In Progress', percentComplete: rollup.percentComplete, outcome: 'active' };
3661
+ }
3662
+ /**
3663
+ * Drives a graph's saga one move per pass (WS-4.3), when its `failurePolicy` is
3664
+ * `'CompensateCompleted'` and a forward step failed unhandled.
3665
+ *
3666
+ * Every decision is recomputed from durable rows ({@link NextSagaStep}), so any dispatcher picks up
3667
+ * where another left off, and every write is one that cannot be raced into a wrong state: the
3668
+ * remaining forward steps are skipped through the guarded `TrySkipPending` (and the claim filter
3669
+ * already refuses them, see `sagaHoldsForwardWork`), and each compensation or escalation row is
3670
+ * inserted with `CompensatesTaskID`, whose unique index lets exactly one dispatcher create it.
3671
+ *
3672
+ * @returns the graph (reloaded whenever this pass tried to insert a row, won or lost) and whether the
3673
+ * saga still has work, so the caller does not settle the parent under it
3674
+ */
3675
+ async coordinateSagaCompensation(provider, parentID, graph, debug) {
3676
+ if (!this.sagaHoldsForwardWork(graph)) {
3677
+ return { Graph: graph, Pending: false };
3678
+ }
3679
+ const forwardTasks = [...graph.entityById.values()].filter((t) => !IsCompensationTask(t));
3680
+ const snapshotHolds = await this.skipRemainingForwardTasks(provider, graph, forwardTasks);
3681
+ // A forward step still running may yet complete — and then needs compensating too. One claimed
3682
+ // elsewhere since this pass loaded the graph still reads Pending here; the next pass sees it.
3683
+ if (!snapshotHolds || forwardTasks.some((t) => t.Status === 'In Progress')) {
3684
+ return { Graph: graph, Pending: true };
3685
+ }
3686
+ const completedActionIDs = forwardTasks.filter((t) => t.Status === 'Complete' && t.ActionID).map((t) => t.ActionID);
3687
+ const actionDefaults = new UUIDMap();
3688
+ for (const [id, row] of await this.actionRows(provider, completedActionIDs)) {
3689
+ const meta = ReadActionCompensationMetadata(row);
3690
+ if (meta)
3691
+ actionDefaults.Set(id, meta);
3692
+ }
3693
+ const plan = SelectTasksToCompensate(forwardTasks, actionDefaults, graph.rawDependencies);
3694
+ const rows = IndexCompensationRows([...graph.entityById.values()]);
3695
+ const step = NextSagaStep({
3696
+ Plan: plan,
3697
+ CompensationFor: (id) => rows.Compensations.Get(id),
3698
+ EscalationFor: (id) => rows.Escalations.Get(id),
3699
+ });
3700
+ switch (step.Kind) {
3701
+ case 'Wait':
3702
+ await this.updateParentSagaState(provider, graph, 'Compensating');
3703
+ return { Graph: graph, Pending: true };
3704
+ case 'Compensate':
3705
+ await this.updateParentSagaState(provider, graph, 'Compensating');
3706
+ await this.materializeCompensation(provider, graph, step.Forward, step.Compensation);
3707
+ // Reloaded whether this insert won or not: a lost insert means another dispatcher's row
3708
+ // exists, and this snapshot does not hold it (S7).
3709
+ return { Graph: await this.loadGraphState(provider, parentID, debug, graph.parent), Pending: true };
3710
+ case 'Escalate':
3711
+ await this.updateParentSagaState(provider, graph, 'CompensationEscalated');
3712
+ await this.escalateCompensationFailure(provider, graph, step.Forward, step.FailedCompensation);
3713
+ return { Graph: await this.loadGraphState(provider, parentID, debug, graph.parent), Pending: true };
3714
+ case 'Finished':
3715
+ await this.updateParentSagaState(provider, graph, step.State);
3716
+ return { Graph: graph, Pending: false };
3717
+ }
3718
+ }
3719
+ /**
3720
+ * Whether a graph is rolling back, so its forward steps must not start: its policy is
3721
+ * `'CompensateCompleted'` and a forward step failed with no drawn route out of the failure. Read from
3722
+ * the rows, so every dispatcher's claim filter agrees.
3723
+ */
3724
+ sagaHoldsForwardWork(graph) {
3725
+ if (graph.parentMetadata?.failurePolicy !== 'CompensateCompleted') {
3726
+ return false;
3727
+ }
3728
+ return [...graph.entityById.values()].some((t) => !IsCompensationTask(t) && t.Status === 'Failed' && !graph.handledFailureIDs.has(t.ID));
3729
+ }
3730
+ /**
3731
+ * Skips every forward step still `Pending` once the graph is rolling back — independent branches too,
3732
+ * since running new work while undoing old work is what the policy exists to prevent. Guarded on
3733
+ * `Pending` in the statement, so a step another dispatcher claimed meanwhile is left to finish (and
3734
+ * is then compensated), never overwritten.
3735
+ *
3736
+ * @returns false when a skip did not land: that step was claimed elsewhere after this pass loaded
3737
+ * the graph (or the write failed), so this snapshot no longer says what is running, and the
3738
+ * saga must not plan from it — a step about to complete would be compensated out of reverse
3739
+ * order, or after the saga reported itself finished
3740
+ */
3741
+ async skipRemainingForwardTasks(provider, graph, forwardTasks) {
3742
+ const pending = forwardTasks.filter((t) => t.Status === 'Pending');
3743
+ if (pending.length === 0)
3744
+ return true;
3745
+ const typeID = await this.workflowTaskTypeID(provider);
3746
+ if (!typeID)
3747
+ return true;
3748
+ const nodeByID = IndexByUUID(graph.nodes, (n) => n.id);
3749
+ let allSkipped = true;
3750
+ for (const task of pending) {
3751
+ if (!(await this.claims.TrySkipPending(provider, task.ID, typeID, this.contextUser))) {
3752
+ allSkipped = false;
3753
+ continue;
3754
+ }
3755
+ task.Status = 'Skipped';
3756
+ const node = nodeByID.Get(task.ID);
3757
+ if (node)
3758
+ node.status = 'Skipped';
3759
+ LogStatus(`[TaskGraphDispatcher] Skipped '${task.Name}' (${task.ID}) — the workflow is rolling back.`);
3760
+ }
3761
+ await this.withdrawOpenRequests(provider, pending.filter((t) => t.Status === 'Skipped').map((t) => t.ID), 'The workflow is rolling back, so this step is no longer needed.');
3762
+ return allSkipped;
3763
+ }
3764
+ /**
3765
+ * Creates the compensation task for one forward step, linked by `CompensatesTaskID`. Its unique index
3766
+ * is the claim: when two dispatchers both get here, one insert succeeds and the other finds the
3767
+ * winner's row and treats the step as already materialized. Nothing is written to the forward step.
3768
+ *
3769
+ * A compensation that can never be created (its action does not exist, or the step's envelope cannot
3770
+ * be read) is recorded as a failed one at once ({@link recordUncreatableSagaRow}), so the saga
3771
+ * escalates it rather than waiting. One that failed for a reason that may not repeat (the action
3772
+ * lookup errored, or the insert failed with no other dispatcher's row behind it) is retried on later
3773
+ * passes, and recorded as failed only after {@link SAGA_ROW_WRITE_ATTEMPTS} of them in a row
3774
+ * ({@link retrySagaRowOrRecordFailed}).
3775
+ *
3776
+ * @returns true when this call wrote a row
3777
+ */
3778
+ async materializeCompensation(provider, graph, forwardTask, compensation) {
3779
+ const action = await this.resolveCompensationActionID(provider, compensation);
3780
+ const compActionID = action.ActionID;
3781
+ const envelope = this.compensationEnvelope(graph, forwardTask);
3782
+ const compTask = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
3783
+ compTask.NewRecord();
3784
+ compTask.ParentID = graph.parentTaskID;
3785
+ compTask.TypeID = forwardTask.TypeID;
3786
+ compTask.Name = `Compensate: ${forwardTask.Name}`;
3787
+ compTask.Description = `Saga compensation for task "${forwardTask.Name}" (${forwardTask.ID}).`;
3788
+ compTask.StepType = 'Action';
3789
+ compTask.Status = 'Pending';
3790
+ compTask.PercentComplete = 0;
3791
+ compTask.ActionID = compActionID;
3792
+ compTask.AgentRunID = forwardTask.AgentRunID ?? graph.parent?.AgentRunID ?? null;
3793
+ compTask.CompensatesTaskID = forwardTask.ID;
3794
+ // An envelope that cannot be read stays as stored, so the row is refused exactly as the step is.
3795
+ compTask.SecurityEnvelope = 'Refusal' in envelope ? forwardTask.SecurityEnvelope : SerializeTaskSecurityEnvelope(envelope.Envelope);
3796
+ const compConfig = {
3797
+ ...(compensation.retryCount != null ? { policy: { retryCount: compensation.retryCount } } : {}),
3798
+ compensation: {
3799
+ ...(compActionID ? { compensationActionId: compActionID } : {}),
3800
+ ...(compensation.onCompensationFailure ? { onCompensationFailure: compensation.onCompensationFailure } : {}),
3801
+ },
3233
3802
  };
3803
+ compTask.Configuration = JSON.stringify(compConfig);
3804
+ const cannotRun = !compActionID && action.LookupError === undefined
3805
+ ? 'its compensation action could not be resolved'
3806
+ : 'Refusal' in envelope ? `its security envelope cannot be enforced: ${envelope.Refusal}` : null;
3807
+ if (cannotRun) {
3808
+ return this.recordUncreatableSagaRow(provider, compTask, `Cannot compensate '${forwardTask.Name}' (${forwardTask.ID}): ${cannotRun}.`);
3809
+ }
3810
+ if (action.LookupError !== undefined) {
3811
+ return this.retrySagaRowOrRecordFailed(provider, graph, compTask, `Cannot compensate '${forwardTask.Name}' (${forwardTask.ID}): looking up its compensation action failed: ${action.LookupError}.`);
3812
+ }
3813
+ const actingUser = await this.sagaActingUser(provider, graph, forwardTask);
3814
+ const recordChanges = await this.loadCorrelatedRecordChanges(provider, forwardTask, actingUser);
3815
+ compTask.InputPayload = JSON.stringify(this.buildForwardTaskCompensationInput(forwardTask, compensation, recordChanges));
3816
+ if (await this.saveWithRuntimeAuthority(compTask)) {
3817
+ this.sagaRowWriteFailures.Delete(forwardTask.ID);
3818
+ LogStatus(`[TaskGraphDispatcher] Compensating '${forwardTask.Name}' (${forwardTask.ID}) with task ${compTask.ID}.`);
3819
+ return true;
3820
+ }
3821
+ if (await this.rowCompensating(provider, forwardTask.ID)) {
3822
+ this.sagaRowWriteFailures.Delete(forwardTask.ID);
3823
+ LogStatus(`[TaskGraphDispatcher] '${forwardTask.Name}' (${forwardTask.ID}) is already being compensated by another dispatcher.`);
3824
+ return false;
3825
+ }
3826
+ return this.retrySagaRowOrRecordFailed(provider, graph, compTask, `Could not create the compensation task for '${forwardTask.Name}' (${forwardTask.ID}): ${compTask.LatestResult?.CompleteMessage ?? 'unknown error'}.`);
3827
+ }
3828
+ /**
3829
+ * A saga row's write failed for a reason that may not repeat: a lookup that errored, or an insert
3830
+ * that failed with no other dispatcher's row behind it (or with that check failing too). The next
3831
+ * pass retries it; only after {@link SAGA_ROW_WRITE_ATTEMPTS} passes in a row have failed for the
3832
+ * same row is it recorded as failed ({@link recordUncreatableSagaRow}).
3833
+ *
3834
+ * @returns true when this call wrote the failed row
3835
+ */
3836
+ async retrySagaRowOrRecordFailed(provider, graph, intended, reason) {
3837
+ const key = intended.CompensatesTaskID;
3838
+ const passes = (this.sagaRowWriteFailures.Get(key)?.Passes ?? 0) + 1;
3839
+ this.sagaRowWriteFailures.Set(key, { GraphID: graph.parentTaskID, Passes: passes });
3840
+ if (passes < SAGA_ROW_WRITE_ATTEMPTS) {
3841
+ LogError(`[TaskGraphDispatcher] ${reason} Failed ${passes} of ${SAGA_ROW_WRITE_ATTEMPTS} passes in a row; the next pass retries.`);
3842
+ return false;
3843
+ }
3844
+ return this.recordUncreatableSagaRow(provider, intended, reason);
3845
+ }
3846
+ /**
3847
+ * Records a saga row that cannot be created as intended — a compensation, or the Human step escalating
3848
+ * a failed one — as a `Failed` row carrying the reason. The saga then moves on by its own rules
3849
+ * ({@link NextSagaStep}): a failed compensation escalates to a person (or halts or continues, per its
3850
+ * `onCompensationFailure`), and a failed escalation ends the rollback, so the graph settles. Leaving
3851
+ * the row unwritten kept the graph `In Progress` and its submitting run `Paused` forever, retrying a
3852
+ * write that could not succeed and logging it on every poll.
3853
+ *
3854
+ * The row carries only what the saga reads plus the reason, none of the columns that can make an
3855
+ * insert fail (payload, assignee, action), so it lands where the full row did not. It is claimed by
3856
+ * the same unique `CompensatesTaskID`. When even it cannot be written the database itself is failing,
3857
+ * and the next pass tries again.
3858
+ *
3859
+ * @returns true when this call wrote the row
3860
+ */
3861
+ async recordUncreatableSagaRow(provider, intended, reason) {
3862
+ const row = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
3863
+ row.NewRecord();
3864
+ const nameLimit = row.EntityInfo?.Fields.find((f) => f.Name === 'Name')?.MaxLength;
3865
+ row.ParentID = intended.ParentID;
3866
+ row.TypeID = intended.TypeID;
3867
+ row.Name = nameLimit ? intended.Name.slice(0, nameLimit) : intended.Name;
3868
+ row.Description = intended.Description;
3869
+ row.StepType = intended.StepType;
3870
+ row.Status = 'Failed';
3871
+ row.PercentComplete = 0;
3872
+ row.CompletedAt = new Date();
3873
+ row.ErrorMessage = reason;
3874
+ row.CompensatesTaskID = intended.CompensatesTaskID;
3875
+ row.SecurityEnvelope = intended.SecurityEnvelope;
3876
+ row.Configuration = intended.Configuration;
3877
+ if (await this.saveWithRuntimeAuthority(row)) {
3878
+ this.sagaRowWriteFailures.Delete(intended.CompensatesTaskID);
3879
+ LogError(`[TaskGraphDispatcher] ${reason} Recorded as failed step ${row.ID} so the rollback can go on.`);
3880
+ return true;
3881
+ }
3882
+ if (!(intended.CompensatesTaskID && await this.rowCompensating(provider, intended.CompensatesTaskID))) {
3883
+ LogError(`[TaskGraphDispatcher] ${reason} Could not record that either (${row.LatestResult?.CompleteMessage ?? 'unknown error'}); the next pass retries.`);
3884
+ }
3885
+ return false;
3886
+ }
3887
+ /**
3888
+ * Asks a person to undo a step by hand after its compensation failed under
3889
+ * `onCompensationFailure: 'EscalateToHumanTask'`: a `Human` step under the graph, assigned to the user
3890
+ * who submitted it, linked to the failed compensation task by `CompensatesTaskID` (unique, so one
3891
+ * escalation per failure however many dispatchers see it). The ordinary human-step machinery then
3892
+ * notifies the person and raises an `MJ: AI Agent Requests` row on behalf of the graph's agent — or,
3893
+ * for a graph with no agent, logs that once and leaves the step in the Tasks UI. Completing the step
3894
+ * resumes the rollback; cancelling it (or letting it expire) stops it (see {@link NextSagaStep}). A step
3895
+ * that cannot be created after {@link SAGA_ROW_WRITE_ATTEMPTS} passes in a row is recorded as a failed
3896
+ * one ({@link retrySagaRowOrRecordFailed}), which stops it too.
3897
+ *
3898
+ * The step carries the forward step's record changes, read as the user the graph's work runs as with
3899
+ * the caller's tenant from the envelope. An envelope that cannot be read carries no tenant
3900
+ * ({@link graphContext}), so that read would run untenanted: the step then gets no record changes.
3901
+ *
3902
+ * @returns true when this call wrote a row
3903
+ */
3904
+ async escalateCompensationFailure(provider, graph, forwardTask, failedCompensation) {
3905
+ const context = await this.graphContext(provider, forwardTask, { parentTask: graph.parent, parentMetadata: graph.parentMetadata });
3906
+ const actingUser = context.ExecutionUser;
3907
+ const escalation = BuildCompensationEscalationSummary({
3908
+ WorkflowName: graph.parent?.Name ?? graph.parentTaskID,
3909
+ ForwardTask: forwardTask,
3910
+ ForwardInput: this.runtimeActionInput(forwardTask),
3911
+ CompensationTask: failedCompensation,
3912
+ ActionLogID: this.runtimeActionLogID(forwardTask),
3913
+ RecordChanges: 'Refusal' in context.Security ? [] : await this.loadCorrelatedRecordChanges(provider, forwardTask, actingUser),
3914
+ });
3915
+ const human = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
3916
+ human.NewRecord();
3917
+ human.ParentID = graph.parentTaskID;
3918
+ human.TypeID = failedCompensation.TypeID;
3919
+ human.Name = `Undo by hand: ${forwardTask.Name}`;
3920
+ human.Description = escalation.RequestText;
3921
+ human.StepType = 'Human';
3922
+ human.Status = 'Pending';
3923
+ human.PercentComplete = 0;
3924
+ human.UserID = graph.parentMetadata?.submittedByUserID ?? graph.parent?.UserID ?? actingUser.ID;
3925
+ human.CompensatesTaskID = failedCompensation.ID;
3926
+ human.SecurityEnvelope = failedCompensation.SecurityEnvelope;
3927
+ human.InputPayload = JSON.stringify(escalation.ContextData);
3928
+ if (await this.saveWithRuntimeAuthority(human)) {
3929
+ this.sagaRowWriteFailures.Delete(failedCompensation.ID);
3930
+ LogStatus(`[TaskGraphDispatcher] Compensation ${failedCompensation.ID} failed; asked a person to undo '${forwardTask.Name}' (task ${human.ID}).`);
3931
+ return true;
3932
+ }
3933
+ if (await this.rowCompensating(provider, failedCompensation.ID)) {
3934
+ this.sagaRowWriteFailures.Delete(failedCompensation.ID);
3935
+ return false;
3936
+ }
3937
+ return this.retrySagaRowOrRecordFailed(provider, graph, human, `Could not ask a person to undo '${forwardTask.Name}' (${forwardTask.ID}) after compensation ${failedCompensation.ID} failed: ` +
3938
+ `${human.LatestResult?.CompleteMessage ?? 'unknown error'}.`);
3939
+ }
3940
+ /** Whether some task already undoes `taskID` — the row the unique `CompensatesTaskID` index let another dispatcher insert. */
3941
+ async rowCompensating(provider, taskID) {
3942
+ const result = await RunView.FromMetadataProvider(provider).RunView({
3943
+ EntityName: 'MJ: Tasks',
3944
+ ExtraFilter: `CompensatesTaskID='${EscapeSQLString(taskID)}'`,
3945
+ Fields: ['ID'],
3946
+ ResultType: 'simple',
3947
+ BypassCache: true,
3948
+ MaxRows: 1,
3949
+ }, this.contextUser);
3950
+ return result.Success && (result.Results?.length ?? 0) > 0;
3951
+ }
3952
+ /** The user the graph's work runs as (the submitter, stamped with the caller's tenant when the graph carries one). */
3953
+ async sagaActingUser(provider, graph, forwardTask) {
3954
+ const context = await this.graphContext(provider, forwardTask, { parentTask: graph.parent, parentMetadata: graph.parentMetadata });
3955
+ return context.ExecutionUser;
3956
+ }
3957
+ /** The `MJ: Action Execution Logs` row a completed action step recorded (`runtime.actionLogID`). */
3958
+ runtimeActionLogID(task) {
3959
+ return this.parseConfiguration(task)?.runtime?.actionLogID ?? null;
3960
+ }
3961
+ /**
3962
+ * The parameters a completed action step's action was given (`runtime.actionInput`), which the
3963
+ * dispatcher records when the step runs. Not `InputPayload`: that is only the authored input, and
3964
+ * the action's real parameters come from its input mapping over upstream outputs and the envelope.
3965
+ */
3966
+ runtimeActionInput(task) {
3967
+ return this.parseConfiguration(task)?.runtime?.actionInput ?? {};
3968
+ }
3969
+ /**
3970
+ * The envelope a compensation task is written with: the forward task's constraints, tainted when
3971
+ * the forward task's output carries taint ({@link UpstreamCarriesTaint}, so a forward task that
3972
+ * recorded none is read as tainted when the graph or anything upstream of it could be). A
3973
+ * compensation reads the forward run's input and output, so it runs under exactly what the forward
3974
+ * task ran under, and never less tainted than what it reads.
3975
+ */
3976
+ compensationEnvelope(graph, forwardTask) {
3977
+ const stored = ResolveStoredNodeSecurity(graph.parent?.SecurityEnvelope, forwardTask.SecurityEnvelope);
3978
+ if ('Refusal' in stored) {
3979
+ return stored;
3980
+ }
3981
+ const graphTainted = stored.Envelope?.IsRunTainted === true;
3982
+ const forwardTainted = UpstreamCarriesTaint(forwardTask, graphTainted, this.upstreamLookupInGraph(graph), graph.parentMetadata?.recordsTaint === true);
3983
+ return { Envelope: forwardTainted ? WithInputTaint(stored.Envelope, true) : stored.Envelope };
3984
+ }
3985
+ /**
3986
+ * Resolves a compensation action UUID from `compensationActionId` or `compensationActionName`.
3987
+ * `ActionID` is null when neither names an action that exists. `LookupError` says the name lookup
3988
+ * itself failed, so whether the action exists is unknown and a later pass may yet find it.
3989
+ */
3990
+ async resolveCompensationActionID(provider, compMeta) {
3991
+ if (compMeta.compensationActionId?.trim()) {
3992
+ return { ActionID: compMeta.compensationActionId.trim() };
3993
+ }
3994
+ const name = compMeta.compensationActionName?.trim();
3995
+ if (!name)
3996
+ return { ActionID: null };
3997
+ const resolved = await ResolveRecordsByNameOrToolName({
3998
+ EntityName: 'MJ: Actions',
3999
+ Names: [name],
4000
+ Provider: provider,
4001
+ ContextUser: this.contextUser,
4002
+ });
4003
+ if (!resolved.Success) {
4004
+ return { ActionID: null, LookupError: resolved.ErrorMessage || 'unknown error' };
4005
+ }
4006
+ return { ActionID: resolved.Map?.get(name) ?? resolved.Map?.get(name.toLowerCase()) ?? null };
4007
+ }
4008
+ /**
4009
+ * The `MJ: Record Changes` a forward action step made, for its compensation's input and a failed
4010
+ * compensation's escalation. Read as the user the graph's work runs as — never the system user — so
4011
+ * the user's own permissions bound what comes back.
4012
+ *
4013
+ * Bounded to the action's own execution window, `StartedAt`..`EndedAt` of the `MJ: Action Execution
4014
+ * Logs` row the step recorded, and to the user that log ran as. That is the tightest correlation the
4015
+ * data allows: a Record Change carries no action-log or task reference, only who changed what and
4016
+ * when, so a window around the one execution — not the task's whole life, which spans its queueing
4017
+ * and retries — is as close as it gets. Changes the same user made elsewhere inside that window can
4018
+ * still appear; a step with no recorded log gets none.
4019
+ */
4020
+ async loadCorrelatedRecordChanges(provider, forwardTask, actingUser) {
4021
+ const logID = this.runtimeActionLogID(forwardTask);
4022
+ if (!logID)
4023
+ return [];
4024
+ try {
4025
+ const rv = RunView.FromMetadataProvider(provider);
4026
+ const logs = await rv.RunView({
4027
+ EntityName: 'MJ: Action Execution Logs',
4028
+ ExtraFilter: `ID='${EscapeSQLString(logID)}'`,
4029
+ Fields: ['ID', 'StartedAt', 'EndedAt', 'UserID'],
4030
+ ResultType: 'simple',
4031
+ MaxRows: 1,
4032
+ }, actingUser);
4033
+ const log = logs.Success ? logs.Results?.[0] : undefined;
4034
+ if (!log?.StartedAt || !log.EndedAt)
4035
+ return [];
4036
+ const changes = await rv.RunView({
4037
+ EntityName: 'MJ: Record Changes',
4038
+ ExtraFilter: `UserID='${EscapeSQLString(log.UserID)}' AND ` +
4039
+ `ChangedAt >= '${new Date(log.StartedAt).toISOString()}' AND ChangedAt <= '${new Date(log.EndedAt).toISOString()}'`,
4040
+ Fields: ['ID', 'EntityID', 'Entity', 'RecordID', 'Type', 'ChangesJSON', 'ChangedAt'],
4041
+ OrderBy: 'ChangedAt ASC',
4042
+ MaxRows: 50,
4043
+ ResultType: 'simple',
4044
+ }, actingUser);
4045
+ return changes.Success ? changes.Results ?? [] : [];
4046
+ }
4047
+ catch (e) {
4048
+ LogError(`[TaskGraphDispatcher] Could not read the record changes of task ${forwardTask.ID}: ${e instanceof Error ? e.message : String(e)}`);
4049
+ return [];
4050
+ }
4051
+ }
4052
+ /**
4053
+ * Builds the compensation input payload from a completed forward task's input (the parameters its
4054
+ * action was given, {@link runtimeActionInput}), output, runtime log ID, and correlated
4055
+ * `MJ: Record Changes` rows.
4056
+ */
4057
+ buildForwardTaskCompensationInput(forwardTask, compMeta, recordChanges) {
4058
+ const forwardInput = this.runtimeActionInput(forwardTask);
4059
+ let forwardOutput = {};
4060
+ if (forwardTask.OutputPayload) {
4061
+ try {
4062
+ const parsedOutput = JSON.parse(forwardTask.OutputPayload);
4063
+ if (parsedOutput && typeof parsedOutput === 'object' && !Array.isArray(parsedOutput)) {
4064
+ forwardOutput = parsedOutput;
4065
+ }
4066
+ }
4067
+ catch {
4068
+ // Non-object output payloads default to `{}`
4069
+ }
4070
+ }
4071
+ return BuildCompensationInputPayload({
4072
+ ForwardInput: forwardInput,
4073
+ ForwardOutput: forwardOutput,
4074
+ ActionLogID: this.runtimeActionLogID(forwardTask),
4075
+ RecordChanges: recordChanges,
4076
+ InputMapping: compMeta.inputMapping,
4077
+ });
4078
+ }
4079
+ /**
4080
+ * Records the saga's state on the parent (`InputPayload.sagaState`) for anyone reading the graph.
4081
+ *
4082
+ * Written through the guarded, type-scoped single-field write and nothing else: a full-row save of the
4083
+ * parent would carry this pass's snapshot of `InputPayload` and could erase a continuation marker or a
4084
+ * debug field another dispatcher wrote meanwhile (R2-14, R3-1). The state is informational — every saga
4085
+ * decision is recomputed from the rows — so a write that does not land is retried on the next pass.
4086
+ */
4087
+ async updateParentSagaState(provider, graph, nextState) {
4088
+ if (graph.parentMetadata?.sagaState === nextState)
4089
+ return;
4090
+ const typeID = await this.workflowTaskTypeID(provider);
4091
+ if (!typeID)
4092
+ return;
4093
+ const wrote = await this.claims.TryWriteDebugFields(provider, graph.parentTaskID, [TaskClaimStore.DebugField('$.sagaState', { Kind: 'string', Value: nextState })], typeID, this.contextUser);
4094
+ if (wrote && graph.parentMetadata) {
4095
+ graph.parentMetadata.sagaState = nextState;
4096
+ }
4097
+ else if (!wrote) {
4098
+ LogError(`[TaskGraphDispatcher] Could not record sagaState='${nextState}' on graph ${graph.parentTaskID}; the next pass retries.`);
4099
+ }
3234
4100
  }
3235
4101
  /**
3236
4102
  * Runs a loop step: its body once per iteration, with the item and index in scope.
@@ -3240,7 +4106,7 @@ export class TaskGraphDispatcher {
3240
4106
  * merged into the payload before the mapping is applied, which is how a body can reference the
3241
4107
  * current item at all.
3242
4108
  */
3243
- async runLoopTask(task, provider, payload, dependencyOutputs, prehydrated) {
4109
+ async runLoopTask(task, provider, payload, dependencyOutputs, graphContext, startEnvelope) {
3244
4110
  const config = task.ConfigurationObject;
3245
4111
  const op = task.StepType === 'ForEach' ? config?.forEach : config?.while;
3246
4112
  if (!op) {
@@ -3262,13 +4128,22 @@ export class TaskGraphDispatcher {
3262
4128
  // the shared payload instead, each overwriting the last, and the mapping matched nothing and
3263
4129
  // wrote nothing. A ForEach over five items reported five successes and kept item five.
3264
4130
  const bodyOutputMapping = op.action?.outputMapping ?? op.prompt?.outputMapping;
3265
- // Where this step sits in its graph, resolved ONCE rather than per iteration. A loop body is
3266
- // dispatched exactly like a one-shot step and needs the same two things: the run that
3267
- // submitted the graph (so a spawned run gets a ParentRunID and is visible to the tree and to
3268
- // cost), and the continuation depth (so the recursion cap still applies). Omitting them made
3269
- // loop bodies second-class in every dimension — and reopened the unbounded-recursion hole
3270
- // THROUGH loops, since each spawned run restarted the chain at zero.
3271
- const graphContext = await this.graphContext(provider, task, prehydrated);
4131
+ // Where this step sits in its graph (`graphContext`), resolved ONCE by the caller rather than
4132
+ // per iteration. A loop body is dispatched exactly like a one-shot step and needs the same two
4133
+ // things: the run that submitted the graph (so a spawned run gets a ParentRunID and is visible
4134
+ // to the tree and to cost), and the continuation depth (so the recursion cap still applies).
4135
+ // Omitting them made loop bodies second-class in every dimension — and reopened the
4136
+ // unbounded-recursion hole THROUGH loops, since each spawned run restarted the chain at zero.
4137
+ if ('Refusal' in startEnvelope) {
4138
+ return this.refusedNode(task, startEnvelope.Refusal);
4139
+ }
4140
+ // Monotonic across passes as well as across nodes: once a pass reports tainted output, every
4141
+ // later pass reads it through the running payload, so it runs tainted too.
4142
+ let loopEnvelope = startEnvelope.Envelope;
4143
+ const markLoopTainted = () => {
4144
+ loopEnvelope = WithInputTaint(loopEnvelope, true);
4145
+ };
4146
+ const executionProvider = provider;
3272
4147
  // Pre-resolve ActionIDs once for multi-step action bodies (`op.steps[]`). Submit stamps
3273
4148
  // `config.stepActionIds`; fallback RunView covers callers constructing Task rows directly.
3274
4149
  const multiSteps = op.steps && op.steps.length > 0 ? op.steps : null;
@@ -3277,7 +4152,7 @@ export class TaskGraphDispatcher {
3277
4152
  if (!this.actionRunner) {
3278
4153
  return { Success: false, AgentRunID: null, ErrorMessage: 'No action runner is loaded on this host.' };
3279
4154
  }
3280
- const resolvedIds = await this.resolveLoopStepActionIds(multiSteps, config?.stepActionIds, task.ActionID, provider, graphContext.ExecutionUser);
4155
+ const resolvedIds = await this.resolveLoopStepActionIds(multiSteps, config?.stepActionIds, task.ActionID, executionProvider, graphContext.ExecutionUser);
3281
4156
  if (!resolvedIds.Success || !resolvedIds.Map) {
3282
4157
  return { Success: false, AgentRunID: null, ErrorMessage: resolvedIds.ErrorMessage };
3283
4158
  }
@@ -3314,11 +4189,13 @@ export class TaskGraphDispatcher {
3314
4189
  deferLivePayloadFold: isParallelForEach,
3315
4190
  deferredFoldsByIndex,
3316
4191
  dependencyOutputs,
3317
- provider,
4192
+ provider: executionProvider,
3318
4193
  executionUser: graphContext.ExecutionUser,
3319
4194
  invocation: graphContext.Invocation,
3320
4195
  iterationTrace,
3321
4196
  budget,
4197
+ securityEnvelope: loopEnvelope,
4198
+ onIterationTainted: markLoopTainted,
3322
4199
  });
3323
4200
  }
3324
4201
  // Bindings go INTO `iterationPayload` AND are passed explicitly to `ResolveLoopBodyParams`,
@@ -3326,10 +4203,14 @@ export class TaskGraphDispatcher {
3326
4203
  // `data.*`, `context.*`, `static:*`) AND the unified ForEachOperation/WhileOperation dialect
3327
4204
  // (`<itemVar>.*`, `{{<itemVar>.*}}`, inline `{{...}}`) while keeping unresolved paths/tokens literal.
3328
4205
  const iterationPayload = { ...livePayload, ...Bindings };
3329
- const resolved = ResolveLoopBodyParams(bodyMapping, Bindings, {
4206
+ const rawResolved = ResolveLoopBodyParams(bodyMapping, Bindings, {
3330
4207
  payload: iterationPayload,
3331
4208
  ...graphContext.Invocation,
3332
4209
  });
4210
+ const envelope = loopEnvelope;
4211
+ const resolved = task.ActionID
4212
+ ? ApplyTaskSecurityEnvelopeToParams(rawResolved, envelope, task.ActionID).Params
4213
+ : rawResolved;
3333
4214
  /**
3334
4215
  * Folds an iteration's output into the running payload the next pass will see, and
3335
4216
  * records what the pass produced.
@@ -3339,6 +4220,9 @@ export class TaskGraphDispatcher {
3339
4220
  * because the loop as a whole did not finish.
3340
4221
  */
3341
4222
  const absorb = (outcome, bodyInput) => {
4223
+ if (outcome.IsOutputTainted) {
4224
+ markLoopTainted();
4225
+ }
3342
4226
  livePayload = this.foldIterationOutput(task, livePayload, outcome.Output, bodyOutputMapping);
3343
4227
  iterationTrace.push({
3344
4228
  index: Index,
@@ -3396,18 +4280,24 @@ export class TaskGraphDispatcher {
3396
4280
  // getting it wrong is silent: the variable renders empty and the model answers
3397
4281
  // confidently about nothing.
3398
4282
  TemplateParameters: { ...stringifyBindings(Bindings), ...op.prompt?.templateParameters },
3399
- Provider: provider,
4283
+ Provider: executionProvider,
3400
4284
  ContextUser: graphContext.ExecutionUser,
4285
+ ...(envelope ? { SecurityEnvelope: envelope } : {}),
3401
4286
  }), iterationPayload);
3402
4287
  }
4288
+ const refusal = this.securityRefusal(task, { Envelope: envelope }, task.ActionID ? this.actionRunner?.EnforcesSecurityEnvelope : this.agentRunner.EnforcesSecurityEnvelope);
4289
+ if (refusal) {
4290
+ return refusal;
4291
+ }
3403
4292
  if (task.ActionID) {
3404
4293
  return absorb(await this.actionRunner.RunActionForTask({
3405
4294
  TaskID: task.ID,
3406
4295
  ActionID: task.ActionID,
3407
4296
  InputPayload: resolved,
3408
4297
  DependencyOutputs: dependencyOutputs,
3409
- Provider: provider,
4298
+ Provider: executionProvider,
3410
4299
  ContextUser: graphContext.ExecutionUser,
4300
+ ...(envelope ? { SecurityEnvelope: envelope } : {}),
3411
4301
  }), resolved);
3412
4302
  }
3413
4303
  const agentInput = Object.keys(resolved).length > 0 ? resolved : iterationPayload;
@@ -3422,13 +4312,14 @@ export class TaskGraphDispatcher {
3422
4312
  ContinuationDepth: graphContext.Depth,
3423
4313
  SubmittingAgentRunID: graphContext.SubmittingAgentRunID,
3424
4314
  ...(graphContext.ParentAgentHierarchy ? { ParentAgentHierarchy: graphContext.ParentAgentHierarchy } : {}),
3425
- Provider: provider,
4315
+ Provider: executionProvider,
3426
4316
  ContextUser: graphContext.ExecutionUser,
4317
+ ...(envelope ? { SecurityEnvelope: envelope } : {}),
3427
4318
  }), agentInput);
3428
4319
  };
3429
4320
  const evaluator = this.conditionEvaluator ?? new DispatcherConditionEvaluator();
3430
4321
  const outcome = task.StepType === 'ForEach'
3431
- ? await RunForEachLoop(op, { payload, ...graphContext.Invocation }, invokeBody)
4322
+ ? await RunForEachLoop(op, { payload: livePayload, ...graphContext.Invocation }, invokeBody)
3432
4323
  : await RunWhileLoop(op, (iteration) => evaluator.Evaluate(op.condition,
3433
4324
  // BOTH forms, because a workflow should not have two condition dialects. An
3434
4325
  // EDGE condition is written `payload.brandOK !== true`; a loop condition used
@@ -3461,6 +4352,7 @@ export class TaskGraphDispatcher {
3461
4352
  // pass inside `foldIterationOutput`; applying it again against the accumulated payload
3462
4353
  // is what used to make it match nothing.
3463
4354
  Output: this.applyStepOutputMapping(task, livePayload, outcome.Output, config?.outputMapping),
4355
+ IsOutputTainted: loopEnvelope?.IsRunTainted === true,
3464
4356
  };
3465
4357
  }
3466
4358
  /**
@@ -3504,7 +4396,7 @@ export class TaskGraphDispatcher {
3504
4396
  * `outputMapping` declarations into the loop's running payload.
3505
4397
  */
3506
4398
  async executeMultiStepLoopPass(args) {
3507
- const { task, op, steps, stepActionIds, index, bindings, getLivePayload, setLivePayload, deferLivePayloadFold, deferredFoldsByIndex, dependencyOutputs, provider, executionUser, invocation, iterationTrace, budget, } = args;
4399
+ const { task, op, steps, stepActionIds, index, bindings, getLivePayload, setLivePayload, deferLivePayloadFold, deferredFoldsByIndex, dependencyOutputs, provider, executionUser, invocation, iterationTrace, budget, securityEnvelope, onIterationTainted, } = args;
3508
4400
  const evaluator = this.conditionEvaluator ?? new DispatcherConditionEvaluator();
3509
4401
  const stepsOutputs = {};
3510
4402
  const stepInputsTrace = {};
@@ -3514,6 +4406,8 @@ export class TaskGraphDispatcher {
3514
4406
  let workingPayload = structuredClone(getLivePayload());
3515
4407
  let lastActionLogID;
3516
4408
  let lastStepOutput;
4409
+ // A later step reads an earlier step's output, so taint is monotonic within the pass too.
4410
+ let stepEnvelope = securityEnvelope;
3517
4411
  for (let stepIdx = 0; stepIdx < steps.length; stepIdx++) {
3518
4412
  const step = steps[stepIdx];
3519
4413
  const stepKey = step.id?.trim() || `step_${stepIdx}`;
@@ -3555,9 +4449,26 @@ export class TaskGraphDispatcher {
3555
4449
  }
3556
4450
  }
3557
4451
  const stepPayload = { ...workingPayload, ...stepBindings };
3558
- const resolvedParams = ResolveLoopBodyParams(step.params ?? {}, stepBindings, { payload: stepPayload, ...invocation });
3559
- stepInputsTrace[stepKey] = resolvedParams;
4452
+ const rawResolvedParams = ResolveLoopBodyParams(step.params ?? {}, stepBindings, { payload: stepPayload, ...invocation });
3560
4453
  const actionId = stepActionIds.get(step.name);
4454
+ const resolvedParams = ApplyTaskSecurityEnvelopeToParams(rawResolvedParams, stepEnvelope, actionId).Params;
4455
+ stepInputsTrace[stepKey] = resolvedParams;
4456
+ const gateRejection = this.securityRefusal(task, { Envelope: stepEnvelope }, this.actionRunner?.EnforcesSecurityEnvelope);
4457
+ if (gateRejection) {
4458
+ iterationTrace.push({
4459
+ index,
4460
+ payloadAtStart: budget.Take(stepInputsTrace),
4461
+ payloadAtEnd: budget.Take({ steps: stepsOutputs }),
4462
+ actionLogID: lastActionLogID,
4463
+ success: false,
4464
+ errorMessage: gateRejection.ErrorMessage,
4465
+ });
4466
+ return {
4467
+ Success: false,
4468
+ ErrorMessage: gateRejection.ErrorMessage,
4469
+ ActionLogID: lastActionLogID,
4470
+ };
4471
+ }
3561
4472
  const actionOutcome = await this.actionRunner.RunActionForTask({
3562
4473
  TaskID: task.ID,
3563
4474
  ActionID: actionId,
@@ -3565,10 +4476,15 @@ export class TaskGraphDispatcher {
3565
4476
  DependencyOutputs: dependencyOutputs,
3566
4477
  Provider: provider,
3567
4478
  ContextUser: executionUser,
4479
+ ...(stepEnvelope ? { SecurityEnvelope: stepEnvelope } : {}),
3568
4480
  });
3569
4481
  if (actionOutcome.ActionLogID) {
3570
4482
  lastActionLogID = actionOutcome.ActionLogID;
3571
4483
  }
4484
+ if (actionOutcome.IsOutputTainted) {
4485
+ stepEnvelope = WithInputTaint(stepEnvelope, true);
4486
+ onIterationTainted?.();
4487
+ }
3572
4488
  if (!actionOutcome.Success) {
3573
4489
  const errMsg = actionOutcome.ErrorMessage || `Loop step "${stepKey}" (${step.name}) failed`;
3574
4490
  iterationTrace.push({
@@ -3710,7 +4626,7 @@ export class TaskGraphDispatcher {
3710
4626
  * Depth and provenance are read together because they come from the same row: the graph's parent
3711
4627
  * task knows both how many continuation hops led here and which run submitted it.
3712
4628
  */
3713
- async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, resolvedContext) {
4629
+ async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, resolvedContext, securityEnvelope) {
3714
4630
  const context = resolvedContext ?? await this.graphContext(provider, task);
3715
4631
  const presetName = task.ConfigurationObject?.agent?.presetName?.trim() || undefined;
3716
4632
  return this.agentRunner.RunAgentForTask({
@@ -3725,6 +4641,7 @@ export class TaskGraphDispatcher {
3725
4641
  Provider: provider,
3726
4642
  ContextUser: context.ExecutionUser,
3727
4643
  OnProgress: onProgress,
4644
+ ...(securityEnvelope ? { SecurityEnvelope: securityEnvelope } : {}),
3728
4645
  });
3729
4646
  }
3730
4647
  /**
@@ -3741,7 +4658,7 @@ export class TaskGraphDispatcher {
3741
4658
  * and the call asks only the rest. If that call fails, or cannot be made, the step stays
3742
4659
  * `Complete` with the same usable answers, and the questions it asked again hold with the reason.
3743
4660
  */
3744
- async runDecisionNode(task, provider, payload, onProgress, prehydrated) {
4661
+ async runDecisionNode(task, provider, payload, context, onProgress) {
3745
4662
  const config = ReadDecisionStepConfiguration(task.Configuration);
3746
4663
  if (!config)
3747
4664
  return this.decisionNotAsked(task, payload, 'it has no decision settings, so there is nothing to ask');
@@ -3758,7 +4675,9 @@ export class TaskGraphDispatcher {
3758
4675
  const conflict = DecisionsPayloadConflict(payload);
3759
4676
  if (conflict)
3760
4677
  return notAsked(conflict);
3761
- const context = await this.graphContext(provider, task, prehydrated);
4678
+ if ('Refusal' in context.Security) {
4679
+ return this.refusedNode(task, context.Security.Refusal);
4680
+ }
3762
4681
  const startedAt = new Date();
3763
4682
  const result = await this.decisionRunner.RunDecisionForTask({
3764
4683
  TaskID: task.ID,
@@ -4235,8 +5154,10 @@ export class TaskGraphDispatcher {
4235
5154
  task.Configuration = JSON.stringify(merged);
4236
5155
  tasksToSave.push(task);
4237
5156
  }
5157
+ // In the dispatcher's scope: these in-memory rows can carry a status a guarded skip already wrote, and a
5158
+ // workflow step's status is the dispatcher's (`MJTaskEntityServer`).
4238
5159
  await Promise.all(tasksToSave.map(async (task) => {
4239
- if (!(await task.Save())) {
5160
+ if (!(await this.saveWithRuntimeAuthority(task))) {
4240
5161
  LogError(`[TaskGraphDispatcher] Could not save computed layout for ${task.ID}: ${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
4241
5162
  }
4242
5163
  }));
@@ -4274,8 +5195,8 @@ export class TaskGraphDispatcher {
4274
5195
  * Returns `undefined` when there is nothing to record, so the guarded write omits the column
4275
5196
  * rather than rewriting it with what it already held.
4276
5197
  */
4277
- configurationWithRuntime(task, promptRunID, actionLogID, iterations, payloadAtStart) {
4278
- if (!promptRunID && !actionLogID && !iterations?.length && !payloadAtStart)
5198
+ configurationWithRuntime(task, promptRunID, actionLogID, iterations, payloadAtStart, isOutputTainted, actionInput) {
5199
+ if (!promptRunID && !actionLogID && !iterations?.length && !payloadAtStart && isOutputTainted === undefined && !actionInput)
4279
5200
  return undefined;
4280
5201
  const existing = this.parseConfiguration(task);
4281
5202
  const merged = {
@@ -4292,6 +5213,10 @@ export class TaskGraphDispatcher {
4292
5213
  // against. NOT written to Task.InputPayload, which holds the AUTHORED input and
4293
5214
  // round-trips back out as part of the spec.
4294
5215
  ...(payloadAtStart ? { payloadAtStart } : {}),
5216
+ // Written true OR false: "ran clean" must be told apart from "never ran" (UpstreamCarriesTaint).
5217
+ ...(isOutputTainted !== undefined ? { isOutputTainted } : {}),
5218
+ // What the action was actually given, which its compensation's `input.*` reads.
5219
+ ...(actionInput ? { actionInput } : {}),
4295
5220
  },
4296
5221
  };
4297
5222
  return JSON.stringify(merged);