@memberjunction/task-graph 6.2.0-edge.1 → 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 (36) 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 +71 -2
  10. package/dist/TaskGraphDispatcher.d.ts.map +1 -1
  11. package/dist/TaskGraphDispatcher.js +253 -18
  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/types.d.ts +44 -0
  34. package/dist/types.d.ts.map +1 -1
  35. package/dist/types.js.map +1 -1
  36. 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';
@@ -219,7 +221,13 @@ export class TaskGraphDispatcher {
219
221
  * Optional. Absent means this host cannot run prompt nodes; they stay Pending and visible
220
222
  * rather than being failed, for the same reason action nodes do.
221
223
  */
222
- 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()) {
223
231
  this.providerFactory = providerFactory;
224
232
  this.agentRunner = agentRunner;
225
233
  this.contextUser = contextUser;
@@ -227,12 +235,22 @@ export class TaskGraphDispatcher {
227
235
  this.observer = observer;
228
236
  this.actionRunner = actionRunner;
229
237
  this.promptRunner = promptRunner;
238
+ this.decisionRunner = decisionRunner;
230
239
  /**
231
240
  * Edges already reported as unevaluable, so the report is once per transition and not once per
232
241
  * poll. Per-instance and in-memory by design: a restart re-reports, which is the right amount of
233
242
  * noise for a condition that is still broken after a restart.
234
243
  */
235
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();
236
254
  /** Resolved once it EXISTS; null while it does not, so a fresh install is not cached blind. */
237
255
  this.cachedWorkflowTaskTypeID = null;
238
256
  /**
@@ -2050,7 +2068,12 @@ export class TaskGraphDispatcher {
2050
2068
  // they cleared. Without a notification here a workflow simply stops, waiting on
2051
2069
  // someone who was never told. That silent stall is the failure mode this exists to
2052
2070
  // prevent, so it happens on the eligibility check rather than at submission.
2053
- 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) {
2054
2077
  // An action node this host has no runner for is left Pending rather than
2055
2078
  // claimed. Claiming it would take ownership of work this process cannot do, and
2056
2079
  // the claim would then have to expire before any host that CAN do it gets a
@@ -2131,6 +2154,9 @@ export class TaskGraphDispatcher {
2131
2154
  canActOn(entity) {
2132
2155
  if (this.inFlight.has(entity.ID))
2133
2156
  return false;
2157
+ // Before the PromptID test, for the reason given in `findClaimableTasks`.
2158
+ if (entity.StepType === 'Decision')
2159
+ return true;
2134
2160
  if (entity.ActionID)
2135
2161
  return !!this.actionRunner;
2136
2162
  if (entity.PromptID)
@@ -2527,6 +2553,10 @@ export class TaskGraphDispatcher {
2527
2553
  Data: parentMeta.invocation?.data,
2528
2554
  Context: parentMeta.invocation?.context,
2529
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);
2530
2560
  // Conditional edges are resolved HERE, before eligibility runs, by dropping edges whose
2531
2561
  // condition does not hold. Expressing it as edge removal rather than as a second rule inside
2532
2562
  // the eligibility algorithm is what keeps one definition of "ready": a task with no live
@@ -2557,7 +2587,16 @@ export class TaskGraphDispatcher {
2557
2587
  const decidingStatuses = failureSemantics === 'edges'
2558
2588
  ? new Set(['Complete', 'Failed'])
2559
2589
  : new Set(['Complete']);
2560
- 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) => ({
2561
2600
  id: d.ID,
2562
2601
  taskId: d.TaskID,
2563
2602
  dependsOnTaskId: d.DependsOnTaskID,
@@ -2565,8 +2604,8 @@ export class TaskGraphDispatcher {
2565
2604
  originStatus: (entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending'),
2566
2605
  priority: d.Priority ?? 0,
2567
2606
  sequence: d.Sequence ?? 0,
2568
- conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, debug),
2569
- })),
2607
+ conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, decisions, debug, exclusiveHoldReasons),
2608
+ })), (edge) => ReadsFailedDecision(conditionByEdge.get(edge.id) ?? '', failedDecisions)),
2570
2609
  // WHICH STATUSES MAY DECIDE — the graph's own failure dialect, not a constant.
2571
2610
  //
2572
2611
  // Under `'edges'`, a flow's failure handling IS its outgoing edges, so a Failed origin
@@ -2591,7 +2630,7 @@ export class TaskGraphDispatcher {
2591
2630
  const gateDecisions = [];
2592
2631
  for (const d of ordinary) {
2593
2632
  if (d.Condition?.trim()) {
2594
- const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, debug);
2633
+ const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, decisions, debug);
2595
2634
  if (decision.decided) {
2596
2635
  gateDecisions.push({
2597
2636
  edge: d,
@@ -2656,13 +2695,19 @@ export class TaskGraphDispatcher {
2656
2695
  const originStatus = entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending';
2657
2696
  if (!decidingStatuses.has(originStatus) && !OverrideVerdictFor(debug ?? {}, d.ID))
2658
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);
2659
2704
  gateDecisions.push({
2660
2705
  edge: d,
2661
2706
  verdict: loserEdgeIDs.has(d.ID)
2662
2707
  ? 'notTaken'
2663
- : exclusiveHolds.has(d.TaskID) ? 'held' : 'satisfied',
2664
- reason: exclusiveHolds.has(d.TaskID)
2665
- ? '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'
2666
2711
  : undefined,
2667
2712
  });
2668
2713
  }
@@ -2722,10 +2767,15 @@ export class TaskGraphDispatcher {
2722
2767
  if (this.reportedUnevaluableConditions.has(key))
2723
2768
  return;
2724
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;
2725
2772
  LogError(`[TaskGraphDispatcher] Dependency ${dep.ID} has an unevaluable condition ` +
2726
2773
  `(${errorMessage}); condition text: ${JSON.stringify(dep.Condition)}. ` +
2727
2774
  `Task ${dep.TaskID} is HELD — it will not run and will not be skipped until the ` +
2728
- `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
+ : ''));
2729
2779
  }
2730
2780
  /**
2731
2781
  * Decides whether a conditional dependency edge is live.
@@ -2734,7 +2784,7 @@ export class TaskGraphDispatcher {
2734
2784
  * only information a runtime graph has to branch on. Returns `'drop'` only on a definite false;
2735
2785
  * an unevaluable condition keeps the edge for the reason stated at the call site.
2736
2786
  */
2737
- evaluateEdgeCondition(dep, entityById, failureSemantics, invocation, debug) {
2787
+ evaluateEdgeCondition(dep, entityById, failureSemantics, invocation, decisions, debug) {
2738
2788
  // An operator's override answers the edge BEFORE the condition is consulted — an override
2739
2789
  // exists precisely because the condition cannot be answered (or answered wrongly), so
2740
2790
  // evaluating first would re-produce the hold the override exists to end.
@@ -2760,7 +2810,9 @@ export class TaskGraphDispatcher {
2760
2810
  let evaluated = false;
2761
2811
  const outcome = DecideGate(upstream.Status, failureSemantics, () => {
2762
2812
  evaluated = true;
2763
- 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));
2764
2816
  if (!result.Success)
2765
2817
  unevaluableError = result.ErrorMessage;
2766
2818
  return result;
@@ -2791,7 +2843,7 @@ export class TaskGraphDispatcher {
2791
2843
  * the branch, the second holds the whole group. The generic keep/drop path cannot express that
2792
2844
  * difference, which is why exclusive edges take this route instead.
2793
2845
  */
2794
- evaluateExclusiveCondition(dep, entityById, invocation, debug) {
2846
+ evaluateExclusiveCondition(dep, entityById, invocation, decisions, debug, holdReasons) {
2795
2847
  // Same override-first rule as ordinary edges — see evaluateEdgeCondition.
2796
2848
  const override = OverrideVerdictFor(debug ?? {}, dep.ID);
2797
2849
  if (override)
@@ -2801,18 +2853,26 @@ export class TaskGraphDispatcher {
2801
2853
  const upstream = entityById.get(dep.DependsOnTaskID);
2802
2854
  if (!upstream)
2803
2855
  return 'unevaluable';
2804
- const result = this.conditionEvaluator.Evaluate(dep.Condition,
2856
+ const result = EvaluateCondition(dep.Condition,
2805
2857
  // The invocation envelope rides the EXCLUSIVE dialect too. R3-3 threaded it into the
2806
2858
  // ordinary path; a flow's XOR branch reading `data.userApproval` is the same documented
2807
2859
  // condition on a different edge kind, and `BuildConditionContext`'s defaulted parameter
2808
2860
  // made omitting it here silently evaluate those roots against nothing.
2809
- 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';
2810
2870
  // SAME CLASSIFICATION AS THE ORDINARY DIALECT (R2-3). The null-safe envelope already makes
2811
2871
  // one level of absence read as false here, but a deeper absent chain still throws — and
2812
2872
  // calling that 'unevaluable' would hold the whole group forever on a terminal origin, while
2813
2873
  // `DecideGate` would have dropped the identical condition. Two dialects, one question.
2814
2874
  if (!result.Success)
2815
- return IsBrokenGuard(result.ErrorMessage) ? 'unevaluable' : 'unsatisfied';
2875
+ return 'unsatisfied';
2816
2876
  return result.Value ? 'satisfied' : 'unsatisfied';
2817
2877
  }
2818
2878
  /**
@@ -2912,6 +2972,12 @@ export class TaskGraphDispatcher {
2912
2972
  if (task.StepType === 'ForEach' || task.StepType === 'While') {
2913
2973
  return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs), PayloadAtStart: payload };
2914
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
+ }
2915
2981
  const { params, errors } = BuildMappedInput(config?.inputMapping, { payload });
2916
2982
  for (const e of errors)
2917
2983
  LogError(`[TaskGraphDispatcher] Task ${task.ID}: ${e}`);
@@ -3259,6 +3325,175 @@ export class TaskGraphDispatcher {
3259
3325
  OnProgress: onProgress,
3260
3326
  });
3261
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
+ }
3262
3497
  /**
3263
3498
  * Leaves exactly one open request standing for a task, withdrawing any others.
3264
3499
  *