@memberjunction/task-graph 6.2.0-edge.0 → 6.2.0-edge.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/AIDecisionTaskRunner.d.ts +7 -0
  2. package/dist/AIDecisionTaskRunner.d.ts.map +1 -0
  3. package/dist/AIDecisionTaskRunner.js +57 -0
  4. package/dist/AIDecisionTaskRunner.js.map +1 -0
  5. package/dist/TaskClaimStore.d.ts +4 -3
  6. package/dist/TaskClaimStore.d.ts.map +1 -1
  7. package/dist/TaskClaimStore.js +3 -2
  8. package/dist/TaskClaimStore.js.map +1 -1
  9. package/dist/TaskGraphDispatcher.d.ts +89 -2
  10. package/dist/TaskGraphDispatcher.d.ts.map +1 -1
  11. package/dist/TaskGraphDispatcher.js +319 -29
  12. package/dist/TaskGraphDispatcher.js.map +1 -1
  13. package/dist/TaskGraphService.d.ts +56 -3
  14. package/dist/TaskGraphService.d.ts.map +1 -1
  15. package/dist/TaskGraphService.js +121 -17
  16. package/dist/TaskGraphService.js.map +1 -1
  17. package/dist/condition-gate.d.ts +17 -2
  18. package/dist/condition-gate.d.ts.map +1 -1
  19. package/dist/condition-gate.js +25 -1
  20. package/dist/condition-gate.js.map +1 -1
  21. package/dist/decision-node.d.ts +150 -0
  22. package/dist/decision-node.d.ts.map +1 -0
  23. package/dist/decision-node.js +234 -0
  24. package/dist/decision-node.js.map +1 -0
  25. package/dist/index.d.ts +2 -0
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +2 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/operations/TaskGraphOperations.d.ts +4 -0
  30. package/dist/operations/TaskGraphOperations.d.ts.map +1 -1
  31. package/dist/operations/TaskGraphOperations.js +10 -2
  32. package/dist/operations/TaskGraphOperations.js.map +1 -1
  33. package/dist/task-predicates.d.ts +2 -0
  34. package/dist/task-predicates.d.ts.map +1 -1
  35. package/dist/task-predicates.js +5 -3
  36. package/dist/task-predicates.js.map +1 -1
  37. package/dist/types.d.ts +44 -0
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/types.js.map +1 -1
  40. package/package.json +11 -11
@@ -18,11 +18,13 @@
18
18
  *
19
19
  * @module @memberjunction/task-graph
20
20
  */
21
- import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveMappedInput, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, } from '@memberjunction/ai-core-plus';
21
+ import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveMappedInput, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, FinalizeAgentRunStep, InitAgentRunStep, DecisionReferencesIn, ResolveDecisionState, } from '@memberjunction/ai-core-plus';
22
22
  import { LogError, LogStatus, RunView } from '@memberjunction/core';
23
23
  import { ShutdownRegistry, UUIDsEqual } from '@memberjunction/global';
24
24
  import { TaskClaimStore, TERMINAL_PARENT_STATUSES, TERMINAL_PARENT_STATUS_SQL } from './TaskClaimStore.js';
25
- import { BuildConditionContext, DecideGate, IsBrokenGuard, ParseConditionOutput, } from './condition-gate.js';
25
+ import { BuildConditionContext, DecideGate, EvaluateCondition, IsBrokenGuard, ParseConditionOutput, } from './condition-gate.js';
26
+ import { BuildDecisionStepOutput, DecisionStepOutputAnswers, DecisionsPayloadConflict, FailedDecisionIDs, KeptDecisionAnswers, PassOverFailedDecisionPaths, QuestionsToAsk, ReadsFailedDecision, ReadDecisionStepConfiguration, ResolveGraphDecisions, StillHoldingDecisionOutput, } from './decision-node.js';
27
+ import { AIDecisionTaskRunner } from './AIDecisionTaskRunner.js';
26
28
  import { HumanTaskSQL, IsHumanTask } from './task-predicates.js';
27
29
  import { IsSettlementExpired, IsSubmittingRunReady, SelectUnsettledGraphIDs, SweepCutoff, UNSETTLED_SWEEP_WINDOW_HOURS, UNSETTLED_STARTUP_WINDOW_HOURS, } from './settlement-rescue.js';
28
30
  import { DispatcherConditionEvaluator } from './DispatcherConditionEvaluator.js';
@@ -76,6 +78,40 @@ function asRunQueryProvider(provider) {
76
78
  const candidate = provider;
77
79
  return typeof candidate.RunQuery === 'function' ? candidate : undefined;
78
80
  }
