@memberjunction/task-graph 6.2.0-edge.4 → 6.2.0-edge.5

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.
@@ -792,7 +792,7 @@ export class TaskGraphDispatcher {
792
792
  // two were the same line of code.
793
793
  //
794
794
  // Only CLAIMING consumes capacity, because only claiming starts work.
795
- await this.propagateAndRollup(provider);
795
+ const activeGraphs = await this.propagateAndRollup(provider);
796
796
  const capacity = this.config.MaxConcurrentTasks - this.inFlight.size;
797
797
  if (capacity <= 0)
798
798
  return;
@@ -803,9 +803,10 @@ export class TaskGraphDispatcher {
803
803
  // starts after the decision to stop.
804
804
  if (!this.running)
805
805
  return;
806
- const { tasks: candidates, stats } = await this.findClaimableTasks(provider, capacity);
806
+ const { tasks: candidates, stats } = await this.findClaimableTasks(provider, capacity, activeGraphs);
807
807
  const claimedByGraph = new Map();
808
- for (const task of candidates) {
808
+ for (const candidate of candidates) {
809
+ const task = candidate.taskEntity;
809
810
  // Re-checked EVERY iteration, not once before the loop (R2-13). Claiming is itself
810
811
  // awaited, so a multi-task wave can straddle a `Stop`; and `findClaimableTasks` loads
811
812
  // and resolves every active graph, so the scan before this loop can run for seconds.
@@ -831,7 +832,7 @@ export class TaskGraphDispatcher {
831
832
  claimedByGraph.set(graphID, (claimedByGraph.get(graphID) ?? 0) + 1);
832
833
  this.inFlight.add(task.ID);
833
834
  // Intentionally not awaited — the poll loop must keep dispatching while this runs.
834
- void this.executeClaimed(task.ID).finally(() => this.inFlight.delete(task.ID));
835
+ void this.executeClaimed(task.ID, candidate).finally(() => this.inFlight.delete(task.ID));
835
836
  }
836
837
  // The engine's heartbeat, per watched graph: what was ready, what was held, what this
837
838
  // instance took. A stuck run is a strip of these ticking with nothing moving, which is
@@ -862,15 +863,29 @@ export class TaskGraphDispatcher {
862
863
  *
863
864
  * A fresh provider per task is the point of `ProviderFactory`: parallel tasks must not share a
864
865
  * transaction scope or entity instances, or one task's work becomes visible inside another's.
866
+ *
867
+ * When `prehydrated` is supplied by `findClaimableTasks`, the task entity, parent graph metadata,
868
+ * and upstream dependency outputs are already in memory from the poll pass — eliminating $3 + D$
869
+ * redundant pre-execution database queries per claimed node.
865
870
  */
866
- async executeClaimed(taskID) {
871
+ async executeClaimed(taskOrID, prehydrated) {
872
+ const hydrated = typeof taskOrID === 'string' ? prehydrated : taskOrID;
873
+ const taskID = typeof taskOrID === 'string'
874
+ ? taskOrID
875
+ : (taskOrID.taskId ?? taskOrID.ID ?? taskOrID.taskEntity.ID);
867
876
  let heartbeat = null;
868
877
  try {
869
878
  const provider = await this.providerFactory.CreateProvider();
870
- const task = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
871
- if (!(await task.Load(taskID))) {
872
- LogError(`[TaskGraphDispatcher] Claimed task ${taskID} could not be loaded.`);
873
- return;
879
+ let task;
880
+ if (hydrated?.taskEntity) {
881
+ task = hydrated.taskEntity;
882
+ }
883
+ else {
884
+ task = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
885
+ if (!(await task.Load(taskID))) {
886
+ LogError(`[TaskGraphDispatcher] Claimed task ${taskID} could not be loaded.`);
887
+ return;
888
+ }
874
889
  }
875
890
  // Emitted after the claim is held, not before: a frame saying "started" for work another
876
891
  // instance actually took would be a lie a viewer cannot detect.
@@ -910,7 +925,11 @@ export class TaskGraphDispatcher {
910
925
  ClaimEvent: 'claimed', ClaimedBy: this.config.InstanceID,
911
926
  ClaimExpiresAt: new Date(Date.now() + this.config.ClaimTTLSeconds * 1000).toISOString(),
912
927
  });
913
- const dependencyOutputs = await this.loadDependencyOutputs(provider, taskID);
928
+ const dependencyOutputs = hydrated?.dependencyOutputs instanceof Map
929
+ ? hydrated.dependencyOutputs
930
+ : hydrated?.dependencyOutputs
931
+ ? new Map(Object.entries(hydrated.dependencyOutputs))
932
+ : await this.loadDependencyOutputs(provider, taskID);
914
933
  const parsed = ParseTaskInputPayload(taskID, task.InputPayload);
915
934
  let result;
916
935
  if ('ErrorMessage' in parsed) {
@@ -921,7 +940,7 @@ export class TaskGraphDispatcher {
921
940
  }
922
941
  else {
923
942
  const onProgress = this.nodeProgressEmitter(graphID, ownerUserID, taskID, task.Name);
924
- result = await this.runTaskBody(task, provider, parsed.Payload, dependencyOutputs, onProgress);
943
+ result = await this.runTaskBody(task, provider, parsed.Payload, dependencyOutputs, onProgress, hydrated);
925
944
  }
926
945
  // ONLY THE CONFIRMED OWNER MUTATES THE GRAPH (R2-10).
927
946
  //
@@ -982,30 +1001,40 @@ export class TaskGraphDispatcher {
982
1001
  }
983
1002
  }
984
1003
  /**
985
- * Applies failure propagation and parent rollup across every graph with active work.
1004
+ * Applies failure propagation and parent rollup across every graph with active work, returning
1005
+ * the surviving non-terminal graphs so `findClaimableTasks` can reuse them without re-querying.
986
1006
  *
987
1007
  * All four decisions — what is eligible, what must block, what the parent status is, whether the
988
1008
  * graph is wedged — are delegated to the pure algorithms, unchanged from Phase 1.
989
1009
  */
990
1010
  async propagateAndRollup(provider, graphIDs) {
991
1011
  const graphs = graphIDs ?? await this.findActiveGraphIDs(provider);
992
- // One read for every graph this pass touches, rather than one per graph — see primeDebugStates.
993
- await this.primeDebugStates(provider, graphs);
1012
+ const survivingGraphs = [];
994
1013
  for (const parentID of graphs) {
995
- // Human steps settle BEFORE the graph state is read, so an answer given since the last
996
- // poll is already reflected when eligibility and rollup are computed. Doing it after
997
- // would delay every dependent branch by a full poll interval for no reason — and on a
998
- // graph whose only remaining work is downstream of a person, that is the difference
999
- // between "answered and moving" and "answered and apparently still stuck".
1000
- await this.expireOverdueRequests(provider, parentID);
1001
- await this.settleAnsweredHumanTasks(provider, parentID);
1002
- await this.reconcileWaitingHumanTasks(provider, parentID);
1003
1014
  // Edge overrides apply to propagation exactly as they apply to claiming — a branch the
1004
1015
  // operator answered 'false' must cascade its skips here, not merely stop being claimed.
1005
- const debug = await this.readDebugState(provider, parentID);
1006
- const graph = await this.loadGraphState(provider, parentID, debug);
1016
+ // `loadGraphState` loads the parent row once and populates `debugStateByGraph` and
1017
+ // `ownerByParentID` from it, avoiding a separate `primeDebugStates` RunView round-trip.
1018
+ let graph = await this.loadGraphState(provider, parentID);
1007
1019
  if (graph.nodes.length === 0)
1008
1020
  continue;
1021
+ const debug = await this.readDebugState(provider, parentID);
1022
+ // Human steps are only swept when the loaded graph actually contains at least one
1023
+ // non-terminal Human task. When a graph has 0 pending human tasks (99% of graphs), this
1024
+ // check short-circuits in memory with 0 DB queries instead of running 3 RunViews per graph.
1025
+ const pendingHumanTasks = [...graph.entityById.values()].filter((t) => t.Status === 'Pending' && IsHumanTask(t));
1026
+ if (pendingHumanTasks.length > 0) {
1027
+ await this.expireOverdueRequests(provider, parentID, pendingHumanTasks);
1028
+ const settledHumanCount = await this.settleAnsweredHumanTasks(provider, parentID, pendingHumanTasks);
1029
+ await this.reconcileWaitingHumanTasks(provider, parentID, pendingHumanTasks);
1030
+ if (settledHumanCount > 0) {
1031
+ // Re-evaluate conditional edges and skip/block cascades now that a human step's
1032
+ // answer and status have landed, reusing the already-loaded parent task.
1033
+ graph = await this.loadGraphState(provider, parentID, debug, graph.parent);
1034
+ if (graph.nodes.length === 0)
1035
+ continue;
1036
+ }
1037
+ }
1009
1038
  // SKIPS FIRST — before blocking, before eligibility. A task whose gating predecessors
1010
1039
  // are all Skipped is simultaneously "eligible" (Skipped satisfies a prerequisite) and
1011
1040
  // "to be skipped"; deciding eligibility first would dispatch the branch nobody took.
@@ -1067,6 +1096,9 @@ export class TaskGraphDispatcher {
1067
1096
  continue;
1068
1097
  entity.Status = 'Blocked';
1069
1098
  if (await entity.Save()) {
1099
+ const node = graph.nodes.find((n) => n.id === taskID);
1100
+ if (node)
1101
+ node.status = 'Blocked';
1070
1102
  LogStatus(`[TaskGraphDispatcher] Blocked '${entity.Name}' (${taskID}) — a dependency can never be satisfied.`);
1071
1103
  // Worth announcing on its own: a blocked step is the one outcome a viewer would
1072
1104
  // otherwise see as a task that simply never starts.
@@ -1087,17 +1119,18 @@ export class TaskGraphDispatcher {
1087
1119
  if (IsGraphStalled(graph.nodes, graph.edges, graph.holdTaskIDs)) {
1088
1120
  LogError(`[TaskGraphDispatcher] Graph ${parentID} is stalled: pending work with no satisfiable path.`);
1089
1121
  }
1090
- const fresh = await this.loadGraphState(provider, parentID, debug);
1091
- // ComputeParentRollup treats an empty child set as Complete-and-terminal, which is right
1092
- // for a graph that genuinely has no children and catastrophic for one whose reload came
1093
- // back empty transiently — it would mark live work finished and fire its continuation.
1094
- // The outer guard covered the first load only.
1095
- if (fresh.nodes.length === 0)
1096
- continue;
1097
- const rollup = ComputeParentRollup(fresh.nodes, fresh.handledFailureIDs);
1098
- const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
1099
- if (!(await parent.Load(parentID)))
1100
- continue;
1122
+ // Reuse the in-memory `graph` (whose `nodes` and `entityById` were updated in-place as
1123
+ // skips and blocks landed) and its pre-loaded `graph.parent` instead of reloading the
1124
+ // graph state and parent task a second time.
1125
+ const rollup = ComputeParentRollup(graph.nodes, graph.handledFailureIDs);
1126
+ let parent = graph.parent;
1127
+ if (!parent) {
1128
+ const fallbackParent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
1129
+ if (!(await fallbackParent.Load(parentID)))
1130
+ continue;
1131
+ parent = fallbackParent;
1132
+ graph.parent = parent;
1133
+ }
1101
1134
  // A graph starts when its first step does.
1102
1135
  //
1103
1136
  // `StartedAt` is stamped by the CLAIM, and a parent is never claimed — it is a container,
@@ -1113,7 +1146,7 @@ export class TaskGraphDispatcher {
1113
1146
  // carry this instance's `InputPayload` snapshot and could erase a continuation marker
1114
1147
  // another instance had just claimed. Guarded on `StartedAt IS NULL`, so calling it on
1115
1148
  // every pass is free.
1116
- const earliestChildStart = this.earliestStart(fresh.entityById);
1149
+ const earliestChildStart = this.earliestStart(graph.entityById);
1117
1150
  if (parent.StartedAt == null && earliestChildStart != null) {
1118
1151
  await this.claims.TryStampParentStart(provider, parentID, earliestChildStart, this.contextUser);
1119
1152
  parent.StartedAt = earliestChildStart;
@@ -1142,13 +1175,16 @@ export class TaskGraphDispatcher {
1142
1175
  }
1143
1176
  parent.Status = rollup.status;
1144
1177
  }
1145
- else if (parent.Status !== rollup.status || parent.PercentComplete !== rollup.percentComplete) {
1146
- // Guarded and column-scoped for the same reason the terminal write is — and the race
1147
- // here needs no exotic timing. This instance may have computed a non-terminal rollup
1148
- // from a snapshot taken before another instance settled the graph; a full-row save
1149
- // would then REVERT the status and erase the continuation marker with it, and the
1150
- // next pass would settle and deliver a second time. See TryUpdateParentProgress.
1151
- await this.claims.TryUpdateParentProgress(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
1178
+ else {
1179
+ if (parent.Status !== rollup.status || parent.PercentComplete !== rollup.percentComplete) {
1180
+ // Guarded and column-scoped for the same reason the terminal write is — and the race
1181
+ // here needs no exotic timing. This instance may have computed a non-terminal rollup
1182
+ // from a snapshot taken before another instance settled the graph; a full-row save
1183
+ // would then REVERT the status and erase the continuation marker with it, and the
1184
+ // next pass would settle and deliver a second time. See TryUpdateParentProgress.
1185
+ await this.claims.TryUpdateParentProgress(provider, parentID, rollup.status, rollup.percentComplete, this.contextUser);
1186
+ }
1187
+ survivingGraphs.push(graph);
1152
1188
  }
1153
1189
  if (rollup.outcome === 'settled') {
1154
1190
  // ANNOUNCE ONCE PER PROCESS, RETRY THE REST (R2-12). Layout and the frame are
@@ -1158,7 +1194,7 @@ export class TaskGraphDispatcher {
1158
1194
  // for the whole rescue window.
1159
1195
  if (!this.announcedSettlements.has(parentID)) {
1160
1196
  // Geometry is settled once, here, so every viewer of this run agrees on it.
1161
- await this.persistComputedLayout(fresh);
1197
+ await this.persistComputedLayout(graph);
1162
1198
  // Emitted before the continuation is delivered, and outside its once-only guard: a
1163
1199
  // viewer watching the run should learn it finished whether or not this instance is
1164
1200
  // the one that wins the delivery CAS.
@@ -1167,8 +1203,8 @@ export class TaskGraphDispatcher {
1167
1203
  ParentTaskID: parentID,
1168
1204
  OwnerUserID: await this.resolveOwner(provider, parentID),
1169
1205
  Status: rollup.status,
1170
- CompletedCount: fresh.nodes.filter((n) => n.status === 'Complete').length,
1171
- TotalCount: fresh.nodes.length,
1206
+ CompletedCount: graph.nodes.filter((n) => n.status === 'Complete').length,
1207
+ TotalCount: graph.nodes.length,
1172
1208
  });
1173
1209
  this.announcedSettlements.add(parentID);
1174
1210
  }
@@ -1219,7 +1255,7 @@ export class TaskGraphDispatcher {
1219
1255
  this.keepRetryingSettlement(parentID);
1220
1256
  continue;
1221
1257
  }
1222
- if (await this.deliverContinuation(provider, parent, fresh, readiness.SubmitterCancelled)) {
1258
+ if (await this.deliverContinuation(provider, parent, graph, readiness.SubmitterCancelled)) {
1223
1259
  // Delivered, expired, or lost the CAS to a peer — every one of those means this
1224
1260
  // graph is somebody's finished business and needs nothing further from here.
1225
1261
  this.retryingSettlement.delete(parentID);
@@ -1232,6 +1268,7 @@ export class TaskGraphDispatcher {
1232
1268
  }
1233
1269
  }
1234
1270
  }
1271
+ return survivingGraphs;
1235
1272
  }
1236
1273
  /**
1237
1274
  * Credits a finished graph's spending back to the agent run that submitted it.
@@ -1499,37 +1536,83 @@ export class TaskGraphDispatcher {
1499
1536
  }
1500
1537
  }
1501
1538
  /**
1502
- * How deep the continuation chain already is, read from the graph's parent metadata.
1539
+ * How deep the continuation chain already is, read from the graph's parent metadata, plus
1540
+ * the resolved `ExecutionUser` of the user who submitted the graph.
1503
1541
  *
1504
1542
  * A run started by a graph inherits that graph's depth **plus one**. Without this every spawned
1505
1543
  * run begins at zero, so a self-referencing flow — one that dispatches a graph containing itself
1506
1544
  * — recurses without bound while the cap it should be hitting compares against a permanent zero.
1507
1545
  */
1508
- async graphContext(provider, task) {
1509
- const none = { Depth: 0, SubmittingAgentRunID: null, Invocation: {} };
1510
- if (!task.ParentID)
1511
- return none;
1512
- try {
1513
- const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
1514
- if (!(await parent.Load(task.ParentID))) {
1515
- LogError(`[TaskGraphDispatcher] Task ${task.ID}: parent ${task.ParentID} could not be loaded; running at depth 0 with no invocation data/context.`);
1516
- return none;
1546
+ async graphContext(provider, task, prehydrated) {
1547
+ let depth = 0;
1548
+ let submittingAgentRunID = null;
1549
+ let invocation = {};
1550
+ let submittedByUserID = task.UserID;
1551
+ if (task.ParentID && prehydrated && (prehydrated.parentMetadata || prehydrated.parentTask)) {
1552
+ const parent = prehydrated.parentTask ?? null;
1553
+ const meta = (prehydrated.parentMetadata && typeof prehydrated.parentMetadata.reinvokeDepth === 'number')
1554
+ ? prehydrated.parentMetadata
1555
+ : ParseTaskGraphParentMetadata(parent?.InputPayload ?? null);
1556
+ depth = meta.reinvokeDepth + 1;
1557
+ submittingAgentRunID = parent?.AgentRunID ?? meta.submittedByAgentRunID ?? null;
1558
+ invocation = { data: meta.invocation?.data, context: meta.invocation?.context };
1559
+ submittedByUserID = meta.submittedByUserID ?? parent?.UserID ?? task.UserID;
1560
+ }
1561
+ else if (task.ParentID && typeof provider?.GetEntityObject === 'function') {
1562
+ try {
1563
+ const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
1564
+ if (!(await parent.Load(task.ParentID))) {
1565
+ LogError(`[TaskGraphDispatcher] Task ${task.ID}: parent ${task.ParentID} could not be loaded; running at depth 0 with no invocation data/context.`);
1566
+ }
1567
+ else {
1568
+ const meta = ParseTaskGraphParentMetadata(parent.InputPayload);
1569
+ depth = meta.reinvokeDepth + 1;
1570
+ submittingAgentRunID = parent.AgentRunID;
1571
+ invocation = { data: meta.invocation?.data, context: meta.invocation?.context };
1572
+ submittedByUserID = meta.submittedByUserID ?? parent.UserID ?? task.UserID;
1573
+ }
1574
+ }
1575
+ catch (e) {
1576
+ // An unreadable parent must not stop the work; depth zero is the safe reading, and the
1577
+ // submit-time cap still guards the next hop. Logged, because it also blanks `data.*`.
1578
+ 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)}`);
1517
1579
  }
1518
- const meta = ParseTaskGraphParentMetadata(parent.InputPayload);
1519
- return {
1520
- Depth: meta.reinvokeDepth + 1,
1521
- // The graph's own row carries the run that submitted it and the invocation it was
1522
- // submitted with. One load answers all three, which is why they are resolved together.
1523
- SubmittingAgentRunID: parent.AgentRunID,
1524
- Invocation: { data: meta.invocation?.data, context: meta.invocation?.context },
1525
- };
1526
1580
  }
1527
- catch (e) {
1528
- // An unreadable parent must not stop the work; depth zero is the safe reading, and the
1529
- // submit-time cap still guards the next hop. Logged, because it also blanks `data.*`.
1530
- 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)}`);
1531
- return none;
1581
+ const executionUser = await this.resolveGraphExecutionUser(submittedByUserID, task.ParentID ?? task.ID);
1582
+ return {
1583
+ Depth: depth,
1584
+ SubmittingAgentRunID: submittingAgentRunID,
1585
+ Invocation: invocation,
1586
+ ExecutionUser: executionUser,
1587
+ };
1588
+ }
1589
+ /**
1590
+ * Resolves the submitting user's `UserInfo` for a task graph so durable node executions
1591
+ * (Agent, Action, Prompt, Decision) run under the submitting user's security context
1592
+ * rather than the background server daemon's `this.contextUser`.
1593
+ */
1594
+ async resolveGraphExecutionUser(submittedByUserID, graphDescription) {
1595
+ const targetUserID = submittedByUserID?.trim();
1596
+ if (!targetUserID) {
1597
+ return this.contextUser;
1598
+ }
1599
+ if (this.contextUser?.ID && UUIDsEqual(this.contextUser.ID, targetUserID)) {
1600
+ return this.contextUser;
1532
1601
  }
1602
+ const userCache = globalThis.___SINGLETON__UserCache;
1603
+ if (userCache && typeof userCache.FindUser === 'function') {
1604
+ const ownerUser = await userCache.FindUser({ ID: targetUserID });
1605
+ if (ownerUser) {
1606
+ if (ownerUser.IsActive === false) {
1607
+ throw new Error(`Cannot execute task graph${graphDescription ? ` (${graphDescription})` : ''}: submitting user ${targetUserID} is inactive.`);
1608
+ }
1609
+ return ownerUser;
1610
+ }
1611
+ if (Array.isArray(userCache.Users) && userCache.Users.length > 0) {
1612
+ throw new Error(`Cannot execute task graph${graphDescription ? ` (${graphDescription})` : ''}: submitting user ${targetUserID} not found in UserCache.`);
1613
+ }
1614
+ }
1615
+ return this.contextUser;
1533
1616
  }
1534
1617
  /**
1535
1618
  * Which failures the workflow drew a way out of.
@@ -1745,7 +1828,7 @@ export class TaskGraphDispatcher {
1745
1828
  * loop; the task is still visible in the Tasks UI, so the work is discoverable even when the
1746
1829
  * nudge does not arrive.
1747
1830
  */
1748
- async notifyHumanTaskReady(task, provider) {
1831
+ async notifyHumanTaskReady(task, provider, preloadedParent) {
1749
1832
  if (task.ClaimedBy === HUMAN_TASK_NOTIFIED_MARKER)
1750
1833
  return;
1751
1834
  // The REQUEST is raised whether or not the task names an assignee. An unassigned human step
@@ -1757,7 +1840,7 @@ export class TaskGraphDispatcher {
1757
1840
  // has no owning agent — which can never succeed — was re-attempted on every poll forever,
1758
1841
  // each pass re-reading the graph, until the process was OOM-killed. The marker exists to
1759
1842
  // prevent exactly that storm; a permanent failure has to set it.
1760
- const raised = await this.raiseHumanRequest(task, provider);
1843
+ const raised = await this.raiseHumanRequest(task, provider, preloadedParent);
1761
1844
  if (raised === 'transient-failure')
1762
1845
  return; // try again next poll
1763
1846
  if (raised === 'permanent-failure') {
@@ -1969,18 +2052,26 @@ export class TaskGraphDispatcher {
1969
2052
  * complete" as a query is possible but would be a second, independently-maintained definition of
1970
2053
  * the same rule, free to drift from the one the in-run executor uses.
1971
2054
  */
1972
- async findClaimableTasks(provider, limit) {
2055
+ async findClaimableTasks(provider, limit, preloadedGraphs) {
1973
2056
  const claimable = [];
1974
2057
  const stats = new Map();
1975
- const activeGraphs = await this.findActiveGraphIDs(provider);
1976
- // Usually a no-op — propagateAndRollup primed these earlier in the same pass.
1977
- await this.primeDebugStates(provider, activeGraphs);
1978
- for (const parentID of activeGraphs) {
2058
+ const graphSources = preloadedGraphs
2059
+ ? preloadedGraphs
2060
+ .map((g) => ({ parentID: g.parentTaskID ?? g.parent?.ID ?? '', preloaded: g }))
2061
+ .filter((entry) => entry.parentID.length > 0)
2062
+ : await (async () => {
2063
+ const activeGraphs = await this.findActiveGraphIDs(provider);
2064
+ // Usually a no-op — propagateAndRollup primed these earlier in the same pass.
2065
+ await this.primeDebugStates(provider, activeGraphs);
2066
+ return activeGraphs.map((parentID) => ({ parentID }));
2067
+ })();
2068
+ for (const source of graphSources) {
1979
2069
  if (claimable.length >= limit)
1980
2070
  break;
2071
+ const { parentID } = source;
1981
2072
  const debug = await this.readDebugState(provider, parentID);
1982
2073
  await this.announcePauseTransition(provider, parentID, debug);
1983
- const graph = await this.loadGraphState(provider, parentID, debug);
2074
+ const graph = source.preloaded ?? await this.loadGraphState(provider, parentID, debug);
1984
2075
  // HOLD is what makes "a broken condition stalls visibly" true rather than merely stated.
1985
2076
  // An undecided exclusive group keeps all its edges, and a kept edge on a Complete origin
1986
2077
  // is a SATISFIED prerequisite — so without this filter every branch of the fork would be
@@ -2109,12 +2200,21 @@ export class TaskGraphDispatcher {
2109
2200
  `assignment and is not a human step — nothing can execute it. The graph will stall.`);
2110
2201
  continue;
2111
2202
  }
2112
- await this.notifyHumanTaskReady(entity, provider);
2203
+ await this.notifyHumanTaskReady(entity, provider, graph.parent);
2113
2204
  continue;
2114
2205
  }
2115
2206
  if (this.inFlight.has(entity.ID))
2116
2207
  continue;
2117
- claimable.push(entity);
2208
+ claimable.push({
2209
+ ID: entity.ID,
2210
+ taskId: entity.ID,
2211
+ ParentID: entity.ParentID,
2212
+ Name: entity.Name,
2213
+ taskEntity: entity,
2214
+ parentTask: graph.parent ?? null,
2215
+ parentMetadata: graph.parentMetadata,
2216
+ dependencyOutputs: this.extractDependencyOutputsFromGraph(entity.ID, graph),
2217
+ });
2118
2218
  if (claimable.length >= limit)
2119
2219
  break;
2120
2220
  }
@@ -2229,7 +2329,7 @@ export class TaskGraphDispatcher {
2229
2329
  * submitted it, so nothing is suspended — the task sits Pending, every other branch keeps
2230
2330
  * running, and answering settles the task. That column staying null is meaningful, not missing.
2231
2331
  */
2232
- async raiseHumanRequest(task, provider) {
2332
+ async raiseHumanRequest(task, provider, preloadedParent) {
2233
2333
  try {
2234
2334
  const existing = await this.findOpenRequests(provider, task.ID);
2235
2335
  if (existing.length > 0) {
@@ -2244,7 +2344,7 @@ export class TaskGraphDispatcher {
2244
2344
  // A human task has NO AgentID of its own — that column names what EXECUTES a step, and
2245
2345
  // a person is not an agent. The request still needs one, so it carries the agent that
2246
2346
  // owns the workflow: the graph's own agent, which is who is asking.
2247
- const owningAgentID = await this.owningAgentOf(provider, task);
2347
+ const owningAgentID = await this.owningAgentOf(provider, task, preloadedParent);
2248
2348
  if (!owningAgentID) {
2249
2349
  // PERMANENT: a graph with no owning agent will not acquire one by being asked
2250
2350
  // again. Graphs submitted before the provenance stamp landed are all in this state.
@@ -2259,7 +2359,7 @@ export class TaskGraphDispatcher {
2259
2359
  request.Status = 'Requested';
2260
2360
  request.Request = task.Description || `A workflow is waiting on you to complete "${task.Name}".`;
2261
2361
  // The graph's own run is the provenance a reader follows back to see what led here.
2262
- request.OriginatingAgentRunID = await this.submittingRunOf(provider, task);
2362
+ request.OriginatingAgentRunID = await this.submittingRunOf(provider, task, preloadedParent);
2263
2363
  // The deadline, when the author set one. `expireOverdueRequests` has always been able to
2264
2364
  // enforce this — it expires the request and fails the step so a give-up edge can route
2265
2365
  // around it — but nothing ever WROTE the column, so that whole path had never run outside
@@ -2308,15 +2408,19 @@ export class TaskGraphDispatcher {
2308
2408
  * Reads the graph's parent row, falling back to the run that submitted it. A human step has no
2309
2409
  * agent of its own by design: `AgentID` names what EXECUTES a step, and a person is not an agent.
2310
2410
  */
2311
- async owningAgentOf(provider, task) {
2411
+ async owningAgentOf(provider, task, preloadedParent) {
2312
2412
  if (task.AgentID)
2313
2413
  return task.AgentID;
2314
2414
  if (!task.ParentID)
2315
2415
  return null;
2316
2416
  try {
2317
- const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
2318
- if (!(await parent.Load(task.ParentID)))
2319
- return null;
2417
+ let parent = preloadedParent ?? null;
2418
+ if (!parent) {
2419
+ const candidate = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
2420
+ if (!(await candidate.Load(task.ParentID)))
2421
+ return null;
2422
+ parent = candidate;
2423
+ }
2320
2424
  if (parent.AgentID)
2321
2425
  return parent.AgentID;
2322
2426
  if (!parent.AgentRunID)
@@ -2360,16 +2464,24 @@ export class TaskGraphDispatcher {
2360
2464
  * request's own ResponseSchema. A step that only recorded "approved" would force every decision
2361
2465
  * back into a separate action.
2362
2466
  */
2363
- async settleAnsweredHumanTasks(provider, graphID) {
2364
- const waiting = await RunView.FromMetadataProvider(provider).RunView({
2365
- EntityName: 'MJ: Tasks',
2366
- ExtraFilter: `ParentID='${graphID}' AND ${HumanTaskSQL()} AND Status='Pending'`,
2367
- ResultType: 'entity_object',
2368
- BypassCache: true,
2369
- }, this.contextUser);
2370
- if (!waiting.Success)
2371
- return;
2372
- for (const task of waiting.Results ?? []) {
2467
+ async settleAnsweredHumanTasks(provider, graphID, pendingHumanTasks) {
2468
+ let tasksToInspect;
2469
+ if (pendingHumanTasks) {
2470
+ tasksToInspect = pendingHumanTasks.filter((t) => t.Status === 'Pending');
2471
+ }
2472
+ else {
2473
+ const waiting = await RunView.FromMetadataProvider(provider).RunView({
2474
+ EntityName: 'MJ: Tasks',
2475
+ ExtraFilter: `ParentID='${graphID}' AND ${HumanTaskSQL()} AND Status='Pending'`,
2476
+ ResultType: 'entity_object',
2477
+ BypassCache: true,
2478
+ }, this.contextUser);
2479
+ if (!waiting.Success)
2480
+ return 0;
2481
+ tasksToInspect = waiting.Results ?? [];
2482
+ }
2483
+ let settledCount = 0;
2484
+ for (const task of tasksToInspect) {
2373
2485
  const request = await this.answeredRequestFor(provider, task.ID);
2374
2486
  if (!request)
2375
2487
  continue;
@@ -2395,6 +2507,7 @@ export class TaskGraphDispatcher {
2395
2507
  `${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
2396
2508
  continue;
2397
2509
  }
2510
+ settledCount++;
2398
2511
  // WITHDRAW EVERY OTHER OPEN ASK FOR THIS STEP (R3-5).
2399
2512
  //
2400
2513
  // The step is terminal now, so both human sweeps — which scope to `Pending` tasks — will
@@ -2404,6 +2517,7 @@ export class TaskGraphDispatcher {
2404
2517
  // retroactively cleans the ones already minted, which the raise-side fix cannot reach.
2405
2518
  await this.withdrawOpenRequests(provider, [task.ID], 'This step has been settled; the request is no longer open.');
2406
2519
  }
2520
+ return settledCount;
2407
2521
  }
2408
2522
  /**
2409
2523
  * Reconciles the requests behind human steps that are waiting on somebody.
@@ -2426,25 +2540,32 @@ export class TaskGraphDispatcher {
2426
2540
  * and raises a fresh request, which is exactly the replacement the design assumed. Bounded by
2427
2541
  * human action: it takes another person cancelling again to come back here.
2428
2542
  */
2429
- async reconcileWaitingHumanTasks(provider, graphID) {
2430
- const waiting = await RunView.FromMetadataProvider(provider).RunView({
2431
- EntityName: 'MJ: Tasks',
2432
- // `StepType` is NULLABLE, and rows predating the column exist (4 in the reference
2433
- // database at the time of writing). None currently carry a UserID, but a human task
2434
- // written by any path that set the assignee without the discriminator would be
2435
- // invisible to a `StepType='Human'` filter and stay dead forever after a cancel —
2436
- // the exact stall this method exists to end. The notified marker already narrows
2437
- // this to tasks the dispatcher raised a request for, so the widening cannot pull in
2438
- // unrelated work.
2439
- ExtraFilter: `ParentID='${graphID}' AND Status='Pending' ` +
2440
- `AND ${HumanTaskSQL()} ` +
2441
- `AND ClaimedBy='${HUMAN_TASK_NOTIFIED_MARKER}'`,
2442
- ResultType: 'entity_object',
2443
- BypassCache: true,
2444
- }, this.contextUser);
2445
- if (!waiting.Success)
2446
- return;
2447
- for (const task of waiting.Results ?? []) {
2543
+ async reconcileWaitingHumanTasks(provider, graphID, pendingHumanTasks) {
2544
+ let tasksToInspect;
2545
+ if (pendingHumanTasks) {
2546
+ tasksToInspect = pendingHumanTasks.filter((t) => t.Status === 'Pending' && t.ClaimedBy === HUMAN_TASK_NOTIFIED_MARKER);
2547
+ }
2548
+ else {
2549
+ const waiting = await RunView.FromMetadataProvider(provider).RunView({
2550
+ EntityName: 'MJ: Tasks',
2551
+ // `StepType` is NULLABLE, and rows predating the column exist (4 in the reference
2552
+ // database at the time of writing). None currently carry a UserID, but a human task
2553
+ // written by any path that set the assignee without the discriminator would be
2554
+ // invisible to a `StepType='Human'` filter and stay dead forever after a cancel —
2555
+ // the exact stall this method exists to end. The notified marker already narrows
2556
+ // this to tasks the dispatcher raised a request for, so the widening cannot pull in
2557
+ // unrelated work.
2558
+ ExtraFilter: `ParentID='${graphID}' AND Status='Pending' ` +
2559
+ `AND ${HumanTaskSQL()} ` +
2560
+ `AND ClaimedBy='${HUMAN_TASK_NOTIFIED_MARKER}'`,
2561
+ ResultType: 'entity_object',
2562
+ BypassCache: true,
2563
+ }, this.contextUser);
2564
+ if (!waiting.Success)
2565
+ return;
2566
+ tasksToInspect = waiting.Results ?? [];
2567
+ }
2568
+ for (const task of tasksToInspect) {
2448
2569
  // Only when there is nothing live AND nothing terminal. A task with an open request is
2449
2570
  // simply waiting; one with a terminal request is settled on the next pass by
2450
2571
  // settleAnsweredHumanTasks, and re-raising either would ask the same question twice.
@@ -2486,16 +2607,22 @@ export class TaskGraphDispatcher {
2486
2607
  * A deadline that nothing enforces is a comment. Without this an `ExpiresAt` in the past leaves
2487
2608
  * the request `Requested` forever and the workflow waiting on it just as long.
2488
2609
  */
2489
- async expireOverdueRequests(provider, graphID) {
2490
- // Scoped by an explicit id list rather than a subquery against a view name, so this reads
2491
- // the same on any provider rather than assuming a SQL dialect and a physical view.
2492
- const humanTasks = await RunView.FromMetadataProvider(provider).RunView({
2493
- EntityName: 'MJ: Tasks',
2494
- Fields: ['ID'],
2495
- ExtraFilter: `ParentID='${graphID}' AND ${HumanTaskSQL()} AND Status='Pending'`,
2496
- ResultType: 'simple',
2497
- }, this.contextUser);
2498
- const ids = (humanTasks.Results ?? []).map((r) => `'${r.ID}'`);
2610
+ async expireOverdueRequests(provider, graphID, pendingHumanTasks) {
2611
+ let ids;
2612
+ if (pendingHumanTasks) {
2613
+ ids = pendingHumanTasks.filter((t) => t.Status === 'Pending').map((r) => `'${r.ID}'`);
2614
+ }
2615
+ else {
2616
+ // Scoped by an explicit id list rather than a subquery against a view name, so this reads
2617
+ // the same on any provider rather than assuming a SQL dialect and a physical view.
2618
+ const humanTasks = await RunView.FromMetadataProvider(provider).RunView({
2619
+ EntityName: 'MJ: Tasks',
2620
+ Fields: ['ID'],
2621
+ ExtraFilter: `ParentID='${graphID}' AND ${HumanTaskSQL()} AND Status='Pending'`,
2622
+ ResultType: 'simple',
2623
+ }, this.contextUser);
2624
+ ids = (humanTasks.Results ?? []).map((r) => `'${r.ID}'`);
2625
+ }
2499
2626
  if (ids.length === 0)
2500
2627
  return;
2501
2628
  const nowISO = new Date().toISOString();
@@ -2516,9 +2643,11 @@ export class TaskGraphDispatcher {
2516
2643
  }
2517
2644
  }
2518
2645
  /** The agent run that submitted this task's graph, for provenance on the request. */
2519
- async submittingRunOf(provider, task) {
2646
+ async submittingRunOf(provider, task, preloadedParent) {
2520
2647
  if (!task.ParentID)
2521
2648
  return null;
2649
+ if (preloadedParent)
2650
+ return preloadedParent.AgentRunID;
2522
2651
  try {
2523
2652
  const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
2524
2653
  return (await parent.Load(task.ParentID)) ? parent.AgentRunID : null;
@@ -2528,7 +2657,7 @@ export class TaskGraphDispatcher {
2528
2657
  }
2529
2658
  }
2530
2659
  /** Loads a graph's children and edges in the shapes both the algorithms and mutation need. */
2531
- async loadGraphState(provider, parentTaskID, debug) {
2660
+ async loadGraphState(provider, parentTaskID, debug, preloadedParent) {
2532
2661
  const rv = RunView.FromMetadataProvider(provider);
2533
2662
  // BypassCache throughout: task status is written by the claim protocol's direct SQL, which
2534
2663
  // fires no cache invalidation. See findActiveGraphIDs.
@@ -2536,7 +2665,11 @@ export class TaskGraphDispatcher {
2536
2665
  const children = (childrenResult.Success ? childrenResult.Results : []) ?? [];
2537
2666
  if (children.length === 0) {
2538
2667
  return {
2668
+ parentTaskID,
2669
+ parent: preloadedParent ?? null,
2670
+ parentMetadata: ParseTaskGraphParentMetadata(preloadedParent?.InputPayload ?? null),
2539
2671
  nodes: [], edges: [], entityById: new Map(),
2672
+ rawDependencies: [],
2540
2673
  unreachableTaskIDs: new Set(), cascadeSkipTaskIDs: new Set(),
2541
2674
  skipSeedTaskIDs: new Set(), holdTaskIDs: new Set(),
2542
2675
  handledFailureIDs: new Set(),
@@ -2546,12 +2679,21 @@ export class TaskGraphDispatcher {
2546
2679
  const depsResult = await rv.RunView({ EntityName: 'MJ: Task Dependencies', ExtraFilter: `TaskID IN (${idList})`, ResultType: 'entity_object', BypassCache: true }, this.contextUser);
2547
2680
  const deps = (depsResult.Success ? depsResult.Results : []) ?? [];
2548
2681
  const entityById = new Map(children.map((c) => [c.ID, c]));
2549
- // Read ONCE, and only when it can change an answer (R2-4). Both consumers below — which
2550
- // origin statuses may decide an exclusive group, and which failures count as handled — are
2551
- // no-ops unless something has actually failed, and this runs on every poll for every active
2552
- // graph, so the parent load stays behind the same cheap exit `computeHandledFailures` used.
2553
- // One parent read serves both questions this pass asks of the metadata bag.
2554
- const parentMeta = await this.readParentMetadataFor(provider, parentTaskID);
2682
+ // Read ONCE, and retained on `GraphState` so parent rollup, continuation, human request
2683
+ // provenance, and claimed-task execution all reuse the same loaded parent entity and
2684
+ // parsed metadata without re-querying `MJ: Tasks`.
2685
+ const parent = preloadedParent !== undefined
2686
+ ? preloadedParent
2687
+ : await this.loadParentTask(provider, parentTaskID);
2688
+ const parentMeta = parent
2689
+ ? ParseTaskGraphParentMetadata(parent.InputPayload)
2690
+ : ParseTaskGraphParentMetadata(null);
2691
+ const effectiveDebug = debug
2692
+ ?? this.debugStateByGraph?.get(parentTaskID)
2693
+ ?? ParseTaskGraphDebugState(parent?.InputPayload ?? null);
2694
+ if (!this.debugStateByGraph?.has(parentTaskID)) {
2695
+ this.debugStateByGraph?.set(parentTaskID, effectiveDebug);
2696
+ }
2555
2697
  const failureSemantics = parentMeta.failureSemantics;
2556
2698
  // The invocation's own parameters, carried on the parent so a condition evaluated by any
2557
2699
  // instance sees what the walker saw (R3-3).
@@ -2610,7 +2752,7 @@ export class TaskGraphDispatcher {
2610
2752
  originStatus: (entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending'),
2611
2753
  priority: d.Priority ?? 0,
2612
2754
  sequence: d.Sequence ?? 0,
2613
- conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, decisions, debug, exclusiveHoldReasons),
2755
+ conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, decisions, effectiveDebug, exclusiveHoldReasons),
2614
2756
  })), (edge) => ReadsFailedDecision(conditionByEdge.get(edge.id) ?? '', failedDecisions)),
2615
2757
  // WHICH STATUSES MAY DECIDE — the graph's own failure dialect, not a constant.
2616
2758
  //
@@ -2635,8 +2777,9 @@ export class TaskGraphDispatcher {
2635
2777
  // change-only, so a viewer learns WHY a branch ran (or is held) the moment it is decided.
2636
2778
  const gateDecisions = [];
2637
2779
  for (const d of ordinary) {
2638
- if (d.Condition?.trim()) {
2639
- const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, decisions, debug);
2780
+ const cond = d.Condition?.trim();
2781
+ if (cond && cond.toLowerCase() !== 'true' && cond !== '1 === 1' && cond !== '1 == 1') {
2782
+ const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, decisions, effectiveDebug);
2640
2783
  if (decision.decided) {
2641
2784
  gateDecisions.push({
2642
2785
  edge: d,
@@ -2650,8 +2793,8 @@ export class TaskGraphDispatcher {
2650
2793
  }
2651
2794
  if (decision.outcome === 'hold')
2652
2795
  heldByCondition.add(d.TaskID);
2796
+ stillReachable.add(d.TaskID);
2653
2797
  }
2654
- stillReachable.add(d.TaskID);
2655
2798
  liveEdges.push({
2656
2799
  taskId: d.TaskID,
2657
2800
  dependsOnTaskId: d.DependsOnTaskID,
@@ -2699,7 +2842,7 @@ export class TaskGraphDispatcher {
2699
2842
  const exclusiveHolds = new Set(resolution.holdTaskIDs);
2700
2843
  for (const d of exclusive) {
2701
2844
  const originStatus = entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending';
2702
- if (!decidingStatuses.has(originStatus) && !OverrideVerdictFor(debug ?? {}, d.ID))
2845
+ if (!decidingStatuses.has(originStatus) && !OverrideVerdictFor(effectiveDebug, d.ID))
2703
2846
  continue;
2704
2847
  const held = !loserEdgeIDs.has(d.ID) && exclusiveHolds.has(d.TaskID);
2705
2848
  // The edge that holds its fork says why — below its confidence, from a failed call — and
@@ -2748,9 +2891,13 @@ export class TaskGraphDispatcher {
2748
2891
  }
2749
2892
  }
2750
2893
  return {
2894
+ parentTaskID,
2895
+ parent,
2896
+ parentMetadata: parentMeta,
2751
2897
  nodes,
2752
2898
  edges: liveEdges,
2753
2899
  entityById,
2900
+ rawDependencies: deps,
2754
2901
  unreachableTaskIDs,
2755
2902
  cascadeSkipTaskIDs,
2756
2903
  skipSeedTaskIDs: confirmedSkipSeeds,
@@ -2922,6 +3069,29 @@ export class TaskGraphDispatcher {
2922
3069
  }
2923
3070
  }).catch(() => { });
2924
3071
  }
3072
+ /**
3073
+ * Extracts parsed `OutputPayload` values for all dependencies of `taskID` directly from the
3074
+ * already-loaded `GraphState`, avoiding any additional database round-trips when claiming and
3075
+ * executing a task.
3076
+ */
3077
+ extractDependencyOutputsFromGraph(taskID, graph) {
3078
+ const outputs = new Map();
3079
+ const deps = graph.rawDependencies ?? [];
3080
+ for (const dep of deps) {
3081
+ if (!UUIDsEqual(dep.TaskID, taskID))
3082
+ continue;
3083
+ const upstream = graph.entityById.get(dep.DependsOnTaskID);
3084
+ if (!upstream?.OutputPayload)
3085
+ continue;
3086
+ try {
3087
+ outputs.set(dep.DependsOnTaskID, JSON.parse(upstream.OutputPayload));
3088
+ }
3089
+ catch (e) {
3090
+ LogError(`[TaskGraphDispatcher] Task ${dep.DependsOnTaskID} has malformed OutputPayload: ${e}`);
3091
+ }
3092
+ }
3093
+ return outputs;
3094
+ }
2925
3095
  /** Parsed `OutputPayload` of each completed dependency, keyed by that task's ID. */
2926
3096
  async loadDependencyOutputs(provider, taskID) {
2927
3097
  const outputs = new Map();
@@ -2955,7 +3125,7 @@ export class TaskGraphDispatcher {
2955
3125
  * Every branch is normalized to one shape so the recording path above stays single: an action has
2956
3126
  * no agent run to point at, because its forensics live in `ActionExecutionLog` instead.
2957
3127
  */
2958
- async runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress) {
3128
+ async runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress, prehydrated) {
2959
3129
  // A node's input is a name → value object (`TaskGraphSpecNode.inputPayload: Record<string, unknown>`).
2960
3130
  // `mergedPayload` below only merges objects, so anything else would be dropped without a word
2961
3131
  // and the step would run with none of its inputs — how durable entity actions ran before MJ#4794
@@ -2976,18 +3146,19 @@ export class TaskGraphDispatcher {
2976
3146
  // A loop's own step type decides how many times its body runs; the body itself is dispatched
2977
3147
  // through the very same runners as a one-shot step.
2978
3148
  if (task.StepType === 'ForEach' || task.StepType === 'While') {
2979
- return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs), PayloadAtStart: payload };
3149
+ return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs, prehydrated), PayloadAtStart: payload };
2980
3150
  }
2981
3151
  // Routed on StepType before the mappings below: a Decision reads its state from the merged
2982
3152
  // payload by path and writes its answers back under `decisions`, so it has no mapping of its
2983
3153
  // own. And it carries a PromptID, so the Prompt branch would otherwise take it.
2984
3154
  if (task.StepType === 'Decision') {
2985
- return { ...await this.runDecisionNode(task, provider, payload, onProgress), PayloadAtStart: payload };
3155
+ return { ...await this.runDecisionNode(task, provider, payload, onProgress, prehydrated), PayloadAtStart: payload };
2986
3156
  }
2987
3157
  // `data.*` / `context.*` resolve against the invocation that submitted the graph, exactly as
2988
3158
  // the in-run walker resolves them and as branch conditions already see them (R3-3). Without
2989
3159
  // it a mapping like `RecordID: data.ID` reached the action as the literal "data.ID".
2990
- const invocation = config?.inputMapping ? (await this.graphContext(provider, task)).Invocation : {};
3160
+ const context = await this.graphContext(provider, task, prehydrated);
3161
+ const invocation = config?.inputMapping ? context.Invocation : {};
2991
3162
  const { params, errors } = BuildMappedInput(config?.inputMapping, { payload, ...invocation });
2992
3163
  for (const e of errors)
2993
3164
  LogError(`[TaskGraphDispatcher] Task ${task.ID}: ${e}`);
@@ -3017,7 +3188,7 @@ export class TaskGraphDispatcher {
3017
3188
  DependencyOutputs: dependencyOutputs,
3018
3189
  TemplateParameters: config?.prompt?.templateParameters,
3019
3190
  Provider: provider,
3020
- ContextUser: this.contextUser,
3191
+ ContextUser: context.ExecutionUser,
3021
3192
  OnProgress: onProgress,
3022
3193
  });
3023
3194
  // A prompt's response is DEEP-MERGED into the payload rather than replacing it. A prompt
@@ -3046,10 +3217,10 @@ export class TaskGraphDispatcher {
3046
3217
  InputPayload: effectiveInput,
3047
3218
  DependencyOutputs: dependencyOutputs,
3048
3219
  Provider: provider,
3049
- ContextUser: this.contextUser,
3220
+ ContextUser: context.ExecutionUser,
3050
3221
  OnProgress: onProgress,
3051
3222
  }), AgentRunID: null }
3052
- : await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress);
3223
+ : await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, context);
3053
3224
  return {
3054
3225
  ...raw,
3055
3226
  Output: this.applyStepOutputMapping(task, payload, raw.Output, config?.outputMapping),
@@ -3064,7 +3235,7 @@ export class TaskGraphDispatcher {
3064
3235
  * merged into the payload before the mapping is applied, which is how a body can reference the
3065
3236
  * current item at all.
3066
3237
  */
3067
- async runLoopTask(task, provider, payload, dependencyOutputs) {
3238
+ async runLoopTask(task, provider, payload, dependencyOutputs, prehydrated) {
3068
3239
  const config = task.ConfigurationObject;
3069
3240
  const op = task.StepType === 'ForEach' ? config?.forEach : config?.while;
3070
3241
  if (!op) {
@@ -3092,7 +3263,7 @@ export class TaskGraphDispatcher {
3092
3263
  // cost), and the continuation depth (so the recursion cap still applies). Omitting them made
3093
3264
  // loop bodies second-class in every dimension — and reopened the unbounded-recursion hole
3094
3265
  // THROUGH loops, since each spawned run restarted the chain at zero.
3095
- const graphContext = await this.graphContext(provider, task);
3266
+ const graphContext = await this.graphContext(provider, task, prehydrated);
3096
3267
  // THE LOOP'S PAYLOAD ACCUMULATES. Each iteration's output merges in, and the next iteration
3097
3268
  // — and the While condition — sees it. Without this the condition closure re-read the
3098
3269
  // payload as it was when the loop STARTED, so a `while payload.brandOK !== true` could never
@@ -3180,7 +3351,7 @@ export class TaskGraphDispatcher {
3180
3351
  // confidently about nothing.
3181
3352
  TemplateParameters: { ...stringifyBindings(Bindings), ...op.prompt?.templateParameters },
3182
3353
  Provider: provider,
3183
- ContextUser: this.contextUser,
3354
+ ContextUser: graphContext.ExecutionUser,
3184
3355
  }), iterationPayload);
3185
3356
  }
3186
3357
  if (task.ActionID) {
@@ -3190,7 +3361,7 @@ export class TaskGraphDispatcher {
3190
3361
  InputPayload: resolved,
3191
3362
  DependencyOutputs: dependencyOutputs,
3192
3363
  Provider: provider,
3193
- ContextUser: this.contextUser,
3364
+ ContextUser: graphContext.ExecutionUser,
3194
3365
  }), resolved);
3195
3366
  }
3196
3367
  const agentInput = Object.keys(resolved).length > 0 ? resolved : iterationPayload;
@@ -3205,7 +3376,7 @@ export class TaskGraphDispatcher {
3205
3376
  ContinuationDepth: graphContext.Depth,
3206
3377
  SubmittingAgentRunID: graphContext.SubmittingAgentRunID,
3207
3378
  Provider: provider,
3208
- ContextUser: this.contextUser,
3379
+ ContextUser: graphContext.ExecutionUser,
3209
3380
  }), agentInput);
3210
3381
  };
3211
3382
  const outcome = task.StepType === 'ForEach'
@@ -3321,8 +3492,8 @@ export class TaskGraphDispatcher {
3321
3492
  * Depth and provenance are read together because they come from the same row: the graph's parent
3322
3493
  * task knows both how many continuation hops led here and which run submitted it.
3323
3494
  */
3324
- async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress) {
3325
- const context = await this.graphContext(provider, task);
3495
+ async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, resolvedContext) {
3496
+ const context = resolvedContext ?? await this.graphContext(provider, task);
3326
3497
  return this.agentRunner.RunAgentForTask({
3327
3498
  TaskID: task.ID,
3328
3499
  AgentID: task.AgentID,
@@ -3331,7 +3502,7 @@ export class TaskGraphDispatcher {
3331
3502
  ContinuationDepth: context.Depth,
3332
3503
  SubmittingAgentRunID: context.SubmittingAgentRunID,
3333
3504
  Provider: provider,
3334
- ContextUser: this.contextUser,
3505
+ ContextUser: context.ExecutionUser,
3335
3506
  OnProgress: onProgress,
3336
3507
  });
3337
3508
  }
@@ -3349,7 +3520,7 @@ export class TaskGraphDispatcher {
3349
3520
  * and the call asks only the rest. If that call fails, or cannot be made, the step stays
3350
3521
  * `Complete` with the same usable answers, and the questions it asked again hold with the reason.
3351
3522
  */
3352
- async runDecisionNode(task, provider, payload, onProgress) {
3523
+ async runDecisionNode(task, provider, payload, onProgress, prehydrated) {
3353
3524
  const config = ReadDecisionStepConfiguration(task.Configuration);
3354
3525
  if (!config)
3355
3526
  return this.decisionNotAsked(task, payload, 'it has no decision settings, so there is nothing to ask');
@@ -3366,6 +3537,7 @@ export class TaskGraphDispatcher {
3366
3537
  const conflict = DecisionsPayloadConflict(payload);
3367
3538
  if (conflict)
3368
3539
  return notAsked(conflict);
3540
+ const context = await this.graphContext(provider, task, prehydrated);
3369
3541
  const startedAt = new Date();
3370
3542
  const result = await this.decisionRunner.RunDecisionForTask({
3371
3543
  TaskID: task.ID,
@@ -3373,10 +3545,10 @@ export class TaskGraphDispatcher {
3373
3545
  State: state.State,
3374
3546
  Questions: toAsk,
3375
3547
  Provider: provider,
3376
- ContextUser: this.contextUser,
3548
+ ContextUser: context.ExecutionUser,
3377
3549
  OnProgress: onProgress,
3378
3550
  });
3379
- await this.logDecisionStep(provider, task, config, toAsk, state.State, result, startedAt);
3551
+ await this.logDecisionStep(provider, task, config, toAsk, state.State, result, startedAt, context);
3380
3552
  if (!result.Success || !result.Answers) {
3381
3553
  const message = result.ErrorMessage || `Decision "${task.Name}" returned no answers.`;
3382
3554
  if (Object.keys(kept).length > 0)
@@ -3440,9 +3612,9 @@ export class TaskGraphDispatcher {
3440
3612
  * recorded in its prompt run, which the task points at. Observability only: a failure to log is
3441
3613
  * reported, and the decision stands.
3442
3614
  */
3443
- async logDecisionStep(provider, task, config, asked, state, result, startedAt) {
3615
+ async logDecisionStep(provider, task, config, asked, state, result, startedAt, resolvedContext) {
3444
3616
  try {
3445
- const { SubmittingAgentRunID: agentRunID } = await this.graphContext(provider, task);
3617
+ const { SubmittingAgentRunID: agentRunID } = resolvedContext ?? await this.graphContext(provider, task);
3446
3618
  if (!agentRunID)
3447
3619
  return;
3448
3620
  // The number is read and the step saved as one unit per run, so two Decision steps
@@ -3612,25 +3784,39 @@ export class TaskGraphDispatcher {
3612
3784
  this.retryingSettlement.set(parentID, passes);
3613
3785
  }
3614
3786
  /**
3615
- * A graph's durable metadata bag, for the questions a pass asks of it.
3616
- *
3617
- * Defaults on any failure to read it, and the defaults are the safe directions: `'block'` means
3618
- * a failed step decides nothing, so a graph whose metadata we cannot read stalls visibly instead
3619
- * of resolving forks on the say-so of a failure; and no early-finish declaration means nothing
3620
- * is removed from the claim filter on the strength of a read that did not work.
3787
+ * Loads a graph's parent `MJ: Tasks` row once and caches its owner and debug state when present.
3621
3788
  */
3622
- async readParentMetadataFor(provider, parentTaskID) {
3789
+ async loadParentTask(provider, parentTaskID) {
3623
3790
  try {
3624
3791
  const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
3625
- if (await parent.Load(parentTaskID))
3626
- return ParseTaskGraphParentMetadata(parent.InputPayload);
3792
+ if (await parent.Load(parentTaskID)) {
3793
+ const meta = ParseTaskGraphParentMetadata(parent.InputPayload);
3794
+ const owner = meta.submittedByUserID ?? parent.UserID ?? null;
3795
+ this.ownerByParentID?.set(parentTaskID, owner);
3796
+ if (!this.debugStateByGraph?.has(parentTaskID)) {
3797
+ this.debugStateByGraph?.set(parentTaskID, ParseTaskGraphDebugState(parent.InputPayload));
3798
+ }
3799
+ return parent;
3800
+ }
3627
3801
  LogError(`[TaskGraphDispatcher] Parent task ${parentTaskID} could not be loaded; using default graph metadata (no invocation data/context).`);
3628
3802
  }
3629
3803
  catch (e) {
3630
3804
  // Safe defaults still apply — but say so: a missing invocation turns every `data.*` mapping literal.
3631
3805
  LogError(`[TaskGraphDispatcher] Reading parent task ${parentTaskID} failed; using default graph metadata: ${e instanceof Error ? e.message : String(e)}`);
3632
3806
  }
3633
- return ParseTaskGraphParentMetadata(null);
3807
+ return null;
3808
+ }
3809
+ /**
3810
+ * A graph's durable metadata bag, for the questions a pass asks of it.
3811
+ *
3812
+ * Defaults on any failure to read it, and the defaults are the safe directions: `'block'` means
3813
+ * a failed step decides nothing, so a graph whose metadata we cannot read stalls visibly instead
3814
+ * of resolving forks on the say-so of a failure; and no early-finish declaration means nothing
3815
+ * is removed from the claim filter on the strength of a read that did not work.
3816
+ */
3817
+ async readParentMetadataFor(provider, parentTaskID) {
3818
+ const parent = await this.loadParentTask(provider, parentTaskID);
3819
+ return parent ? ParseTaskGraphParentMetadata(parent.InputPayload) : ParseTaskGraphParentMetadata(null);
3634
3820
  }
3635
3821
  /**
3636
3822
  * Whether the submitting run is in a state where this pass's writes to it will mean anything.
@@ -3670,7 +3856,7 @@ export class TaskGraphDispatcher {
3670
3856
  // own bookkeeping is owed either way — but announcing it would message a conversation
3671
3857
  // about a workflow the user stopped, and for `reinvoke` would start a fresh billed turn
3672
3858
  // for the agent they cancelled.
3673
- const cancelled = run.Status === 'Cancelled';
3859
+ let cancelled = run.Status === 'Cancelled';
3674
3860
  const settledFor = parent.CompletedAt ? Date.now() - parent.CompletedAt.getTime() : 0;
3675
3861
  if (!IsSubmittingRunReady(run.Status, settledFor)) {
3676
3862
  // Still `Running` and inside the grace: `finalizeAgentRun` has not parked it yet.
@@ -3685,6 +3871,24 @@ export class TaskGraphDispatcher {
3685
3871
  `since graph ${parent.ID} settled — it never parked, so its submitting process most ` +
3686
3872
  `likely died. Settling and delivering the graph anyway; the run needs separate attention.`);
3687
3873
  }
3874
+ // When a sub-agent submitted the graph on behalf of a parent run, check that any
3875
+ // ancestor runs in the ParentRunID chain have also parked before settling.
3876
+ let currentParentRunID = run.ParentRunID;
3877
+ const visitedReadinessIDs = new Set([(run.ID || meta.submittedByAgentRunID).toLowerCase()]);
3878
+ while (currentParentRunID && !visitedReadinessIDs.has(currentParentRunID.toLowerCase()) && visitedReadinessIDs.size < 10) {
3879
+ visitedReadinessIDs.add(currentParentRunID.toLowerCase());
3880
+ const ancestorRun = await provider.GetEntityObject('MJ: AI Agent Runs', this.contextUser);
3881
+ if (!(await ancestorRun.Load(currentParentRunID))) {
3882
+ break;
3883
+ }
3884
+ if (ancestorRun.Status === 'Cancelled') {
3885
+ cancelled = true;
3886
+ }
3887
+ if (!IsSubmittingRunReady(ancestorRun.Status, settledFor)) {
3888
+ return { Verdict: 'defer', SubmitterCancelled: cancelled };
3889
+ }
3890
+ currentParentRunID = ancestorRun.ParentRunID;
3891
+ }
3688
3892
  return { Verdict: 'ready', SubmitterCancelled: cancelled };
3689
3893
  }
3690
3894
  catch (e) {
@@ -3724,30 +3928,42 @@ export class TaskGraphDispatcher {
3724
3928
  LogError(`[TaskGraphDispatcher] Could not load run ${meta.submittedByAgentRunID} to settle it against graph ${parent.ID}.`);
3725
3929
  return 'defer';
3726
3930
  }
3727
- if (run.Status !== 'Paused')
3728
- return 'done';
3729
- // The workflow's outcome becomes the run's outcome. A graph that ended any way other than
3730
- // Complete did not do what the run started it to do, and a run reporting success over it
3731
- // would be the same untruth in a different place.
3732
3931
  const succeeded = graphStatus === 'Complete';
3733
- // COLUMN-SCOPED AND GUARDED ON `Paused` (C4), for the same reason every parent write has
3734
- // been since Round 1: a full-row save carries a stale snapshot of a row another instance
3735
- // may have moved, and the predicate makes the transition once-only rather than
3736
- // last-write-wins.
3737
- const settled = await this.claims.TrySettleRun(provider, run.ID, succeeded, succeeded ? null : `The workflow "${parent.Name}" ended ${graphStatus}.`, this.contextUser);
3738
- if (!settled) {
3739
- // Left parked rather than forced. A run stuck at Paused is visibly unfinished, which
3740
- // is a state someone can investigate; a run flipped to Completed by a write that did
3741
- // not land would be the same lie this whole change removes.
3742
- // Rowcount 0 is either "a peer settled it first" — fine, and the status read above
3743
- // would have caught the common case — or a write that did not land. Deferring covers
3744
- // both: a peer's settle makes the next pass's `Paused` check return `done`.
3745
- LogError(`[TaskGraphDispatcher] Could not settle run ${run.ID} against graph ${parent.ID}; ` +
3746
- `it is no longer Paused or the write did not land. Retrying next pass.`);
3747
- return 'defer';
3932
+ const failureMessage = succeeded ? null : `The workflow "${parent.Name}" ended ${graphStatus}.`;
3933
+ if (run.Status === 'Paused') {
3934
+ // COLUMN-SCOPED AND GUARDED ON `Paused` (C4), for the same reason every parent write has
3935
+ // been since Round 1: a full-row save carries a stale snapshot of a row another instance
3936
+ // may have moved, and the predicate makes the transition once-only rather than
3937
+ // last-write-wins.
3938
+ const settled = await this.claims.TrySettleRun(provider, run.ID, succeeded, failureMessage, this.contextUser);
3939
+ if (!settled) {
3940
+ LogError(`[TaskGraphDispatcher] Could not settle run ${run.ID} against graph ${parent.ID}; ` +
3941
+ `it is no longer Paused or the write did not land. Retrying next pass.`);
3942
+ return 'defer';
3943
+ }
3944
+ LogStatus(`[TaskGraphDispatcher] Run ${run.ID} settled ${succeeded ? 'Completed' : 'Failed'} — ` +
3945
+ `workflow "${parent.Name}" ended ${graphStatus}.`);
3946
+ }
3947
+ // When a sub-agent (e.g. Workflow Planner) submitted the graph on behalf of a parent
3948
+ // conversation agent (e.g. Sage), BaseAgent parks the parent run as `Paused` as well.
3949
+ // Walk up `ParentRunID` and settle any ancestor runs parked in `Paused`.
3950
+ let currentParentRunID = run.ParentRunID;
3951
+ const visitedSettleIDs = new Set([(run.ID || meta.submittedByAgentRunID).toLowerCase()]);
3952
+ while (currentParentRunID && !visitedSettleIDs.has(currentParentRunID.toLowerCase()) && visitedSettleIDs.size < 10) {
3953
+ visitedSettleIDs.add(currentParentRunID.toLowerCase());
3954
+ const ancestorRun = await provider.GetEntityObject('MJ: AI Agent Runs', this.contextUser);
3955
+ if (!(await ancestorRun.Load(currentParentRunID))) {
3956
+ break;
3957
+ }
3958
+ if (ancestorRun.Status === 'Paused') {
3959
+ const ancestorSettled = await this.claims.TrySettleRun(provider, ancestorRun.ID, succeeded, failureMessage, this.contextUser);
3960
+ if (ancestorSettled) {
3961
+ LogStatus(`[TaskGraphDispatcher] Ancestor run ${ancestorRun.ID} settled ${succeeded ? 'Completed' : 'Failed'} — ` +
3962
+ `workflow "${parent.Name}" ended ${graphStatus}.`);
3963
+ }
3964
+ }
3965
+ currentParentRunID = ancestorRun.ParentRunID;
3748
3966
  }
3749
- LogStatus(`[TaskGraphDispatcher] Run ${run.ID} settled ${succeeded ? 'Completed' : 'Failed'} — ` +
3750
- `workflow "${parent.Name}" ended ${graphStatus}.`);
3751
3967
  return 'done';
3752
3968
  }
3753
3969
  catch (e) {
@@ -3784,6 +4000,7 @@ export class TaskGraphDispatcher {
3784
4000
  // nodes as though the rest of the workflow did not exist.
3785
4001
  const edges = graph.edges.map((e) => ({ From: e.dependsOnTaskId, To: e.taskId }));
3786
4002
  const positions = LayoutGraphNodes([...graph.entityById.keys()], edges, { Direction: 'LR' });
4003
+ const tasksToSave = [];
3787
4004
  for (const task of needsLayout) {
3788
4005
  const position = positions.get(task.ID);
3789
4006
  if (!position)
@@ -3794,10 +4011,13 @@ export class TaskGraphDispatcher {
3794
4011
  layout: { x: position.X, y: position.Y },
3795
4012
  };
3796
4013
  task.Configuration = JSON.stringify(merged);
4014
+ tasksToSave.push(task);
4015
+ }
4016
+ await Promise.all(tasksToSave.map(async (task) => {
3797
4017
  if (!(await task.Save())) {
3798
4018
  LogError(`[TaskGraphDispatcher] Could not save computed layout for ${task.ID}: ${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
3799
4019
  }
3800
- }
4020
+ }));
3801
4021
  }
3802
4022
  catch (e) {
3803
4023
  LogError(`[TaskGraphDispatcher] Could not compute a layout for the settled graph: ${e instanceof Error ? e.message : String(e)}`);
@@ -3897,9 +4117,162 @@ export class TaskGraphDispatcher {
3897
4117
  }
3898
4118
  }
3899
4119
  if (inputPayload) {
3900
- Object.assign(merged, inputPayload);
4120
+ const upstreamSnapshot = { ...merged };
4121
+ const resolvedInput = this.resolveInputValue(inputPayload, upstreamSnapshot, true);
4122
+ return { ...merged, ...resolvedInput };
3901
4123
  }
3902
4124
  return merged;
3903
4125
  }
4126
+ /**
4127
+ * Resolves LLM-authored template references (such as `{{output.task3.handle}}`, `{{output.summary}}`,
4128
+ * or `@task1.output.rows`) inside `inputPayload` against the merged upstream dependency outputs so
4129
+ * literal placeholder strings do not clobber real upstream values.
4130
+ */
4131
+ resolveInputValue(val, upstream, isRootObject = false, topLevelKey) {
4132
+ if (typeof val === 'string') {
4133
+ const singleMustache = val.match(/^\s*\{\{\s*([^{}]+?)\s*\}\}\s*$/);
4134
+ const singleAtRef = val.match(/^\s*@([a-zA-Z0-9_-]+\.(?:output|payload)(?:\..+?)?)\s*$/i);
4135
+ if (singleMustache || singleAtRef) {
4136
+ const expr = singleMustache ? singleMustache[1] : singleAtRef[1];
4137
+ if (this.isWholeUpstreamReference(expr, upstream)) {
4138
+ if (topLevelKey) {
4139
+ const existing = this.lookupCaseInsensitive(upstream, topLevelKey);
4140
+ if (existing !== undefined) {
4141
+ return existing;
4142
+ }
4143
+ }
4144
+ return { ...upstream };
4145
+ }
4146
+ const resolved = this.resolveUpstreamPath(expr, upstream);
4147
+ if (resolved !== undefined) {
4148
+ return resolved;
4149
+ }
4150
+ if (topLevelKey) {
4151
+ const existing = this.lookupCaseInsensitive(upstream, topLevelKey);
4152
+ if (existing !== undefined) {
4153
+ return existing;
4154
+ }
4155
+ }
4156
+ return val;
4157
+ }
4158
+ if (val.includes('{{') && val.includes('}}')) {
4159
+ return val.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (fullMatch, expr) => {
4160
+ const resolved = this.resolveUpstreamPath(expr, upstream);
4161
+ if (resolved === undefined || resolved === null) {
4162
+ return fullMatch;
4163
+ }
4164
+ return typeof resolved === 'object' ? JSON.stringify(resolved) : String(resolved);
4165
+ });
4166
+ }
4167
+ return val;
4168
+ }
4169
+ if (Array.isArray(val)) {
4170
+ return val.map((item) => this.resolveInputValue(item, upstream, false));
4171
+ }
4172
+ if (val && typeof val === 'object') {
4173
+ const out = {};
4174
+ for (const [k, v] of Object.entries(val)) {
4175
+ out[k] = this.resolveInputValue(v, upstream, false, isRootObject ? k : undefined);
4176
+ }
4177
+ return out;
4178
+ }
4179
+ return val;
4180
+ }
4181
+ /**
4182
+ * Returns true when `rawExpr` refers to an entire upstream task output object
4183
+ * (e.g. `@task1.output`, `{{query_sales.output}}`, `{{output.task1}}`, `{{output}}`)
4184
+ * rather than a specific property path within the output.
4185
+ */
4186
+ isWholeUpstreamReference(rawExpr, upstream) {
4187
+ const normalized = rawExpr.trim().replace(/^@/, '');
4188
+ if (/^(?:[a-zA-Z0-9_-]+\.)?(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload)$/i.test(normalized)) {
4189
+ return true;
4190
+ }
4191
+ const m = normalized.match(/^(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload|result)\.([a-zA-Z0-9_-]+)$/i);
4192
+ if (m) {
4193
+ const key = m[1];
4194
+ if (this.lookupCaseInsensitive(upstream, key) === undefined &&
4195
+ !(upstream.results && typeof upstream.results === 'object' && !Array.isArray(upstream.results) &&
4196
+ this.lookupCaseInsensitive(upstream.results, key) !== undefined)) {
4197
+ return true;
4198
+ }
4199
+ }
4200
+ return false;
4201
+ }
4202
+ resolveUpstreamPath(rawExpr, upstream) {
4203
+ let normalized = rawExpr.trim().replace(/^@/, '');
4204
+ if (this.isWholeUpstreamReference(normalized, upstream)) {
4205
+ return { ...upstream };
4206
+ }
4207
+ const taskOutputFieldMatch = normalized.match(/^(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload|result)\.[a-zA-Z0-9_-]+\.(?:output|payload)\.(.+)$/i) ??
4208
+ normalized.match(/^[a-zA-Z0-9_-]+\.(?:output|payload)\.(.+)$/i);
4209
+ if (taskOutputFieldMatch) {
4210
+ normalized = taskOutputFieldMatch[1];
4211
+ }
4212
+ else {
4213
+ normalized = normalized.replace(/^(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload|result)\./i, '');
4214
+ }
4215
+ const direct = this.walkObjectPath(upstream, normalized);
4216
+ if (direct !== undefined) {
4217
+ return direct;
4218
+ }
4219
+ if (upstream.results && typeof upstream.results === 'object' && !Array.isArray(upstream.results)) {
4220
+ const fromResults = this.walkObjectPath(upstream.results, normalized);
4221
+ if (fromResults !== undefined) {
4222
+ return fromResults;
4223
+ }
4224
+ }
4225
+ // Fallback when the first segment is a symbolic task ID (e.g. `output.create_report_doc.handle` or `outputFromTask.code1.summary`)
4226
+ const firstDot = normalized.indexOf('.');
4227
+ if (firstDot > 0) {
4228
+ const firstSeg = normalized.slice(0, firstDot);
4229
+ const rest = normalized.slice(firstDot + 1);
4230
+ if (this.lookupCaseInsensitive(upstream, firstSeg) === undefined) {
4231
+ const viaRest = this.walkObjectPath(upstream, rest);
4232
+ if (viaRest !== undefined) {
4233
+ return viaRest;
4234
+ }
4235
+ if (upstream.results && typeof upstream.results === 'object' && !Array.isArray(upstream.results)) {
4236
+ const viaResultsRest = this.walkObjectPath(upstream.results, rest);
4237
+ if (viaResultsRest !== undefined) {
4238
+ return viaResultsRest;
4239
+ }
4240
+ }
4241
+ }
4242
+ }
4243
+ return undefined;
4244
+ }
4245
+ walkObjectPath(root, dotPath) {
4246
+ const segments = dotPath.split('.').map((s) => s.trim()).filter(Boolean);
4247
+ let current = root;
4248
+ for (const seg of segments) {
4249
+ if (!current || typeof current !== 'object' || Array.isArray(current)) {
4250
+ return undefined;
4251
+ }
4252
+ const arrayMatch = seg.match(/^([^[\]]+)\[(\d+)\]$/);
4253
+ if (arrayMatch) {
4254
+ const arrVal = this.lookupCaseInsensitive(current, arrayMatch[1]);
4255
+ if (!Array.isArray(arrVal)) {
4256
+ return undefined;
4257
+ }
4258
+ current = arrVal[Number(arrayMatch[2])];
4259
+ continue;
4260
+ }
4261
+ current = this.lookupCaseInsensitive(current, seg);
4262
+ }
4263
+ return current;
4264
+ }
4265
+ lookupCaseInsensitive(obj, key) {
4266
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
4267
+ return obj[key];
4268
+ }
4269
+ const lower = key.toLowerCase();
4270
+ for (const [k, v] of Object.entries(obj)) {
4271
+ if (k.toLowerCase() === lower) {
4272
+ return v;
4273
+ }
4274
+ }
4275
+ return undefined;
4276
+ }
3904
4277
  }
3905
4278
  //# sourceMappingURL=TaskGraphDispatcher.js.map