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

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.
@@ -1655,6 +1738,7 @@ export class TaskGraphDispatcher {
1655
1738
  WorkflowName: parent.Name,
1656
1739
  ConversationDetailID: parent.ConversationDetailID ?? null,
1657
1740
  SubmittedByAgentRunID: meta.submittedByAgentRunID,
1741
+ SubmittedByUserID: meta.submittedByUserID ?? null,
1658
1742
  ReinvokeDepth: meta.reinvokeDepth,
1659
1743
  Tasks: [...graph.entityById.values()].map((t) => ({
1660
1744
  TaskID: t.ID,
@@ -1745,7 +1829,7 @@ export class TaskGraphDispatcher {
1745
1829
  * loop; the task is still visible in the Tasks UI, so the work is discoverable even when the
1746
1830
  * nudge does not arrive.
1747
1831
  */
1748
- async notifyHumanTaskReady(task, provider) {
1832
+ async notifyHumanTaskReady(task, provider, preloadedParent) {
1749
1833
  if (task.ClaimedBy === HUMAN_TASK_NOTIFIED_MARKER)
1750
1834
  return;
1751
1835
  // The REQUEST is raised whether or not the task names an assignee. An unassigned human step
@@ -1757,7 +1841,7 @@ export class TaskGraphDispatcher {
1757
1841
  // has no owning agent — which can never succeed — was re-attempted on every poll forever,
1758
1842
  // each pass re-reading the graph, until the process was OOM-killed. The marker exists to
1759
1843
  // prevent exactly that storm; a permanent failure has to set it.
1760
- const raised = await this.raiseHumanRequest(task, provider);
1844
+ const raised = await this.raiseHumanRequest(task, provider, preloadedParent);
1761
1845
  if (raised === 'transient-failure')
1762
1846
  return; // try again next poll
1763
1847
  if (raised === 'permanent-failure') {
@@ -1969,18 +2053,26 @@ export class TaskGraphDispatcher {
1969
2053
  * complete" as a query is possible but would be a second, independently-maintained definition of
1970
2054
  * the same rule, free to drift from the one the in-run executor uses.
1971
2055
  */
1972
- async findClaimableTasks(provider, limit) {
2056
+ async findClaimableTasks(provider, limit, preloadedGraphs) {
1973
2057
  const claimable = [];
1974
2058
  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) {
2059
+ const graphSources = preloadedGraphs
2060
+ ? preloadedGraphs
2061
+ .map((g) => ({ parentID: g.parentTaskID ?? g.parent?.ID ?? '', preloaded: g }))
2062
+ .filter((entry) => entry.parentID.length > 0)
2063
+ : await (async () => {
2064
+ const activeGraphs = await this.findActiveGraphIDs(provider);
2065
+ // Usually a no-op — propagateAndRollup primed these earlier in the same pass.
2066
+ await this.primeDebugStates(provider, activeGraphs);
2067
+ return activeGraphs.map((parentID) => ({ parentID }));
2068
+ })();
2069
+ for (const source of graphSources) {
1979
2070
  if (claimable.length >= limit)
1980
2071
  break;
2072
+ const { parentID } = source;
1981
2073
  const debug = await this.readDebugState(provider, parentID);
1982
2074
  await this.announcePauseTransition(provider, parentID, debug);
1983
- const graph = await this.loadGraphState(provider, parentID, debug);
2075
+ const graph = source.preloaded ?? await this.loadGraphState(provider, parentID, debug);
1984
2076
  // HOLD is what makes "a broken condition stalls visibly" true rather than merely stated.
1985
2077
  // An undecided exclusive group keeps all its edges, and a kept edge on a Complete origin
1986
2078
  // is a SATISFIED prerequisite — so without this filter every branch of the fork would be
@@ -2109,12 +2201,21 @@ export class TaskGraphDispatcher {
2109
2201
  `assignment and is not a human step — nothing can execute it. The graph will stall.`);
2110
2202
  continue;
2111
2203
  }
2112
- await this.notifyHumanTaskReady(entity, provider);
2204
+ await this.notifyHumanTaskReady(entity, provider, graph.parent);
2113
2205
  continue;
2114
2206
  }
2115
2207
  if (this.inFlight.has(entity.ID))
2116
2208
  continue;
2117
- claimable.push(entity);
2209
+ claimable.push({
2210
+ ID: entity.ID,
2211
+ taskId: entity.ID,
2212
+ ParentID: entity.ParentID,
2213
+ Name: entity.Name,
2214
+ taskEntity: entity,
2215
+ parentTask: graph.parent ?? null,
2216
+ parentMetadata: graph.parentMetadata,
2217
+ dependencyOutputs: this.extractDependencyOutputsFromGraph(entity.ID, graph),
2218
+ });
2118
2219
  if (claimable.length >= limit)
2119
2220
  break;
2120
2221
  }
@@ -2229,7 +2330,7 @@ export class TaskGraphDispatcher {
2229
2330
  * submitted it, so nothing is suspended — the task sits Pending, every other branch keeps
2230
2331
  * running, and answering settles the task. That column staying null is meaningful, not missing.
2231
2332
  */
2232
- async raiseHumanRequest(task, provider) {
2333
+ async raiseHumanRequest(task, provider, preloadedParent) {
2233
2334
  try {
2234
2335
  const existing = await this.findOpenRequests(provider, task.ID);
2235
2336
  if (existing.length > 0) {
@@ -2244,7 +2345,7 @@ export class TaskGraphDispatcher {
2244
2345
  // A human task has NO AgentID of its own — that column names what EXECUTES a step, and
2245
2346
  // a person is not an agent. The request still needs one, so it carries the agent that
2246
2347
  // owns the workflow: the graph's own agent, which is who is asking.
2247
- const owningAgentID = await this.owningAgentOf(provider, task);
2348
+ const owningAgentID = await this.owningAgentOf(provider, task, preloadedParent);
2248
2349
  if (!owningAgentID) {
2249
2350
  // PERMANENT: a graph with no owning agent will not acquire one by being asked
2250
2351
  // again. Graphs submitted before the provenance stamp landed are all in this state.
@@ -2259,7 +2360,7 @@ export class TaskGraphDispatcher {
2259
2360
  request.Status = 'Requested';
2260
2361
  request.Request = task.Description || `A workflow is waiting on you to complete "${task.Name}".`;
2261
2362
  // 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);
2363
+ request.OriginatingAgentRunID = await this.submittingRunOf(provider, task, preloadedParent);
2263
2364
  // The deadline, when the author set one. `expireOverdueRequests` has always been able to
2264
2365
  // enforce this — it expires the request and fails the step so a give-up edge can route
2265
2366
  // around it — but nothing ever WROTE the column, so that whole path had never run outside
@@ -2308,15 +2409,19 @@ export class TaskGraphDispatcher {
2308
2409
  * Reads the graph's parent row, falling back to the run that submitted it. A human step has no
2309
2410
  * agent of its own by design: `AgentID` names what EXECUTES a step, and a person is not an agent.
2310
2411
  */
2311
- async owningAgentOf(provider, task) {
2412
+ async owningAgentOf(provider, task, preloadedParent) {
2312
2413
  if (task.AgentID)
2313
2414
  return task.AgentID;
2314
2415
  if (!task.ParentID)
2315
2416
  return null;
2316
2417
  try {
2317
- const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
2318
- if (!(await parent.Load(task.ParentID)))
2319
- return null;
2418
+ let parent = preloadedParent ?? null;
2419
+ if (!parent) {
2420
+ const candidate = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
2421
+ if (!(await candidate.Load(task.ParentID)))
2422
+ return null;
2423
+ parent = candidate;
2424
+ }
2320
2425
  if (parent.AgentID)
2321
2426
  return parent.AgentID;
2322
2427
  if (!parent.AgentRunID)
@@ -2360,16 +2465,24 @@ export class TaskGraphDispatcher {
2360
2465
  * request's own ResponseSchema. A step that only recorded "approved" would force every decision
2361
2466
  * back into a separate action.
2362
2467
  */
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 ?? []) {
2468
+ async settleAnsweredHumanTasks(provider, graphID, pendingHumanTasks) {
2469
+ let tasksToInspect;
2470
+ if (pendingHumanTasks) {
2471
+ tasksToInspect = pendingHumanTasks.filter((t) => t.Status === 'Pending');
2472
+ }
2473
+ else {
2474
+ const waiting = await RunView.FromMetadataProvider(provider).RunView({
2475
+ EntityName: 'MJ: Tasks',
2476
+ ExtraFilter: `ParentID='${graphID}' AND ${HumanTaskSQL()} AND Status='Pending'`,
2477
+ ResultType: 'entity_object',
2478
+ BypassCache: true,
2479
+ }, this.contextUser);
2480
+ if (!waiting.Success)
2481
+ return 0;
2482
+ tasksToInspect = waiting.Results ?? [];
2483
+ }
2484
+ let settledCount = 0;
2485
+ for (const task of tasksToInspect) {
2373
2486
  const request = await this.answeredRequestFor(provider, task.ID);
2374
2487
  if (!request)
2375
2488
  continue;
@@ -2395,6 +2508,7 @@ export class TaskGraphDispatcher {
2395
2508
  `${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
2396
2509
  continue;
2397
2510
  }
2511
+ settledCount++;
2398
2512
  // WITHDRAW EVERY OTHER OPEN ASK FOR THIS STEP (R3-5).
2399
2513
  //
2400
2514
  // The step is terminal now, so both human sweeps — which scope to `Pending` tasks — will
@@ -2404,6 +2518,7 @@ export class TaskGraphDispatcher {
2404
2518
  // retroactively cleans the ones already minted, which the raise-side fix cannot reach.
2405
2519
  await this.withdrawOpenRequests(provider, [task.ID], 'This step has been settled; the request is no longer open.');
2406
2520
  }
2521
+ return settledCount;
2407
2522
  }
2408
2523
  /**
2409
2524
  * Reconciles the requests behind human steps that are waiting on somebody.
@@ -2426,25 +2541,32 @@ export class TaskGraphDispatcher {
2426
2541
  * and raises a fresh request, which is exactly the replacement the design assumed. Bounded by
2427
2542
  * human action: it takes another person cancelling again to come back here.
2428
2543
  */
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 ?? []) {
2544
+ async reconcileWaitingHumanTasks(provider, graphID, pendingHumanTasks) {
2545
+ let tasksToInspect;
2546
+ if (pendingHumanTasks) {
2547
+ tasksToInspect = pendingHumanTasks.filter((t) => t.Status === 'Pending' && t.ClaimedBy === HUMAN_TASK_NOTIFIED_MARKER);
2548
+ }
2549
+ else {
2550
+ const waiting = await RunView.FromMetadataProvider(provider).RunView({
2551
+ EntityName: 'MJ: Tasks',
2552
+ // `StepType` is NULLABLE, and rows predating the column exist (4 in the reference
2553
+ // database at the time of writing). None currently carry a UserID, but a human task
2554
+ // written by any path that set the assignee without the discriminator would be
2555
+ // invisible to a `StepType='Human'` filter and stay dead forever after a cancel —
2556
+ // the exact stall this method exists to end. The notified marker already narrows
2557
+ // this to tasks the dispatcher raised a request for, so the widening cannot pull in
2558
+ // unrelated work.
2559
+ ExtraFilter: `ParentID='${graphID}' AND Status='Pending' ` +
2560
+ `AND ${HumanTaskSQL()} ` +
2561
+ `AND ClaimedBy='${HUMAN_TASK_NOTIFIED_MARKER}'`,
2562
+ ResultType: 'entity_object',
2563
+ BypassCache: true,
2564
+ }, this.contextUser);
2565
+ if (!waiting.Success)
2566
+ return;
2567
+ tasksToInspect = waiting.Results ?? [];
2568
+ }
2569
+ for (const task of tasksToInspect) {
2448
2570
  // Only when there is nothing live AND nothing terminal. A task with an open request is
2449
2571
  // simply waiting; one with a terminal request is settled on the next pass by
2450
2572
  // settleAnsweredHumanTasks, and re-raising either would ask the same question twice.
@@ -2486,16 +2608,22 @@ export class TaskGraphDispatcher {
2486
2608
  * A deadline that nothing enforces is a comment. Without this an `ExpiresAt` in the past leaves
2487
2609
  * the request `Requested` forever and the workflow waiting on it just as long.
2488
2610
  */
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}'`);
2611
+ async expireOverdueRequests(provider, graphID, pendingHumanTasks) {
2612
+ let ids;
2613
+ if (pendingHumanTasks) {
2614
+ ids = pendingHumanTasks.filter((t) => t.Status === 'Pending').map((r) => `'${r.ID}'`);
2615
+ }
2616
+ else {
2617
+ // Scoped by an explicit id list rather than a subquery against a view name, so this reads
2618
+ // the same on any provider rather than assuming a SQL dialect and a physical view.
2619
+ const humanTasks = await RunView.FromMetadataProvider(provider).RunView({
2620
+ EntityName: 'MJ: Tasks',
2621
+ Fields: ['ID'],
2622
+ ExtraFilter: `ParentID='${graphID}' AND ${HumanTaskSQL()} AND Status='Pending'`,
2623
+ ResultType: 'simple',
2624
+ }, this.contextUser);
2625
+ ids = (humanTasks.Results ?? []).map((r) => `'${r.ID}'`);
2626
+ }
2499
2627
  if (ids.length === 0)
2500
2628
  return;
2501
2629
  const nowISO = new Date().toISOString();
@@ -2516,9 +2644,11 @@ export class TaskGraphDispatcher {
2516
2644
  }
2517
2645
  }
2518
2646
  /** The agent run that submitted this task's graph, for provenance on the request. */
2519
- async submittingRunOf(provider, task) {
2647
+ async submittingRunOf(provider, task, preloadedParent) {
2520
2648
  if (!task.ParentID)
2521
2649
  return null;
2650
+ if (preloadedParent)
2651
+ return preloadedParent.AgentRunID;
2522
2652
  try {
2523
2653
  const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
2524
2654
  return (await parent.Load(task.ParentID)) ? parent.AgentRunID : null;
@@ -2528,7 +2658,7 @@ export class TaskGraphDispatcher {
2528
2658
  }
2529
2659
  }
2530
2660
  /** Loads a graph's children and edges in the shapes both the algorithms and mutation need. */
2531
- async loadGraphState(provider, parentTaskID, debug) {
2661
+ async loadGraphState(provider, parentTaskID, debug, preloadedParent) {
2532
2662
  const rv = RunView.FromMetadataProvider(provider);
2533
2663
  // BypassCache throughout: task status is written by the claim protocol's direct SQL, which
2534
2664
  // fires no cache invalidation. See findActiveGraphIDs.
@@ -2536,7 +2666,11 @@ export class TaskGraphDispatcher {
2536
2666
  const children = (childrenResult.Success ? childrenResult.Results : []) ?? [];
2537
2667
  if (children.length === 0) {
2538
2668
  return {
2669
+ parentTaskID,
2670
+ parent: preloadedParent ?? null,
2671
+ parentMetadata: ParseTaskGraphParentMetadata(preloadedParent?.InputPayload ?? null),
2539
2672
  nodes: [], edges: [], entityById: new Map(),
2673
+ rawDependencies: [],
2540
2674
  unreachableTaskIDs: new Set(), cascadeSkipTaskIDs: new Set(),
2541
2675
  skipSeedTaskIDs: new Set(), holdTaskIDs: new Set(),
2542
2676
  handledFailureIDs: new Set(),
@@ -2546,12 +2680,21 @@ export class TaskGraphDispatcher {
2546
2680
  const depsResult = await rv.RunView({ EntityName: 'MJ: Task Dependencies', ExtraFilter: `TaskID IN (${idList})`, ResultType: 'entity_object', BypassCache: true }, this.contextUser);
2547
2681
  const deps = (depsResult.Success ? depsResult.Results : []) ?? [];
2548
2682
  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);
2683
+ // Read ONCE, and retained on `GraphState` so parent rollup, continuation, human request
2684
+ // provenance, and claimed-task execution all reuse the same loaded parent entity and
2685
+ // parsed metadata without re-querying `MJ: Tasks`.
2686
+ const parent = preloadedParent !== undefined
2687
+ ? preloadedParent
2688
+ : await this.loadParentTask(provider, parentTaskID);
2689
+ const parentMeta = parent
2690
+ ? ParseTaskGraphParentMetadata(parent.InputPayload)
2691
+ : ParseTaskGraphParentMetadata(null);
2692
+ const effectiveDebug = debug
2693
+ ?? this.debugStateByGraph?.get(parentTaskID)
2694
+ ?? ParseTaskGraphDebugState(parent?.InputPayload ?? null);
2695
+ if (!this.debugStateByGraph?.has(parentTaskID)) {
2696
+ this.debugStateByGraph?.set(parentTaskID, effectiveDebug);
2697
+ }
2555
2698
  const failureSemantics = parentMeta.failureSemantics;
2556
2699
  // The invocation's own parameters, carried on the parent so a condition evaluated by any
2557
2700
  // instance sees what the walker saw (R3-3).
@@ -2610,7 +2753,7 @@ export class TaskGraphDispatcher {
2610
2753
  originStatus: (entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending'),
2611
2754
  priority: d.Priority ?? 0,
2612
2755
  sequence: d.Sequence ?? 0,
2613
- conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, decisions, debug, exclusiveHoldReasons),
2756
+ conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, decisions, effectiveDebug, exclusiveHoldReasons),
2614
2757
  })), (edge) => ReadsFailedDecision(conditionByEdge.get(edge.id) ?? '', failedDecisions)),
2615
2758
  // WHICH STATUSES MAY DECIDE — the graph's own failure dialect, not a constant.
2616
2759
  //
@@ -2635,8 +2778,9 @@ export class TaskGraphDispatcher {
2635
2778
  // change-only, so a viewer learns WHY a branch ran (or is held) the moment it is decided.
2636
2779
  const gateDecisions = [];
2637
2780
  for (const d of ordinary) {
2638
- if (d.Condition?.trim()) {
2639
- const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, decisions, debug);
2781
+ const cond = d.Condition?.trim();
2782
+ if (cond && cond.toLowerCase() !== 'true' && cond !== '1 === 1' && cond !== '1 == 1') {
2783
+ const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, decisions, effectiveDebug);
2640
2784
  if (decision.decided) {
2641
2785
  gateDecisions.push({
2642
2786
  edge: d,
@@ -2650,8 +2794,8 @@ export class TaskGraphDispatcher {
2650
2794
  }
2651
2795
  if (decision.outcome === 'hold')
2652
2796
  heldByCondition.add(d.TaskID);
2797
+ stillReachable.add(d.TaskID);
2653
2798
  }
2654
- stillReachable.add(d.TaskID);
2655
2799
  liveEdges.push({
2656
2800
  taskId: d.TaskID,
2657
2801
  dependsOnTaskId: d.DependsOnTaskID,
@@ -2699,7 +2843,7 @@ export class TaskGraphDispatcher {
2699
2843
  const exclusiveHolds = new Set(resolution.holdTaskIDs);
2700
2844
  for (const d of exclusive) {
2701
2845
  const originStatus = entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending';
2702
- if (!decidingStatuses.has(originStatus) && !OverrideVerdictFor(debug ?? {}, d.ID))
2846
+ if (!decidingStatuses.has(originStatus) && !OverrideVerdictFor(effectiveDebug, d.ID))
2703
2847
  continue;
2704
2848
  const held = !loserEdgeIDs.has(d.ID) && exclusiveHolds.has(d.TaskID);
2705
2849
  // The edge that holds its fork says why — below its confidence, from a failed call — and
@@ -2748,9 +2892,13 @@ export class TaskGraphDispatcher {
2748
2892
  }
2749
2893
  }
2750
2894
  return {
2895
+ parentTaskID,
2896
+ parent,
2897
+ parentMetadata: parentMeta,
2751
2898
  nodes,
2752
2899
  edges: liveEdges,
2753
2900
  entityById,
2901
+ rawDependencies: deps,
2754
2902
  unreachableTaskIDs,
2755
2903
  cascadeSkipTaskIDs,
2756
2904
  skipSeedTaskIDs: confirmedSkipSeeds,
@@ -2922,6 +3070,29 @@ export class TaskGraphDispatcher {
2922
3070
  }
2923
3071
  }).catch(() => { });
2924
3072
  }
3073
+ /**
3074
+ * Extracts parsed `OutputPayload` values for all dependencies of `taskID` directly from the
3075
+ * already-loaded `GraphState`, avoiding any additional database round-trips when claiming and
3076
+ * executing a task.
3077
+ */
3078
+ extractDependencyOutputsFromGraph(taskID, graph) {
3079
+ const outputs = new Map();
3080
+ const deps = graph.rawDependencies ?? [];
3081
+ for (const dep of deps) {
3082
+ if (!UUIDsEqual(dep.TaskID, taskID))
3083
+ continue;
3084
+ const upstream = graph.entityById.get(dep.DependsOnTaskID);
3085
+ if (!upstream?.OutputPayload)
3086
+ continue;
3087
+ try {
3088
+ outputs.set(dep.DependsOnTaskID, JSON.parse(upstream.OutputPayload));
3089
+ }
3090
+ catch (e) {
3091
+ LogError(`[TaskGraphDispatcher] Task ${dep.DependsOnTaskID} has malformed OutputPayload: ${e}`);
3092
+ }
3093
+ }
3094
+ return outputs;
3095
+ }
2925
3096
  /** Parsed `OutputPayload` of each completed dependency, keyed by that task's ID. */
2926
3097
  async loadDependencyOutputs(provider, taskID) {
2927
3098
  const outputs = new Map();
@@ -2955,7 +3126,7 @@ export class TaskGraphDispatcher {
2955
3126
  * Every branch is normalized to one shape so the recording path above stays single: an action has
2956
3127
  * no agent run to point at, because its forensics live in `ActionExecutionLog` instead.
2957
3128
  */
2958
- async runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress) {
3129
+ async runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress, prehydrated) {
2959
3130
  // A node's input is a name → value object (`TaskGraphSpecNode.inputPayload: Record<string, unknown>`).
2960
3131
  // `mergedPayload` below only merges objects, so anything else would be dropped without a word
2961
3132
  // and the step would run with none of its inputs — how durable entity actions ran before MJ#4794
@@ -2976,18 +3147,19 @@ export class TaskGraphDispatcher {
2976
3147
  // A loop's own step type decides how many times its body runs; the body itself is dispatched
2977
3148
  // through the very same runners as a one-shot step.
2978
3149
  if (task.StepType === 'ForEach' || task.StepType === 'While') {
2979
- return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs), PayloadAtStart: payload };
3150
+ return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs, prehydrated), PayloadAtStart: payload };
2980
3151
  }
2981
3152
  // Routed on StepType before the mappings below: a Decision reads its state from the merged
2982
3153
  // payload by path and writes its answers back under `decisions`, so it has no mapping of its
2983
3154
  // own. And it carries a PromptID, so the Prompt branch would otherwise take it.
2984
3155
  if (task.StepType === 'Decision') {
2985
- return { ...await this.runDecisionNode(task, provider, payload, onProgress), PayloadAtStart: payload };
3156
+ return { ...await this.runDecisionNode(task, provider, payload, onProgress, prehydrated), PayloadAtStart: payload };
2986
3157
  }
2987
3158
  // `data.*` / `context.*` resolve against the invocation that submitted the graph, exactly as
2988
3159
  // the in-run walker resolves them and as branch conditions already see them (R3-3). Without
2989
3160
  // 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 : {};
3161
+ const context = await this.graphContext(provider, task, prehydrated);
3162
+ const invocation = config?.inputMapping ? context.Invocation : {};
2991
3163
  const { params, errors } = BuildMappedInput(config?.inputMapping, { payload, ...invocation });
2992
3164
  for (const e of errors)
2993
3165
  LogError(`[TaskGraphDispatcher] Task ${task.ID}: ${e}`);
@@ -3017,7 +3189,7 @@ export class TaskGraphDispatcher {
3017
3189
  DependencyOutputs: dependencyOutputs,
3018
3190
  TemplateParameters: config?.prompt?.templateParameters,
3019
3191
  Provider: provider,
3020
- ContextUser: this.contextUser,
3192
+ ContextUser: context.ExecutionUser,
3021
3193
  OnProgress: onProgress,
3022
3194
  });
3023
3195
  // A prompt's response is DEEP-MERGED into the payload rather than replacing it. A prompt
@@ -3046,10 +3218,10 @@ export class TaskGraphDispatcher {
3046
3218
  InputPayload: effectiveInput,
3047
3219
  DependencyOutputs: dependencyOutputs,
3048
3220
  Provider: provider,
3049
- ContextUser: this.contextUser,
3221
+ ContextUser: context.ExecutionUser,
3050
3222
  OnProgress: onProgress,
3051
3223
  }), AgentRunID: null }
3052
- : await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress);
3224
+ : await this.runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, context);
3053
3225
  return {
3054
3226
  ...raw,
3055
3227
  Output: this.applyStepOutputMapping(task, payload, raw.Output, config?.outputMapping),
@@ -3064,7 +3236,7 @@ export class TaskGraphDispatcher {
3064
3236
  * merged into the payload before the mapping is applied, which is how a body can reference the
3065
3237
  * current item at all.
3066
3238
  */
3067
- async runLoopTask(task, provider, payload, dependencyOutputs) {
3239
+ async runLoopTask(task, provider, payload, dependencyOutputs, prehydrated) {
3068
3240
  const config = task.ConfigurationObject;
3069
3241
  const op = task.StepType === 'ForEach' ? config?.forEach : config?.while;
3070
3242
  if (!op) {
@@ -3092,7 +3264,7 @@ export class TaskGraphDispatcher {
3092
3264
  // cost), and the continuation depth (so the recursion cap still applies). Omitting them made
3093
3265
  // loop bodies second-class in every dimension — and reopened the unbounded-recursion hole
3094
3266
  // THROUGH loops, since each spawned run restarted the chain at zero.
3095
- const graphContext = await this.graphContext(provider, task);
3267
+ const graphContext = await this.graphContext(provider, task, prehydrated);
3096
3268
  // THE LOOP'S PAYLOAD ACCUMULATES. Each iteration's output merges in, and the next iteration
3097
3269
  // — and the While condition — sees it. Without this the condition closure re-read the
3098
3270
  // payload as it was when the loop STARTED, so a `while payload.brandOK !== true` could never
@@ -3180,7 +3352,7 @@ export class TaskGraphDispatcher {
3180
3352
  // confidently about nothing.
3181
3353
  TemplateParameters: { ...stringifyBindings(Bindings), ...op.prompt?.templateParameters },
3182
3354
  Provider: provider,
3183
- ContextUser: this.contextUser,
3355
+ ContextUser: graphContext.ExecutionUser,
3184
3356
  }), iterationPayload);
3185
3357
  }
3186
3358
  if (task.ActionID) {
@@ -3190,7 +3362,7 @@ export class TaskGraphDispatcher {
3190
3362
  InputPayload: resolved,
3191
3363
  DependencyOutputs: dependencyOutputs,
3192
3364
  Provider: provider,
3193
- ContextUser: this.contextUser,
3365
+ ContextUser: graphContext.ExecutionUser,
3194
3366
  }), resolved);
3195
3367
  }
3196
3368
  const agentInput = Object.keys(resolved).length > 0 ? resolved : iterationPayload;
@@ -3205,7 +3377,7 @@ export class TaskGraphDispatcher {
3205
3377
  ContinuationDepth: graphContext.Depth,
3206
3378
  SubmittingAgentRunID: graphContext.SubmittingAgentRunID,
3207
3379
  Provider: provider,
3208
- ContextUser: this.contextUser,
3380
+ ContextUser: graphContext.ExecutionUser,
3209
3381
  }), agentInput);
3210
3382
  };
3211
3383
  const outcome = task.StepType === 'ForEach'
@@ -3321,8 +3493,8 @@ export class TaskGraphDispatcher {
3321
3493
  * Depth and provenance are read together because they come from the same row: the graph's parent
3322
3494
  * task knows both how many continuation hops led here and which run submitted it.
3323
3495
  */
3324
- async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress) {
3325
- const context = await this.graphContext(provider, task);
3496
+ async runAgentNode(task, provider, effectiveInput, dependencyOutputs, onProgress, resolvedContext) {
3497
+ const context = resolvedContext ?? await this.graphContext(provider, task);
3326
3498
  return this.agentRunner.RunAgentForTask({
3327
3499
  TaskID: task.ID,
3328
3500
  AgentID: task.AgentID,
@@ -3331,7 +3503,7 @@ export class TaskGraphDispatcher {
3331
3503
  ContinuationDepth: context.Depth,
3332
3504
  SubmittingAgentRunID: context.SubmittingAgentRunID,
3333
3505
  Provider: provider,
3334
- ContextUser: this.contextUser,
3506
+ ContextUser: context.ExecutionUser,
3335
3507
  OnProgress: onProgress,
3336
3508
  });
3337
3509
  }
@@ -3349,7 +3521,7 @@ export class TaskGraphDispatcher {
3349
3521
  * and the call asks only the rest. If that call fails, or cannot be made, the step stays
3350
3522
  * `Complete` with the same usable answers, and the questions it asked again hold with the reason.
3351
3523
  */
3352
- async runDecisionNode(task, provider, payload, onProgress) {
3524
+ async runDecisionNode(task, provider, payload, onProgress, prehydrated) {
3353
3525
  const config = ReadDecisionStepConfiguration(task.Configuration);
3354
3526
  if (!config)
3355
3527
  return this.decisionNotAsked(task, payload, 'it has no decision settings, so there is nothing to ask');
@@ -3366,6 +3538,7 @@ export class TaskGraphDispatcher {
3366
3538
  const conflict = DecisionsPayloadConflict(payload);
3367
3539
  if (conflict)
3368
3540
  return notAsked(conflict);
3541
+ const context = await this.graphContext(provider, task, prehydrated);
3369
3542
  const startedAt = new Date();
3370
3543
  const result = await this.decisionRunner.RunDecisionForTask({
3371
3544
  TaskID: task.ID,
@@ -3373,10 +3546,10 @@ export class TaskGraphDispatcher {
3373
3546
  State: state.State,
3374
3547
  Questions: toAsk,
3375
3548
  Provider: provider,
3376
- ContextUser: this.contextUser,
3549
+ ContextUser: context.ExecutionUser,
3377
3550
  OnProgress: onProgress,
3378
3551
  });
3379
- await this.logDecisionStep(provider, task, config, toAsk, state.State, result, startedAt);
3552
+ await this.logDecisionStep(provider, task, config, toAsk, state.State, result, startedAt, context);
3380
3553
  if (!result.Success || !result.Answers) {
3381
3554
  const message = result.ErrorMessage || `Decision "${task.Name}" returned no answers.`;
3382
3555
  if (Object.keys(kept).length > 0)
@@ -3440,9 +3613,9 @@ export class TaskGraphDispatcher {
3440
3613
  * recorded in its prompt run, which the task points at. Observability only: a failure to log is
3441
3614
  * reported, and the decision stands.
3442
3615
  */
3443
- async logDecisionStep(provider, task, config, asked, state, result, startedAt) {
3616
+ async logDecisionStep(provider, task, config, asked, state, result, startedAt, resolvedContext) {
3444
3617
  try {
3445
- const { SubmittingAgentRunID: agentRunID } = await this.graphContext(provider, task);
3618
+ const { SubmittingAgentRunID: agentRunID } = resolvedContext ?? await this.graphContext(provider, task);
3446
3619
  if (!agentRunID)
3447
3620
  return;
3448
3621
  // The number is read and the step saved as one unit per run, so two Decision steps
@@ -3612,25 +3785,39 @@ export class TaskGraphDispatcher {
3612
3785
  this.retryingSettlement.set(parentID, passes);
3613
3786
  }
3614
3787
  /**
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.
3788
+ * Loads a graph's parent `MJ: Tasks` row once and caches its owner and debug state when present.
3621
3789
  */
3622
- async readParentMetadataFor(provider, parentTaskID) {
3790
+ async loadParentTask(provider, parentTaskID) {
3623
3791
  try {
3624
3792
  const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
3625
- if (await parent.Load(parentTaskID))
3626
- return ParseTaskGraphParentMetadata(parent.InputPayload);
3793
+ if (await parent.Load(parentTaskID)) {
3794
+ const meta = ParseTaskGraphParentMetadata(parent.InputPayload);
3795
+ const owner = meta.submittedByUserID ?? parent.UserID ?? null;
3796
+ this.ownerByParentID?.set(parentTaskID, owner);
3797
+ if (!this.debugStateByGraph?.has(parentTaskID)) {
3798
+ this.debugStateByGraph?.set(parentTaskID, ParseTaskGraphDebugState(parent.InputPayload));
3799
+ }
3800
+ return parent;
3801
+ }
3627
3802
  LogError(`[TaskGraphDispatcher] Parent task ${parentTaskID} could not be loaded; using default graph metadata (no invocation data/context).`);
3628
3803
  }
3629
3804
  catch (e) {
3630
3805
  // Safe defaults still apply — but say so: a missing invocation turns every `data.*` mapping literal.
3631
3806
  LogError(`[TaskGraphDispatcher] Reading parent task ${parentTaskID} failed; using default graph metadata: ${e instanceof Error ? e.message : String(e)}`);
3632
3807
  }
3633
- return ParseTaskGraphParentMetadata(null);
3808
+ return null;
3809
+ }
3810
+ /**
3811
+ * A graph's durable metadata bag, for the questions a pass asks of it.
3812
+ *
3813
+ * Defaults on any failure to read it, and the defaults are the safe directions: `'block'` means
3814
+ * a failed step decides nothing, so a graph whose metadata we cannot read stalls visibly instead
3815
+ * of resolving forks on the say-so of a failure; and no early-finish declaration means nothing
3816
+ * is removed from the claim filter on the strength of a read that did not work.
3817
+ */
3818
+ async readParentMetadataFor(provider, parentTaskID) {
3819
+ const parent = await this.loadParentTask(provider, parentTaskID);
3820
+ return parent ? ParseTaskGraphParentMetadata(parent.InputPayload) : ParseTaskGraphParentMetadata(null);
3634
3821
  }
3635
3822
  /**
3636
3823
  * Whether the submitting run is in a state where this pass's writes to it will mean anything.
@@ -3670,7 +3857,7 @@ export class TaskGraphDispatcher {
3670
3857
  // own bookkeeping is owed either way — but announcing it would message a conversation
3671
3858
  // about a workflow the user stopped, and for `reinvoke` would start a fresh billed turn
3672
3859
  // for the agent they cancelled.
3673
- const cancelled = run.Status === 'Cancelled';
3860
+ let cancelled = run.Status === 'Cancelled';
3674
3861
  const settledFor = parent.CompletedAt ? Date.now() - parent.CompletedAt.getTime() : 0;
3675
3862
  if (!IsSubmittingRunReady(run.Status, settledFor)) {
3676
3863
  // Still `Running` and inside the grace: `finalizeAgentRun` has not parked it yet.
@@ -3685,6 +3872,24 @@ export class TaskGraphDispatcher {
3685
3872
  `since graph ${parent.ID} settled — it never parked, so its submitting process most ` +
3686
3873
  `likely died. Settling and delivering the graph anyway; the run needs separate attention.`);
3687
3874
  }
3875
+ // When a sub-agent submitted the graph on behalf of a parent run, check that any
3876
+ // ancestor runs in the ParentRunID chain have also parked before settling.
3877
+ let currentParentRunID = run.ParentRunID;
3878
+ const visitedReadinessIDs = new Set([(run.ID || meta.submittedByAgentRunID).toLowerCase()]);
3879
+ while (currentParentRunID && !visitedReadinessIDs.has(currentParentRunID.toLowerCase()) && visitedReadinessIDs.size < 10) {
3880
+ visitedReadinessIDs.add(currentParentRunID.toLowerCase());
3881
+ const ancestorRun = await provider.GetEntityObject('MJ: AI Agent Runs', this.contextUser);
3882
+ if (!(await ancestorRun.Load(currentParentRunID))) {
3883
+ break;
3884
+ }
3885
+ if (ancestorRun.Status === 'Cancelled') {
3886
+ cancelled = true;
3887
+ }
3888
+ if (!IsSubmittingRunReady(ancestorRun.Status, settledFor)) {
3889
+ return { Verdict: 'defer', SubmitterCancelled: cancelled };
3890
+ }
3891
+ currentParentRunID = ancestorRun.ParentRunID;
3892
+ }
3688
3893
  return { Verdict: 'ready', SubmitterCancelled: cancelled };
3689
3894
  }
3690
3895
  catch (e) {
@@ -3724,30 +3929,42 @@ export class TaskGraphDispatcher {
3724
3929
  LogError(`[TaskGraphDispatcher] Could not load run ${meta.submittedByAgentRunID} to settle it against graph ${parent.ID}.`);
3725
3930
  return 'defer';
3726
3931
  }
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
3932
  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';
3933
+ const failureMessage = succeeded ? null : `The workflow "${parent.Name}" ended ${graphStatus}.`;
3934
+ if (run.Status === 'Paused') {
3935
+ // COLUMN-SCOPED AND GUARDED ON `Paused` (C4), for the same reason every parent write has
3936
+ // been since Round 1: a full-row save carries a stale snapshot of a row another instance
3937
+ // may have moved, and the predicate makes the transition once-only rather than
3938
+ // last-write-wins.
3939
+ const settled = await this.claims.TrySettleRun(provider, run.ID, succeeded, failureMessage, this.contextUser);
3940
+ if (!settled) {
3941
+ LogError(`[TaskGraphDispatcher] Could not settle run ${run.ID} against graph ${parent.ID}; ` +
3942
+ `it is no longer Paused or the write did not land. Retrying next pass.`);
3943
+ return 'defer';
3944
+ }
3945
+ LogStatus(`[TaskGraphDispatcher] Run ${run.ID} settled ${succeeded ? 'Completed' : 'Failed'} — ` +
3946
+ `workflow "${parent.Name}" ended ${graphStatus}.`);
3947
+ }
3948
+ // When a sub-agent (e.g. Workflow Planner) submitted the graph on behalf of a parent
3949
+ // conversation agent (e.g. Sage), BaseAgent parks the parent run as `Paused` as well.
3950
+ // Walk up `ParentRunID` and settle any ancestor runs parked in `Paused`.
3951
+ let currentParentRunID = run.ParentRunID;
3952
+ const visitedSettleIDs = new Set([(run.ID || meta.submittedByAgentRunID).toLowerCase()]);
3953
+ while (currentParentRunID && !visitedSettleIDs.has(currentParentRunID.toLowerCase()) && visitedSettleIDs.size < 10) {
3954
+ visitedSettleIDs.add(currentParentRunID.toLowerCase());
3955
+ const ancestorRun = await provider.GetEntityObject('MJ: AI Agent Runs', this.contextUser);
3956
+ if (!(await ancestorRun.Load(currentParentRunID))) {
3957
+ break;
3958
+ }
3959
+ if (ancestorRun.Status === 'Paused') {
3960
+ const ancestorSettled = await this.claims.TrySettleRun(provider, ancestorRun.ID, succeeded, failureMessage, this.contextUser);
3961
+ if (ancestorSettled) {
3962
+ LogStatus(`[TaskGraphDispatcher] Ancestor run ${ancestorRun.ID} settled ${succeeded ? 'Completed' : 'Failed'} — ` +
3963
+ `workflow "${parent.Name}" ended ${graphStatus}.`);
3964
+ }
3965
+ }
3966
+ currentParentRunID = ancestorRun.ParentRunID;
3748
3967
  }
3749
- LogStatus(`[TaskGraphDispatcher] Run ${run.ID} settled ${succeeded ? 'Completed' : 'Failed'} — ` +
3750
- `workflow "${parent.Name}" ended ${graphStatus}.`);
3751
3968
  return 'done';
3752
3969
  }
3753
3970
  catch (e) {
@@ -3784,6 +4001,7 @@ export class TaskGraphDispatcher {
3784
4001
  // nodes as though the rest of the workflow did not exist.
3785
4002
  const edges = graph.edges.map((e) => ({ From: e.dependsOnTaskId, To: e.taskId }));
3786
4003
  const positions = LayoutGraphNodes([...graph.entityById.keys()], edges, { Direction: 'LR' });
4004
+ const tasksToSave = [];
3787
4005
  for (const task of needsLayout) {
3788
4006
  const position = positions.get(task.ID);
3789
4007
  if (!position)
@@ -3794,10 +4012,13 @@ export class TaskGraphDispatcher {
3794
4012
  layout: { x: position.X, y: position.Y },
3795
4013
  };
3796
4014
  task.Configuration = JSON.stringify(merged);
4015
+ tasksToSave.push(task);
4016
+ }
4017
+ await Promise.all(tasksToSave.map(async (task) => {
3797
4018
  if (!(await task.Save())) {
3798
4019
  LogError(`[TaskGraphDispatcher] Could not save computed layout for ${task.ID}: ${task.LatestResult?.CompleteMessage ?? 'unknown error'}`);
3799
4020
  }
3800
- }
4021
+ }));
3801
4022
  }
3802
4023
  catch (e) {
3803
4024
  LogError(`[TaskGraphDispatcher] Could not compute a layout for the settled graph: ${e instanceof Error ? e.message : String(e)}`);
@@ -3897,9 +4118,162 @@ export class TaskGraphDispatcher {
3897
4118
  }
3898
4119
  }
3899
4120
  if (inputPayload) {
3900
- Object.assign(merged, inputPayload);
4121
+ const upstreamSnapshot = { ...merged };
4122
+ const resolvedInput = this.resolveInputValue(inputPayload, upstreamSnapshot, true);
4123
+ return { ...merged, ...resolvedInput };
3901
4124
  }
3902
4125
  return merged;
3903
4126
  }
4127
+ /**
4128
+ * Resolves LLM-authored template references (such as `{{output.task3.handle}}`, `{{output.summary}}`,
4129
+ * or `@task1.output.rows`) inside `inputPayload` against the merged upstream dependency outputs so
4130
+ * literal placeholder strings do not clobber real upstream values.
4131
+ */
4132
+ resolveInputValue(val, upstream, isRootObject = false, topLevelKey) {
4133
+ if (typeof val === 'string') {
4134
+ const singleMustache = val.match(/^\s*\{\{\s*([^{}]+?)\s*\}\}\s*$/);
4135
+ const singleAtRef = val.match(/^\s*@([a-zA-Z0-9_-]+\.(?:output|payload)(?:\..+?)?)\s*$/i);
4136
+ if (singleMustache || singleAtRef) {
4137
+ const expr = singleMustache ? singleMustache[1] : singleAtRef[1];
4138
+ if (this.isWholeUpstreamReference(expr, upstream)) {
4139
+ if (topLevelKey) {
4140
+ const existing = this.lookupCaseInsensitive(upstream, topLevelKey);
4141
+ if (existing !== undefined) {
4142
+ return existing;
4143
+ }
4144
+ }
4145
+ return { ...upstream };
4146
+ }
4147
+ const resolved = this.resolveUpstreamPath(expr, upstream);
4148
+ if (resolved !== undefined) {
4149
+ return resolved;
4150
+ }
4151
+ if (topLevelKey) {
4152
+ const existing = this.lookupCaseInsensitive(upstream, topLevelKey);
4153
+ if (existing !== undefined) {
4154
+ return existing;
4155
+ }
4156
+ }
4157
+ return val;
4158
+ }
4159
+ if (val.includes('{{') && val.includes('}}')) {
4160
+ return val.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (fullMatch, expr) => {
4161
+ const resolved = this.resolveUpstreamPath(expr, upstream);
4162
+ if (resolved === undefined || resolved === null) {
4163
+ return fullMatch;
4164
+ }
4165
+ return typeof resolved === 'object' ? JSON.stringify(resolved) : String(resolved);
4166
+ });
4167
+ }
4168
+ return val;
4169
+ }
4170
+ if (Array.isArray(val)) {
4171
+ return val.map((item) => this.resolveInputValue(item, upstream, false));
4172
+ }
4173
+ if (val && typeof val === 'object') {
4174
+ const out = {};
4175
+ for (const [k, v] of Object.entries(val)) {
4176
+ out[k] = this.resolveInputValue(v, upstream, false, isRootObject ? k : undefined);
4177
+ }
4178
+ return out;
4179
+ }
4180
+ return val;
4181
+ }
4182
+ /**
4183
+ * Returns true when `rawExpr` refers to an entire upstream task output object
4184
+ * (e.g. `@task1.output`, `{{query_sales.output}}`, `{{output.task1}}`, `{{output}}`)
4185
+ * rather than a specific property path within the output.
4186
+ */
4187
+ isWholeUpstreamReference(rawExpr, upstream) {
4188
+ const normalized = rawExpr.trim().replace(/^@/, '');
4189
+ if (/^(?:[a-zA-Z0-9_-]+\.)?(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload)$/i.test(normalized)) {
4190
+ return true;
4191
+ }
4192
+ const m = normalized.match(/^(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload|result)\.([a-zA-Z0-9_-]+)$/i);
4193
+ if (m) {
4194
+ const key = m[1];
4195
+ if (this.lookupCaseInsensitive(upstream, key) === undefined &&
4196
+ !(upstream.results && typeof upstream.results === 'object' && !Array.isArray(upstream.results) &&
4197
+ this.lookupCaseInsensitive(upstream.results, key) !== undefined)) {
4198
+ return true;
4199
+ }
4200
+ }
4201
+ return false;
4202
+ }
4203
+ resolveUpstreamPath(rawExpr, upstream) {
4204
+ let normalized = rawExpr.trim().replace(/^@/, '');
4205
+ if (this.isWholeUpstreamReference(normalized, upstream)) {
4206
+ return { ...upstream };
4207
+ }
4208
+ const taskOutputFieldMatch = normalized.match(/^(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload|result)\.[a-zA-Z0-9_-]+\.(?:output|payload)\.(.+)$/i) ??
4209
+ normalized.match(/^[a-zA-Z0-9_-]+\.(?:output|payload)\.(.+)$/i);
4210
+ if (taskOutputFieldMatch) {
4211
+ normalized = taskOutputFieldMatch[1];
4212
+ }
4213
+ else {
4214
+ normalized = normalized.replace(/^(?:output|outputs|outputFromTask|taskOutput|taskOutputs|payload|result)\./i, '');
4215
+ }
4216
+ const direct = this.walkObjectPath(upstream, normalized);
4217
+ if (direct !== undefined) {
4218
+ return direct;
4219
+ }
4220
+ if (upstream.results && typeof upstream.results === 'object' && !Array.isArray(upstream.results)) {
4221
+ const fromResults = this.walkObjectPath(upstream.results, normalized);
4222
+ if (fromResults !== undefined) {
4223
+ return fromResults;
4224
+ }
4225
+ }
4226
+ // Fallback when the first segment is a symbolic task ID (e.g. `output.create_report_doc.handle` or `outputFromTask.code1.summary`)
4227
+ const firstDot = normalized.indexOf('.');
4228
+ if (firstDot > 0) {
4229
+ const firstSeg = normalized.slice(0, firstDot);
4230
+ const rest = normalized.slice(firstDot + 1);
4231
+ if (this.lookupCaseInsensitive(upstream, firstSeg) === undefined) {
4232
+ const viaRest = this.walkObjectPath(upstream, rest);
4233
+ if (viaRest !== undefined) {
4234
+ return viaRest;
4235
+ }
4236
+ if (upstream.results && typeof upstream.results === 'object' && !Array.isArray(upstream.results)) {
4237
+ const viaResultsRest = this.walkObjectPath(upstream.results, rest);
4238
+ if (viaResultsRest !== undefined) {
4239
+ return viaResultsRest;
4240
+ }
4241
+ }
4242
+ }
4243
+ }
4244
+ return undefined;
4245
+ }
4246
+ walkObjectPath(root, dotPath) {
4247
+ const segments = dotPath.split('.').map((s) => s.trim()).filter(Boolean);
4248
+ let current = root;
4249
+ for (const seg of segments) {
4250
+ if (!current || typeof current !== 'object' || Array.isArray(current)) {
4251
+ return undefined;
4252
+ }
4253
+ const arrayMatch = seg.match(/^([^[\]]+)\[(\d+)\]$/);
4254
+ if (arrayMatch) {
4255
+ const arrVal = this.lookupCaseInsensitive(current, arrayMatch[1]);
4256
+ if (!Array.isArray(arrVal)) {
4257
+ return undefined;
4258
+ }
4259
+ current = arrVal[Number(arrayMatch[2])];
4260
+ continue;
4261
+ }
4262
+ current = this.lookupCaseInsensitive(current, seg);
4263
+ }
4264
+ return current;
4265
+ }
4266
+ lookupCaseInsensitive(obj, key) {
4267
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
4268
+ return obj[key];
4269
+ }
4270
+ const lower = key.toLowerCase();
4271
+ for (const [k, v] of Object.entries(obj)) {
4272
+ if (k.toLowerCase() === lower) {
4273
+ return v;
4274
+ }
4275
+ }
4276
+ return undefined;
4277
+ }
3904
4278
  }
3905
4279
  //# sourceMappingURL=TaskGraphDispatcher.js.map