81
+ /**
82
+ * True when a task's `InputPayload` is a well-formed name → value object, or absent entirely.
83
+ *
84
+ * A type predicate rather than a plain boolean check so `runTaskBody`'s `if (!isNameValuePayload(...))
85
+ * return ...` narrows `inputPayload` for the rest of the method — including the call into
86
+ * `mergedPayload` — instead of leaving it `unknown` and inviting a second, possibly-divergent
87
+ * array/scalar check downstream (MJ#4794 was exactly that: a shape decision duplicated in two
88
+ * places that disagreed).
89
+ */
90
+ function isNameValuePayload(inputPayload) {
91
+ return inputPayload == null || (typeof inputPayload === 'object' && !Array.isArray(inputPayload));
92
+ }
93
+ /**
94
+ * Parses a task's stored `InputPayload`, telling an ABSENT input apart from an UNREADABLE one.
95
+ *
96
+ * Both used to come out as `null`, and `null` is a legitimate "this node takes no input" — so a row
97
+ * whose payload could not be parsed ran with none of its inputs, the same silent outcome the shape
98
+ * guard in `runTaskBody` refuses for an array. A string that is not JSON reaches here through
99
+ * `TaskGraph.RetryTask` / `UpdateTaskInput`, which store a string payload verbatim.
100
+ */
101
+ export function ParseTaskInputPayload(taskID, raw) {
102
+ if (!raw) {
103
+ return { Payload: null };
104
+ }
105
+ try {
106
+ return { Payload: JSON.parse(raw) };
107
+ }
108
+ catch (e) {
109
+ return {
110
+ ErrorMessage: `Task ${taskID} has an InputPayload that is not valid JSON (${e instanceof Error ? e.message : String(e)}). ` +
111
+ `Its inputs cannot be mapped to parameters, so it was not run.`,
112
+ };
113
+ }
114
+ }
79
115
  import { IsReinvokeCapReached, MAX_REINVOKE_DEPTH, ParseTaskGraphParentMetadata, TASK_TYPE_NAME } from './TaskGraphService.js';
80
116
  import { DEFAULT_DISPATCHER_CONFIG, } from './types.js';
81
117
  /**
@@ -185,7 +221,13 @@ export class TaskGraphDispatcher {
185
221
  * Optional. Absent means this host cannot run prompt nodes; they stay Pending and visible
186
222
  * rather than being failed, for the same reason action nodes do.
187
223
  */
188
- promptRunner) {
224
+ promptRunner,
225
+ /**
226
+ * Answers Decision nodes. Defaults to {@link AIDecisionTaskRunner}, one `AIDecisionRunner`
227
+ * call per node, so every host that runs the dispatcher can run a Decision; supply one to
228
+ * decide differently, or to test without a model.
229
+ */
230
+ decisionRunner = new AIDecisionTaskRunner()) {
189
231
  this.providerFactory = providerFactory;
190
232
  this.agentRunner = agentRunner;
191
233
  this.contextUser = contextUser;
@@ -193,12 +235,22 @@ export class TaskGraphDispatcher {
193
235
  this.observer = observer;
194
236
  this.actionRunner = actionRunner;
195
237
  this.promptRunner = promptRunner;
238
+ this.decisionRunner = decisionRunner;
196
239
  /**
197
240
  * Edges already reported as unevaluable, so the report is once per transition and not once per
198
241
  * poll. Per-instance and in-memory by design: a restart re-reports, which is the right amount of
199
242
  * noise for a condition that is still broken after a restart.
200
243
  */
201
244
  this.reportedUnevaluableConditions = new Set();
245
+ /**
246
+ * Decision run-step logs in flight, by agent run.
247
+ *
248
+ * A logged step takes the run's next step number, which is read and then written, so two
249
+ * Decision steps logging on one run at once would take the same number. Chaining them per run
250
+ * closes that on this instance. Instances do not share it; the column has no unique constraint,
251
+ * so a collision across instances only misorders the run's timeline.
252
+ */
253
+ this.runStepLogs = new Map();
202
254
  /** Resolved once it EXISTS; null while it does not, so a fresh install is not cached blind. */
203
255
  this.cachedWorkflowTaskTypeID = null;
204
256
  /**
@@ -859,17 +911,18 @@ export class TaskGraphDispatcher {
859
911
  ClaimExpiresAt: new Date(Date.now() + this.config.ClaimTTLSeconds * 1000).toISOString(),
860
912
  });
861
913
  const dependencyOutputs = await this.loadDependencyOutputs(provider, taskID);
862
- let inputPayload = null;
863
- if (task.InputPayload) {
864
- try {
865
- inputPayload = JSON.parse(task.InputPayload);
866
- }
867
- catch (e) {
868
- LogError(`[TaskGraphDispatcher] Task ${taskID} has malformed InputPayload: ${e}`);
869
- }
914
+ const parsed = ParseTaskInputPayload(taskID, task.InputPayload);
915
+ let result;
916
+ if ('ErrorMessage' in parsed) {
917
+ // Refused through the normal Failed path below, like runTaskBody's shape guard — never
918
+ // run as though the node had no input.
919
+ LogError(`[TaskGraphDispatcher] ${parsed.ErrorMessage}`);
920
+ result = { Success: false, ErrorMessage: parsed.ErrorMessage };
921
+ }
922
+ else {
923
+ const onProgress = this.nodeProgressEmitter(graphID, ownerUserID, taskID, task.Name);
924
+ result = await this.runTaskBody(task, provider, parsed.Payload, dependencyOutputs, onProgress);
870
925
  }
871
- const onProgress = this.nodeProgressEmitter(graphID, ownerUserID, taskID, task.Name);
872
- const result = await this.runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress);
873
926
  // ONLY THE CONFIRMED OWNER MUTATES THE GRAPH (R2-10).
874
927
  //
875
928
  // The early-finish skips used to run BEFORE this, so a lapsed claim produced the worst
@@ -2015,7 +2068,12 @@ export class TaskGraphDispatcher {
2015
2068
  // they cleared. Without a notification here a workflow simply stops, waiting on
2016
2069
  // someone who was never told. That silent stall is the failure mode this exists to
2017
2070
  // prevent, so it happens on the eligibility check rather than at submission.
2018
- if (entity.ActionID) {
2071
+ if (entity.StepType === 'Decision') {
2072
+ // Tested before the key columns: a Decision carries its decision prompt in
2073
+ // PromptID, but it runs on the decision runner, which every dispatcher has — so
2074
+ // a host with no PROMPT runner must not leave it Pending.
2075
+ }
2076
+ else if (entity.ActionID) {
2019
2077
  // An action node this host has no runner for is left Pending rather than
2020
2078
  // claimed. Claiming it would take ownership of work this process cannot do, and
2021
2079
  // the claim would then have to expire before any host that CAN do it gets a
@@ -2096,6 +2154,9 @@ export class TaskGraphDispatcher {
2096
2154
  canActOn(entity) {
2097
2155
  if (this.inFlight.has(entity.ID))
2098
2156
  return false;
2157
+ // Before the PromptID test, for the reason given in `findClaimableTasks`.
2158
+ if (entity.StepType === 'Decision')
2159
+ return true;
2099
2160
  if (entity.ActionID)
2100
2161
  return !!this.actionRunner;
2101
2162
  if (entity.PromptID)
@@ -2492,6 +2553,10 @@ export class TaskGraphDispatcher {
2492
2553
  Data: parentMeta.invocation?.data,
2493
2554
  Context: parentMeta.invocation?.context,
2494
2555
  };
2556
+ // The graph's Decision answers, read ONCE from the Decision steps' own rows. Every condition
2557
+ // this pass evaluates sees the same answers, and one reading an answer that is not settled
2558
+ // holds instead of reading false (plan 4.5).
2559
+ const decisions = ResolveGraphDecisions(children);
2495
2560
  // Conditional edges are resolved HERE, before eligibility runs, by dropping edges whose
2496
2561
  // condition does not hold. Expressing it as edge removal rather than as a second rule inside
2497
2562
  // the eligibility algorithm is what keeps one definition of "ready": a task with no live
@@ -2522,7 +2587,16 @@ export class TaskGraphDispatcher {
2522
2587
  const decidingStatuses = failureSemantics === 'edges'
2523
2588
  ? new Set(['Complete', 'Failed'])
2524
2589
  : new Set(['Complete']);
2525
- const resolution = ResolveExclusiveGroups(exclusive.map((d) => ({
2590
+ // A path reading a decision whose call FAILED is passed over when another path of its fork
2591
+ // is satisfied: that path is the author's recovery route, taken whatever its rank, exactly
2592
+ // as the in-run walker takes it. With no such path the fork still holds, so a Retry of the
2593
+ // failed Decision step can route it.
2594
+ const failedDecisions = FailedDecisionIDs(children);
2595
+ const conditionByEdge = new Map(exclusive.map((d) => [d.ID, d.Condition ?? '']));
2596
+ // Why each exclusive edge that cannot be evaluated is held, by edge — reported below, once the
2597
+ // resolution says whether its fork is actually held.
2598
+ const exclusiveHoldReasons = new Map();
2599
+ const resolution = ResolveExclusiveGroups(PassOverFailedDecisionPaths(exclusive.map((d) => ({
2526
2600
  id: d.ID,
2527
2601
  taskId: d.TaskID,
2528
2602
  dependsOnTaskId: d.DependsOnTaskID,
@@ -2530,8 +2604,8 @@ export class TaskGraphDispatcher {
2530
2604
  originStatus: (entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending'),
2531
2605
  priority: d.Priority ?? 0,
2532
2606
  sequence: d.Sequence ?? 0,
2533
- conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, debug),
2534
- })),
2607
+ conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, decisions, debug, exclusiveHoldReasons),
2608
+ })), (edge) => ReadsFailedDecision(conditionByEdge.get(edge.id) ?? '', failedDecisions)),
2535
2609
  // WHICH STATUSES MAY DECIDE — the graph's own failure dialect, not a constant.
2536
2610
  //
2537
2611
  // Under `'edges'`, a flow's failure handling IS its outgoing edges, so a Failed origin
@@ -2556,7 +2630,7 @@ export class TaskGraphDispatcher {
2556
2630
  const gateDecisions = [];
2557
2631
  for (const d of ordinary) {
2558
2632
  if (d.Condition?.trim()) {
2559
- const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, debug);
2633
+ const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, decisions, debug);
2560
2634
  if (decision.decided) {
2561
2635
  gateDecisions.push({
2562
2636
  edge: d,
@@ -2621,13 +2695,19 @@ export class TaskGraphDispatcher {
2621
2695
  const originStatus = entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending';
2622
2696
  if (!decidingStatuses.has(originStatus) && !OverrideVerdictFor(debug ?? {}, d.ID))
2623
2697
  continue;
2698
+ const held = !loserEdgeIDs.has(d.ID) && exclusiveHolds.has(d.TaskID);
2699
+ // The edge that holds its fork says why — below its confidence, from a failed call — and
2700
+ // is logged once, as an ordinary edge is. Its siblings hold only because it does.
2701
+ const holdReason = held ? exclusiveHoldReasons.get(d.ID) : undefined;
2702
+ if (holdReason)
2703
+ this.logUnevaluableConditionOnce(d, holdReason);
2624
2704
  gateDecisions.push({
2625
2705
  edge: d,
2626
2706
  verdict: loserEdgeIDs.has(d.ID)
2627
2707
  ? 'notTaken'
2628
- : exclusiveHolds.has(d.TaskID) ? 'held' : 'satisfied',
2629
- reason: exclusiveHolds.has(d.TaskID)
2630
- ? 'this fork is undecided — a path in its group cannot be answered yet'
2708
+ : held ? 'held' : 'satisfied',
2709
+ reason: held
2710
+ ? holdReason ?? 'this fork is undecided — a path in its group cannot be answered yet'
2631
2711
  : undefined,
2632
2712
  });
2633
2713
  }
@@ -2687,10 +2767,15 @@ export class TaskGraphDispatcher {
2687
2767
  if (this.reportedUnevaluableConditions.has(key))
2688
2768
  return;
2689
2769
  this.reportedUnevaluableConditions.add(key);
2770
+ // A hold on a decision has a way out that a broken condition does not: ask again.
2771
+ const readsDecision = DecisionReferencesIn(dep.Condition ?? '').References.length > 0;
2690
2772
  LogError(`[TaskGraphDispatcher] Dependency ${dep.ID} has an unevaluable condition ` +
2691
2773
  `(${errorMessage}); condition text: ${JSON.stringify(dep.Condition)}. ` +
2692
2774
  `Task ${dep.TaskID} is HELD — it will not run and will not be skipped until the ` +
2693
- `condition can be evaluated. The graph reports as stalled while this holds.`);
2775
+ `condition can be evaluated. The graph reports as stalled while this holds.` +
2776
+ (readsDecision
2777
+ ? ' Retrying the Decision step it reads asks the questions it is holding again; an edge override answers the condition by hand.'
2778
+ : ''));
2694
2779
  }
2695
2780
  /**
2696
2781
  * Decides whether a conditional dependency edge is live.
@@ -2699,7 +2784,7 @@ export class TaskGraphDispatcher {
2699
2784
  * only information a runtime graph has to branch on. Returns `'drop'` only on a definite false;
2700
2785
  * an unevaluable condition keeps the edge for the reason stated at the call site.
2701
2786
  */
2702
- evaluateEdgeCondition(dep, entityById, failureSemantics, invocation, debug) {
2787
+ evaluateEdgeCondition(dep, entityById, failureSemantics, invocation, decisions, debug) {
2703
2788
  // An operator's override answers the edge BEFORE the condition is consulted — an override
2704
2789
  // exists precisely because the condition cannot be answered (or answered wrongly), so
2705
2790
  // evaluating first would re-produce the hold the override exists to end.
@@ -2725,7 +2810,9 @@ export class TaskGraphDispatcher {
2725
2810
  let evaluated = false;
2726
2811
  const outcome = DecideGate(upstream.Status, failureSemantics, () => {
2727
2812
  evaluated = true;
2728
- const result = this.conditionEvaluator.Evaluate(dep.Condition, BuildConditionContext(upstream, ParseConditionOutput(upstream.OutputPayload), invocation));
2813
+ // A condition reading an unsettled decision is held here, before evaluation could read
2814
+ // its absence as a confident false.
2815
+ const result = EvaluateCondition(dep.Condition, BuildConditionContext(upstream, ParseConditionOutput(upstream.OutputPayload), invocation, decisions.Answers), decisions, (condition, context) => this.conditionEvaluator.Evaluate(condition, context));
2729
2816
  if (!result.Success)
2730
2817
  unevaluableError = result.ErrorMessage;
2731
2818
  return result;
@@ -2756,7 +2843,7 @@ export class TaskGraphDispatcher {
2756
2843
  * the branch, the second holds the whole group. The generic keep/drop path cannot express that
2757
2844
  * difference, which is why exclusive edges take this route instead.
2758
2845
  */
2759
- evaluateExclusiveCondition(dep, entityById, invocation, debug) {
2846
+ evaluateExclusiveCondition(dep, entityById, invocation, decisions, debug, holdReasons) {
2760
2847
  // Same override-first rule as ordinary edges — see evaluateEdgeCondition.
2761
2848
  const override = OverrideVerdictFor(debug ?? {}, dep.ID);
2762
2849
  if (override)
@@ -2766,18 +2853,26 @@ export class TaskGraphDispatcher {
2766
2853
  const upstream = entityById.get(dep.DependsOnTaskID);
2767
2854
  if (!upstream)
2768
2855
  return 'unevaluable';
2769
- const result = this.conditionEvaluator.Evaluate(dep.Condition,
2856
+ const result = EvaluateCondition(dep.Condition,
2770
2857
  // The invocation envelope rides the EXCLUSIVE dialect too. R3-3 threaded it into the
2771
2858
  // ordinary path; a flow's XOR branch reading `data.userApproval` is the same documented
2772
2859
  // condition on a different edge kind, and `BuildConditionContext`'s defaulted parameter
2773
2860
  // made omitting it here silently evaluate those roots against nothing.
2774
- BuildConditionContext(upstream, ParseConditionOutput(upstream.OutputPayload), invocation));
2861
+ BuildConditionContext(upstream, ParseConditionOutput(upstream.OutputPayload), invocation, decisions.Answers), decisions, (condition, context) => this.conditionEvaluator.Evaluate(condition, context));
2862
+ // A fork on a judgment that is not settled — below its confidence, or from a failed call —
2863
+ // holds the whole group rather than guessing a branch (plan 4.5). The reason is kept for the
2864
+ // caller to report, as an ordinary edge's is.
2865
+ const unevaluable = result.Unevaluable || (!result.Success && IsBrokenGuard(result.ErrorMessage));
2866
+ if (unevaluable && result.ErrorMessage)
2867
+ holdReasons?.set(dep.ID, result.ErrorMessage);
2868
+ if (unevaluable)
2869
+ return 'unevaluable';
2775
2870
  // SAME CLASSIFICATION AS THE ORDINARY DIALECT (R2-3). The null-safe envelope already makes
2776
2871
  // one level of absence read as false here, but a deeper absent chain still throws — and
2777
2872
  // calling that 'unevaluable' would hold the whole group forever on a terminal origin, while
2778
2873
  // `DecideGate` would have dropped the identical condition. Two dialects, one question.
2779
2874
  if (!result.Success)
2780
- return IsBrokenGuard(result.ErrorMessage) ? 'unevaluable' : 'unsatisfied';
2875
+ return 'unsatisfied';
2781
2876
  return result.Value ? 'satisfied' : 'unsatisfied';
2782
2877
  }
2783
2878
  /**
@@ -2855,6 +2950,21 @@ export class TaskGraphDispatcher {
2855
2950
  * no agent run to point at, because its forensics live in `ActionExecutionLog` instead.
2856
2951
  */
2857
2952
  async runTaskBody(task, provider, inputPayload, dependencyOutputs, onProgress) {
2953
+ // A node's input is a name → value object (`TaskGraphSpecNode.inputPayload: Record<string, unknown>`).
2954
+ // `mergedPayload` below only merges objects, so anything else would be dropped without a word
2955
+ // and the step would run with none of its inputs — how durable entity actions ran before MJ#4794
2956
+ // (their redacted params were stored as an array). Rows written that way may still be queued, so
2957
+ // refuse them loudly rather than run them empty. This is also the only place that narrows
2958
+ // `inputPayload`'s type: everything downstream (`mergedPayload` included) receives the narrowed
2959
+ // `Record<string, unknown> | null`, so the array/scalar case cannot recur as a second, divergent
2960
+ // check further down the call chain.
2961
+ if (!isNameValuePayload(inputPayload)) {
2962
+ const found = Array.isArray(inputPayload) ? 'an array' : `a ${typeof inputPayload}`;
2963
+ const message = `Task ${task.ID} has an InputPayload that is ${found}; expected a name → value object. ` +
2964
+ `Its inputs cannot be mapped to parameters, so it was not run.`;
2965
+ LogError(`[TaskGraphDispatcher] ${message}`);
2966
+ return { Success: false, ErrorMessage: message };
2967
+ }
2858
2968
  const payload = this.mergedPayload(inputPayload, dependencyOutputs);
2859
2969
  const config = task.ConfigurationObject;
2860
2970
  // A loop's own step type decides how many times its body runs; the body itself is dispatched
@@ -2862,6 +2972,12 @@ export class TaskGraphDispatcher {
2862
2972
  if (task.StepType === 'ForEach' || task.StepType === 'While') {
2863
2973
  return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs), PayloadAtStart: payload };
2864
2974
  }
2975
+ // Routed on StepType before the mappings below: a Decision reads its state from the merged
2976
+ // payload by path and writes its answers back under `decisions`, so it has no mapping of its
2977
+ // own. And it carries a PromptID, so the Prompt branch would otherwise take it.
2978
+ if (task.StepType === 'Decision') {
2979
+ return { ...await this.runDecisionNode(task, provider, payload, onProgress), PayloadAtStart: payload };
2980
+ }
2865
2981
  const { params, errors } = BuildMappedInput(config?.inputMapping, { payload });
2866
2982
  for (const e of errors)
2867
2983
  LogError(`[TaskGraphDispatcher] Task ${task.ID}: ${e}`);
@@ -3209,6 +3325,175 @@ export class TaskGraphDispatcher {
3209
3325
  OnProgress: onProgress,
3210
3326
  });
3211
3327
  }
3328
+ /**
3329
+ * Runs a Decision step: ONE call that answers every question the node asks, about one state.
3330
+ *
3331
+ * The answers land in the step's output under `decisions.<tempId>`, where later steps can read
3332
+ * them, and the edges that route on them read the same answers from this row (see
3333
+ * `ResolveGraphDecisions`). A call that fails writes no answers and fails the step: under
3334
+ * `'block'` its dependents block, and under `'edges'` every condition that reads it holds. It
3335
+ * never reads as `false`.
3336
+ *
3337
+ * **A retry asks only what the step is holding.** A step retried from `Complete` keeps the usable
3338
+ * answers it already gave (`KeptDecisionAnswers`), because the graph has already acted on them,
3339
+ * and the call asks only the rest. If that call fails, or cannot be made, the step stays
3340
+ * `Complete` with the same usable answers, and the questions it asked again hold with the reason.
3341
+ */
3342
+ async runDecisionNode(task, provider, payload, onProgress) {
3343
+ const config = ReadDecisionStepConfiguration(task.Configuration);
3344
+ if (!config)
3345
+ return this.decisionNotAsked(task, payload, 'it has no decision settings, so there is nothing to ask');
3346
+ const kept = KeptDecisionAnswers(task);
3347
+ const toAsk = QuestionsToAsk(config.questions, kept);
3348
+ const notAsked = (reason) => this.decisionNotAsked(task, payload, reason, { config, kept });
3349
+ if (!task.PromptID)
3350
+ return notAsked('it has no decision prompt to run on');
3351
+ const state = ResolveDecisionState(config.state, payload);
3352
+ if ('ErrorMessage' in state)
3353
+ return notAsked(state.ErrorMessage);
3354
+ // Checked before the call, not after: a step that cannot write its answers without destroying
3355
+ // data should not pay for the answers first.
3356
+ const conflict = DecisionsPayloadConflict(payload);
3357
+ if (conflict)
3358
+ return notAsked(conflict);
3359
+ const startedAt = new Date();
3360
+ const result = await this.decisionRunner.RunDecisionForTask({
3361
+ TaskID: task.ID,
3362
+ PromptID: task.PromptID,
3363
+ State: state.State,
3364
+ Questions: toAsk,
3365
+ Provider: provider,
3366
+ ContextUser: this.contextUser,
3367
+ OnProgress: onProgress,
3368
+ });
3369
+ await this.logDecisionStep(provider, task, config, toAsk, state.State, result, startedAt);
3370
+ if (!result.Success || !result.Answers) {
3371
+ const message = result.ErrorMessage || `Decision "${task.Name}" returned no answers.`;
3372
+ if (Object.keys(kept).length > 0)
3373
+ return this.decisionStillHolding(task, config, kept, message, result.PromptRunID);
3374
+ return {
3375
+ Success: false,
3376
+ AgentRunID: null,
3377
+ ErrorMessage: message,
3378
+ // The payload passes through WITHOUT answers, so nothing downstream can mistake a
3379
+ // failed decision for one that answered.
3380
+ Output: payload,
3381
+ // A failed call can still have cost tokens; the rollup reaches it through this.
3382
+ PromptRunID: result.PromptRunID,
3383
+ };
3384
+ }
3385
+ // A kept answer is never replaced, whatever the call returned for its question.
3386
+ const answers = { ...result.Answers, ...kept };
3387
+ return {
3388
+ Success: true,
3389
+ AgentRunID: null,
3390
+ // Only the answers a condition may act on; each other one is replaced by why it is held.
3391
+ Output: BuildDecisionStepOutput(payload, config.nodeId, DecisionStepOutputAnswers(task.Name, config.questions, answers)),
3392
+ PromptRunID: result.PromptRunID,
3393
+ };
3394
+ }
3395
+ /**
3396
+ * A Decision step that could not be asked — failed with the reason, its input passed through.
3397
+ * A retried step with answers to keep stays `Complete` and holds instead (see `runDecisionNode`).
3398
+ */
3399
+ decisionNotAsked(task, payload, reason, retry) {
3400
+ if (retry && Object.keys(retry.kept).length > 0)
3401
+ return this.decisionStillHolding(task, retry.config, retry.kept, reason);
3402
+ return { Success: false, AgentRunID: null, ErrorMessage: `Decision "${task.Name}" was not asked: ${reason}.`, Output: payload };
3403
+ }
3404
+ /**
3405
+ * A retried Decision step that could not answer again. It keeps its usable answers and stays
3406
+ * `Complete`, and each question it asked again holds with `reason`, so it can be retried again.
3407
+ */
3408
+ decisionStillHolding(task, config, kept, reason, promptRunID) {
3409
+ LogError(`[TaskGraphDispatcher] Decision "${task.Name}" (${task.ID}) was retried and could not answer again: ${reason}. ` +
3410
+ 'It keeps the answers it already gave and still holds the rest; retry it again.');
3411
+ return {
3412
+ Success: true,
3413
+ AgentRunID: null,
3414
+ Output: StillHoldingDecisionOutput(task.OutputPayload, task.Name, config.nodeId, config.questions, kept, reason),
3415
+ PromptRunID: promptRunID,
3416
+ };
3417
+ }
3418
+ /**
3419
+ * Records a Decision step's call on the agent run that submitted the graph, as an
3420
+ * `AIAgentRunStep` with `StepType 'Decision'`.
3421
+ *
3422
+ * **`'Decision'` means exactly one typed decision call**: a fixed set of Likelihood, Choice or
3423
+ * Score questions answered about one state. `TargetID` is the decision prompt, `TargetLogID` the
3424
+ * call's `MJ: AI Prompt Runs` row, `InputData` the state and the questions asked, and
3425
+ * `OutputData` the answers. Some older writers use the value loosely for bookkeeping; this is the
3426
+ * meaning new code writes (see `TaskGraphNodeConfigMap['Decision']`). A retry asks only the
3427
+ * questions the step was holding, so its step lists only those.
3428
+ *
3429
+ * A graph no run submitted — a schedule, MCP, a person — has no run to log on; the call is still
3430
+ * recorded in its prompt run, which the task points at. Observability only: a failure to log is
3431
+ * reported, and the decision stands.
3432
+ */
3433
+ async logDecisionStep(provider, task, config, asked, state, result, startedAt) {
3434
+ try {
3435
+ const { SubmittingAgentRunID: agentRunID } = await this.graphContext(provider, task);
3436
+ if (!agentRunID)
3437
+ return;
3438
+ // The number is read and the step saved as one unit per run, so two Decision steps
3439
+ // logging on the same run cannot take the same number.
3440
+ await this.oneRunStepLogAtATime(agentRunID, async () => {
3441
+ const step = await provider.GetEntityObject('MJ: AI Agent Run Steps', this.contextUser);
3442
+ step.NewRecord();
3443
+ InitAgentRunStep(step, {
3444
+ AgentRunID: agentRunID,
3445
+ StepNumber: await this.nextRunStepNumber(provider, agentRunID),
3446
+ StepType: 'Decision',
3447
+ StepName: `Decision: ${task.Name}`,
3448
+ TargetID: task.PromptID,
3449
+ InputData: JSON.stringify({ taskID: task.ID, decision: config.nodeId, state, questions: asked }),
3450
+ });
3451
+ step.StartedAt = startedAt;
3452
+ FinalizeAgentRunStep(step, {
3453
+ success: result.Success,
3454
+ errorMessage: result.ErrorMessage,
3455
+ targetLogID: result.PromptRunID,
3456
+ outputData: { answers: result.Answers ?? {} },
3457
+ });
3458
+ if (!(await step.Save())) {
3459
+ LogError(`[TaskGraphDispatcher] Could not log the Decision step for task ${task.ID}: ${step.LatestResult?.CompleteMessage ?? 'unknown error'}`);
3460
+ }
3461
+ });
3462
+ }
3463
+ catch (e) {
3464
+ LogError(`[TaskGraphDispatcher] Could not log the Decision step for task ${task.ID}: ${e instanceof Error ? e.message : String(e)}`);
3465
+ }
3466
+ }
3467
+ /**
3468
+ * Runs `write` after every earlier run-step log for the same agent run has finished, on this
3469
+ * instance. A failed write does not hold up the next one; its error still reaches the caller.
3470
+ */
3471
+ async oneRunStepLogAtATime(agentRunID, write) {
3472
+ const key = agentRunID.toLowerCase();
3473
+ const current = (this.runStepLogs.get(key) ?? Promise.resolve()).then(write);
3474
+ const settled = current.catch(() => undefined);
3475
+ this.runStepLogs.set(key, settled);
3476
+ try {
3477
+ await current;
3478
+ }
3479
+ finally {
3480
+ if (this.runStepLogs.get(key) === settled)
3481
+ this.runStepLogs.delete(key);
3482
+ }
3483
+ }
3484
+ /** One past a run's highest step number, so a step logged from here sorts after the run's own. */
3485
+ async nextRunStepNumber(provider, agentRunID) {
3486
+ const result = await RunView.FromMetadataProvider(provider).RunView({
3487
+ EntityName: 'MJ: AI Agent Run Steps',
3488
+ ExtraFilter: `AgentRunID='${agentRunID}'`,
3489
+ Fields: ['StepNumber'],
3490
+ OrderBy: 'StepNumber DESC',
3491
+ MaxRows: 1,
3492
+ ResultType: 'simple',
3493
+ BypassCache: true,
3494
+ }, this.contextUser);
3495
+ return (result.Success ? result.Results?.[0]?.StepNumber ?? 0 : 0) + 1;
3496
+ }
3212
3497
  /**
3213
3498
  * Leaves exactly one open request standing for a task, withdrawing any others.
3214
3499
  *
@@ -3584,6 +3869,11 @@ export class TaskGraphDispatcher {
3584
3869
  * than the flow it was compiled from. Merging in dependency order restores the accumulation.
3585
3870
  *
3586
3871
  * Later prerequisites win on a key collision, matching a flow's own last-write-wins behaviour.
3872
+ *
3873
+ * `inputPayload` arrives pre-narrowed: `runTaskBody`'s guard is the only place that decides
3874
+ * whether it is a name → value object, so this method trusts that decision rather than
3875
+ * re-checking it. `dependencyOutputs` is a separate input with no equivalent guard upstream, so
3876
+ * its per-entry object/array check stays here.
3587
3877
  */
3588
3878
  mergedPayload(inputPayload, dependencyOutputs) {
3589
3879
  const merged = {};
@@ -3592,7 +3882,7 @@ export class TaskGraphDispatcher {
3592
3882
  Object.assign(merged, output);
3593
3883
  }
3594
3884
  }
3595
- if (inputPayload && typeof inputPayload === 'object' && !Array.isArray(inputPayload)) {
3885
+ if (inputPayload) {
3596
3886
  Object.assign(merged, inputPayload);
3597
3887
  }
3598
3888
  return merged;