@uipath/maestro-builder-sdk 6.124.19 → 6.125.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,26 @@ export type { PreservedDocumentExtractionData } from './document-extraction-save
8
8
  export type { CaseJsonPreservation, PreservedActionDataFields, PreservedCaseNode, PreservedConnectorConfiguration, PreservedMetadataKey, PreservedSubscriptionFilter, PreservedTaskFields, PreservedVariableLane } from './preserve.js';
9
9
  export { CaseBuildError } from './case-expr-check.js';
10
10
  export type { CaseLocatedDiagnostic } from './case-expr-check.js';
11
- export type CaseRuleType = 'case-entered' | 'required-tasks-completed' | 'required-stages-completed' | 'selected-stage-completed' | 'selected-stage-exited' | 'selected-tasks-completed' | 'current-stage-entered' | 'adhoc' | 'runs-sequentially' | 'user-selected-stage' | 'wait-for-connector' | 'sla-status-change' | 'api-event';
11
+ export type CaseRuleType = 'case-entered' | 'required-tasks-completed' | 'required-stages-completed' | 'selected-stage-completed' | 'selected-stage-exited' | 'selected-tasks-completed' | 'current-stage-entered' | 'adhoc' | 'runs-sequentially' | 'user-selected-stage' | 'wait-for-connector' | 'sla-status-change' | 'api-event' | 'task-exited';
12
+ /**
13
+ * How a task ended without completing, as a `task-exited` rule filters it
14
+ * (`exitReasons`): `failed`, the task failed on its own, or `userExited`, a
15
+ * person ended the running task through the exit API. A task the case itself
16
+ * cancelled (an interrupting stage, the agent switching tasks) is neither; it
17
+ * fires no rule.
18
+ */
19
+ export declare const TASK_EXIT_REASONS: readonly ["failed", "userExited"];
20
+ /** One of {@link TASK_EXIT_REASONS}: `failed` or `userExited`. */
21
+ export type TaskExitReason = (typeof TASK_EXIT_REASONS)[number];
22
+ /**
23
+ * The class of the error a failed task exited with, as a `task-exited` rule
24
+ * filters it (`errorCategories`): `User` (a 4xx or a modeled business error),
25
+ * `System` (any other status) or `Deployment` (a resource the robot cannot
26
+ * reach). The component that saw the failure sets it; the rule only reads it.
27
+ */
28
+ export declare const TASK_ERROR_CATEGORIES: readonly ["User", "System", "Deployment"];
29
+ /** One of {@link TASK_ERROR_CATEGORIES}: `User`, `System` or `Deployment`. */
30
+ export type TaskErrorCategory = (typeof TASK_ERROR_CATEGORIES)[number];
12
31
  export interface RuleOpts {
13
32
  /**
14
33
  * Symbolic stage label (for `selected-stage-completed` / `selected-stage-exited`).
@@ -34,8 +53,12 @@ export interface RuleOpts {
34
53
  */
35
54
  stages?: string[];
36
55
  /**
37
- * Task references for `selected-tasks-completed`. Resolved **case-wide, not
38
- * per-stage** — a rule in one stage may reference a task in another.
56
+ * Task references for `selected-tasks-completed` and `task-exited`. Resolved
57
+ * **case-wide, not per-stage** — a `selected-tasks-completed` rule in one
58
+ * stage may reference a task in another. A `task-exited` rule may only name
59
+ * tasks of the stage it sits in (`check` reports TASK_EXITED_TASK_OUTSIDE_STAGE;
60
+ * `uip maestro case validate` rejects it), and fires once EVERY named task has
61
+ * exited; for "any one of them", write one rule per task.
39
62
  *
40
63
  * @remarks
41
64
  * Two forms:
@@ -90,6 +113,27 @@ export interface RuleOpts {
90
113
  * undeclared or misspelled name never fires.
91
114
  */
92
115
  businessEvent?: string;
116
+ /**
117
+ * For a `task-exited` rule — which exits count: `failed` (the task failed on
118
+ * its own, after its retries) or `userExited` (a person ended the running task
119
+ * through the exit API). Omit it for either. A task the case cancelled never
120
+ * counts. Written as `exitReasons`.
121
+ *
122
+ * @example
123
+ * rule('task-exited', { tasks: ['Fetch Policy'], exitReasons: ['failed'] })
124
+ */
125
+ exitReasons?: TaskExitReason[];
126
+ /**
127
+ * For a `task-exited` rule that reacts to failures only
128
+ * (`exitReasons: ['failed']`) — only a failure whose error has one of these
129
+ * categories counts. The platform ignores the filter on a rule that also
130
+ * reacts to `userExited`, or names no reason (`check` warns
131
+ * TASK_EXITED_FILTER_IGNORED). Written as `errorCategories`.
132
+ *
133
+ * @example
134
+ * rule('task-exited', { tasks: ['Fetch Policy'], exitReasons: ['failed'], errorCategories: ['Deployment'] })
135
+ */
136
+ errorCategories?: TaskErrorCategory[];
93
137
  /** A `=js:` gate on case state (for `adhoc`, or as an extra guard on any rule). */
94
138
  expression?: string;
95
139
  }
@@ -122,6 +166,25 @@ export declare const ANY_ESCALATION: unique symbol;
122
166
  * array of arrays for the complete OR-of-AND grid to
123
167
  * `entryWhen`/`exitWhen`/etc.
124
168
  *
169
+ * A `task-exited` rule reacts to a task of its own stage ending without
170
+ * completing: it failed, or a person ended it. It belongs on a task's entry
171
+ * (start a replacement task) or on a stage exit that does not mark the stage
172
+ * complete (leave for a review stage, whose entry selects
173
+ * `selected-stage-exited`); the platform ignores it at stage entry, on a
174
+ * completing exit and at case completion. Writing one turns on the case's
175
+ * `caseExecutionExitsOnTaskFailure` and `caseExecutionUsesTaskExitRules` flags
176
+ * ({@link CaseBuilder.exitOnTaskFailure}, {@link CaseBuilder.taskExitRules}).
177
+ *
178
+ * @example
179
+ * **Start a manual fallback when the automated task fails**
180
+ * ```ts
181
+ * casePlan('policy-intake').stage('Intake', (s) => s
182
+ * .entryWhen(rule('case-entered'))
183
+ * .task('Fetch Policy', (t) => t.process('FetchPolicy', { folder: 'Shared' }).entryWhen(rule('current-stage-entered')))
184
+ * .task('Enter Policy By Hand', (t) => t.action({ title: 'Enter the policy' })
185
+ * .entryWhen(rule('task-exited', { tasks: ['Fetch Policy'], exitReasons: ['failed'] }))))
186
+ * ```
187
+ *
125
188
  * @param type - Which condition, e.g. `'case-entered'` or `'selected-tasks-completed'`.
126
189
  * @param opts - What the rule needs, e.g. the `tasks` a task-completion rule waits on.
127
190
  * @returns A rule to pass to `entryWhen` / `exitWhen` / `completeWhen`.
@@ -1225,6 +1288,18 @@ export interface BuiltCase {
1225
1288
  caseAppConfig?: CaseAppConfig;
1226
1289
  /** Whether optional tasks with an `adhoc` entry rule may be started on demand. */
1227
1290
  allowAdhocOptionalStageTasks?: boolean;
1291
+ /**
1292
+ * `metadata.caseExecutionExitsOnTaskFailure`: a failing task exits and the
1293
+ * case keeps running, instead of the case faulting. Unset = not declared; the
1294
+ * serializer writes `true` when the case has a `task-exited` rule.
1295
+ */
1296
+ exitOnTaskFailure?: boolean;
1297
+ /**
1298
+ * `metadata.caseExecutionUsesTaskExitRules`: the case's rules react to task
1299
+ * exits. Unset = not declared; the serializer writes `true` when the case has a
1300
+ * `task-exited` rule.
1301
+ */
1302
+ taskExitRules?: boolean;
1228
1303
  vars: CaseVarDecl[];
1229
1304
  stages: BuiltStage[];
1230
1305
  caseExit: BuiltCaseExitCondition[];
@@ -1906,6 +1981,8 @@ declare class CaseBuilder {
1906
1981
  private _caseApp;
1907
1982
  private _caseAppConfig?;
1908
1983
  private _allowAdhocTasks?;
1984
+ private _exitOnTaskFailure?;
1985
+ private _taskExitRules?;
1909
1986
  private _layout?;
1910
1987
  private readonly _vars;
1911
1988
  private readonly _stages;
@@ -2012,6 +2089,33 @@ declare class CaseBuilder {
2012
2089
  * @returns This builder, so calls chain.
2013
2090
  */
2014
2091
  allowAdhocTasks(enabled?: boolean): this;
2092
+ /**
2093
+ * Make a failing task exit instead of faulting the case: once the task's
2094
+ * retries are spent, the engine records the exit (with the error's code and
2095
+ * category) and the case keeps running, so an operator can re-run the task
2096
+ * and a `task-exited` rule can route around it. Written as
2097
+ * `metadata.caseExecutionExitsOnTaskFailure`. A case with a `task-exited`
2098
+ * rule gets `true` without this call; pass `false` to keep a failing task
2099
+ * faulting the case, which also makes every `task-exited` rule a no-op
2100
+ * (`check` warns TASK_EXITED_IGNORED).
2101
+ *
2102
+ * @param enabled - Whether a failing task exits rather than faults the case.
2103
+ * @returns This builder, so calls chain.
2104
+ */
2105
+ exitOnTaskFailure(enabled?: boolean): this;
2106
+ /**
2107
+ * Let the case's rules react to task exits, so a `task-exited` rule fires and
2108
+ * an operator can end a running task through the exit API. Written as
2109
+ * `metadata.caseExecutionUsesTaskExitRules`; it takes effect only on a case
2110
+ * that also exits on task failure ({@link CaseBuilder.exitOnTaskFailure}). A
2111
+ * case with a `task-exited` rule gets `true` without this call; the explicit
2112
+ * call declares the flag on a case that has no such rule yet, or turns it off
2113
+ * with `false`.
2114
+ *
2115
+ * @param enabled - Whether the case's rules react to task exits.
2116
+ * @returns This builder, so calls chain.
2117
+ */
2118
+ taskExitRules(enabled?: boolean): this;
2015
2119
  /**
2016
2120
  * Set optional designer layout for stages and triggers by their author-level
2017
2121
  * names. This metadata does not affect Case behavior. Unknown or ambiguous
@@ -33,6 +33,21 @@ import { unquoteLiteral } from './literal.js';
33
33
  import { ANY_ESCALATION_KEY } from './rule-options.js';
34
34
  export { preserveCaseJson } from './preserve.js';
35
35
  export { CaseBuildError } from './case-expr-check.js';
36
+ /**
37
+ * How a task ended without completing, as a `task-exited` rule filters it
38
+ * (`exitReasons`): `failed`, the task failed on its own, or `userExited`, a
39
+ * person ended the running task through the exit API. A task the case itself
40
+ * cancelled (an interrupting stage, the agent switching tasks) is neither; it
41
+ * fires no rule.
42
+ */
43
+ export const TASK_EXIT_REASONS = ['failed', 'userExited'];
44
+ /**
45
+ * The class of the error a failed task exited with, as a `task-exited` rule
46
+ * filters it (`errorCategories`): `User` (a 4xx or a modeled business error),
47
+ * `System` (any other status) or `Deployment` (a resource the robot cannot
48
+ * reach). The component that saw the failure sets it; the rule only reads it.
49
+ */
50
+ export const TASK_ERROR_CATEGORIES = ['User', 'System', 'Deployment'];
36
51
  /**
37
52
  * The escalation of an at-risk `sla-status-change` rule that fires on **any**
38
53
  * at-risk escalation of the referenced SLA: the Case Designer's "Any" choice,
@@ -58,6 +73,25 @@ export const ANY_ESCALATION = Symbol.for(ANY_ESCALATION_KEY);
58
73
  * array of arrays for the complete OR-of-AND grid to
59
74
  * `entryWhen`/`exitWhen`/etc.
60
75
  *
76
+ * A `task-exited` rule reacts to a task of its own stage ending without
77
+ * completing: it failed, or a person ended it. It belongs on a task's entry
78
+ * (start a replacement task) or on a stage exit that does not mark the stage
79
+ * complete (leave for a review stage, whose entry selects
80
+ * `selected-stage-exited`); the platform ignores it at stage entry, on a
81
+ * completing exit and at case completion. Writing one turns on the case's
82
+ * `caseExecutionExitsOnTaskFailure` and `caseExecutionUsesTaskExitRules` flags
83
+ * ({@link CaseBuilder.exitOnTaskFailure}, {@link CaseBuilder.taskExitRules}).
84
+ *
85
+ * @example
86
+ * **Start a manual fallback when the automated task fails**
87
+ * ```ts
88
+ * casePlan('policy-intake').stage('Intake', (s) => s
89
+ * .entryWhen(rule('case-entered'))
90
+ * .task('Fetch Policy', (t) => t.process('FetchPolicy', { folder: 'Shared' }).entryWhen(rule('current-stage-entered')))
91
+ * .task('Enter Policy By Hand', (t) => t.action({ title: 'Enter the policy' })
92
+ * .entryWhen(rule('task-exited', { tasks: ['Fetch Policy'], exitReasons: ['failed'] }))))
93
+ * ```
94
+ *
61
95
  * @param type - Which condition, e.g. `'case-entered'` or `'selected-tasks-completed'`.
62
96
  * @param opts - What the rule needs, e.g. the `tasks` a task-completion rule waits on.
63
97
  * @returns A rule to pass to `entryWhen` / `exitWhen` / `completeWhen`.
@@ -1094,6 +1128,8 @@ class CaseBuilder {
1094
1128
  _caseApp = false;
1095
1129
  _caseAppConfig;
1096
1130
  _allowAdhocTasks;
1131
+ _exitOnTaskFailure;
1132
+ _taskExitRules;
1097
1133
  _layout;
1098
1134
  _vars = [];
1099
1135
  _stages = [];
@@ -1234,6 +1270,39 @@ class CaseBuilder {
1234
1270
  this._allowAdhocTasks = enabled;
1235
1271
  return this;
1236
1272
  }
1273
+ /**
1274
+ * Make a failing task exit instead of faulting the case: once the task's
1275
+ * retries are spent, the engine records the exit (with the error's code and
1276
+ * category) and the case keeps running, so an operator can re-run the task
1277
+ * and a `task-exited` rule can route around it. Written as
1278
+ * `metadata.caseExecutionExitsOnTaskFailure`. A case with a `task-exited`
1279
+ * rule gets `true` without this call; pass `false` to keep a failing task
1280
+ * faulting the case, which also makes every `task-exited` rule a no-op
1281
+ * (`check` warns TASK_EXITED_IGNORED).
1282
+ *
1283
+ * @param enabled - Whether a failing task exits rather than faults the case.
1284
+ * @returns This builder, so calls chain.
1285
+ */
1286
+ exitOnTaskFailure(enabled = true) {
1287
+ this._exitOnTaskFailure = enabled;
1288
+ return this;
1289
+ }
1290
+ /**
1291
+ * Let the case's rules react to task exits, so a `task-exited` rule fires and
1292
+ * an operator can end a running task through the exit API. Written as
1293
+ * `metadata.caseExecutionUsesTaskExitRules`; it takes effect only on a case
1294
+ * that also exits on task failure ({@link CaseBuilder.exitOnTaskFailure}). A
1295
+ * case with a `task-exited` rule gets `true` without this call; the explicit
1296
+ * call declares the flag on a case that has no such rule yet, or turns it off
1297
+ * with `false`.
1298
+ *
1299
+ * @param enabled - Whether the case's rules react to task exits.
1300
+ * @returns This builder, so calls chain.
1301
+ */
1302
+ taskExitRules(enabled = true) {
1303
+ this._taskExitRules = enabled;
1304
+ return this;
1305
+ }
1237
1306
  /**
1238
1307
  * Set optional designer layout for stages and triggers by their author-level
1239
1308
  * names. This metadata does not affect Case behavior. Unknown or ambiguous
@@ -1465,6 +1534,8 @@ class CaseBuilder {
1465
1534
  ...(this._allowAdhocTasks !== undefined
1466
1535
  ? { allowAdhocOptionalStageTasks: this._allowAdhocTasks }
1467
1536
  : {}),
1537
+ ...(this._exitOnTaskFailure !== undefined ? { exitOnTaskFailure: this._exitOnTaskFailure } : {}),
1538
+ ...(this._taskExitRules !== undefined ? { taskExitRules: this._taskExitRules } : {}),
1468
1539
  vars: this._vars,
1469
1540
  stages: this._stages,
1470
1541
  caseExit: this._caseExit,
@@ -0,0 +1,15 @@
1
+ /**
2
+ * check-task-exit — `check()` rules on `task-exited` rules: where one can sit,
3
+ * which tasks it may name, and when its filters or the case's flags make it a
4
+ * no-op. Each mirrors a rule of the platform's canvas validation
5
+ * (`@uipath/case-schema`, `validateTaskExitedRule`), at the severity `uip
6
+ * maestro case validate` reports it, plus one the Designer enforces through
7
+ * its task picker rather than a finding (TASK_EXITED_SELF_RERUN).
8
+ *
9
+ * All of them are `lint`: compile writes the rule as authored, so a decompiled
10
+ * source keeps it and `check` reports it again.
11
+ */
12
+ import type { Diagnostic } from './check.js';
13
+ import type { BuiltCase } from './case-sdk.js';
14
+ /** The rules above, in the order `check` reports them. */
15
+ export declare function checkTaskExit(built: BuiltCase, diags: Diagnostic[]): void;
@@ -0,0 +1,203 @@
1
+ import { ruleSites } from './rule-sites.js';
2
+ import { taskExitFlags } from './task-exit.js';
3
+ /** Every `task-exited` rule of the case, with its slot. */
4
+ function* sites(built) {
5
+ for (const site of ruleSites(built)) {
6
+ if (site.rule.rule !== 'task-exited')
7
+ continue;
8
+ // The platform compiles the rule on an exit unless the exit marks the
9
+ // stage complete without holding for a person (`conditionCompilesTaskExited`).
10
+ const completing = site.exit !== undefined && site.exit.marksStageComplete === true && (site.exit.type ?? 'exit-only') !== 'wait-for-user';
11
+ yield { rule: site.rule, where: site.where, slot: completing ? 'completing-exit' : site.slot, stage: site.stage, task: site.task };
12
+ }
13
+ }
14
+ /** Every key the serializer resolves a task by (its bare name, and `Stage/Task`) → its stage and task. */
15
+ function taskIndex(built) {
16
+ const index = new Map();
17
+ for (const stage of built.stages)
18
+ for (const task of stage.lanes.flat()) {
19
+ index.set(task.name, { stage, task });
20
+ index.set(`${stage.label}/${task.name}`, { stage, task });
21
+ }
22
+ return index;
23
+ }
24
+ /**
25
+ * For each task, the tasks whose exit starts it and that it starts in turn,
26
+ * through any chain of `task-exited` entry rules: the loops other than a task
27
+ * naming itself.
28
+ */
29
+ function exitCycles(built, index) {
30
+ // startedBy: task -> the tasks its entry names in a task-exited rule.
31
+ const startedBy = new Map();
32
+ for (const site of ruleSites(built)) {
33
+ if (site.rule.rule !== 'task-exited' || site.task === undefined)
34
+ continue;
35
+ for (const key of site.rule.tasks ?? []) {
36
+ const named = index.get(key);
37
+ if (named === undefined || named.stage !== site.stage || named.task === site.task)
38
+ continue;
39
+ if (!startedBy.has(site.task))
40
+ startedBy.set(site.task, new Set());
41
+ startedBy.get(site.task).add(named.task);
42
+ }
43
+ }
44
+ const reaches = (from, to) => {
45
+ const seen = new Set();
46
+ const queue = [from];
47
+ while (queue.length) {
48
+ const next = queue.pop();
49
+ if (next === to)
50
+ return true;
51
+ if (seen.has(next))
52
+ continue;
53
+ seen.add(next);
54
+ queue.push(...(startedBy.get(next) ?? []));
55
+ }
56
+ return false;
57
+ };
58
+ const cycles = new Map();
59
+ for (const [task, sources] of startedBy)
60
+ for (const source of sources)
61
+ if (reaches(source, task)) {
62
+ if (!cycles.has(task))
63
+ cycles.set(task, new Set());
64
+ cycles.get(task).add(source);
65
+ }
66
+ return cycles;
67
+ }
68
+ const SLOT_NAMES = new Map([
69
+ ['stage-entry', 'a stage entry'],
70
+ ['completing-exit', 'a stage exit that marks the stage complete'],
71
+ ['stage-exit', 'a stage exit'],
72
+ ['task-entry', "a task's entry"],
73
+ ['case-exit', 'case completion'],
74
+ ]);
75
+ /** The rules above, in the order `check` reports them. */
76
+ export function checkTaskExit(built, diags) {
77
+ const index = taskIndex(built);
78
+ const flags = taskExitFlags(built);
79
+ const off = [
80
+ ...(flags.exitOnTaskFailure === false ? ['.exitOnTaskFailure(false)'] : []),
81
+ ...(flags.taskExitRules === false ? ['.taskExitRules(false)'] : []),
82
+ ];
83
+ // A decompiled plan that had the rule without a flag keeps the flag out
84
+ // (`taskExitFlags`), so the rule stays as ignored as the platform had it.
85
+ const missing = [
86
+ ...(flags.exitOnTaskFailure === undefined ? ['.exitOnTaskFailure()'] : []),
87
+ ...(flags.taskExitRules === undefined ? ['.taskExitRules()'] : []),
88
+ ];
89
+ const names = new Map();
90
+ for (const stage of built.stages)
91
+ for (const task of stage.lanes.flat())
92
+ names.set(task.name, (names.get(task.name) ?? 0) + 1);
93
+ const cycles = exitCycles(built, index);
94
+ for (const site of sites(built)) {
95
+ const { rule, where, slot, stage, task } = site;
96
+ const stageLabel = stage?.label;
97
+ // Where the platform does not compile the rule, it never fires
98
+ // (CASE_MGMT_CASE_CONDITION_RULE_TASK_EXITED_NOT_HERE, a warning).
99
+ if (slot === 'stage-entry' || slot === 'completing-exit' || slot === 'case-exit')
100
+ diags.push({
101
+ level: 'warning',
102
+ code: 'TASK_EXITED_PLACEMENT',
103
+ message: `Rule "task-exited" at ${SLOT_NAMES.get(slot)} never fires: the platform compiles it only on a task's entry `
104
+ + 'or on a stage exit that does not mark the stage complete (or that holds for a user). `uip maestro case validate` '
105
+ + 'reports it as CASE_MGMT_CASE_CONDITION_RULE_TASK_EXITED_NOT_HERE.',
106
+ suggestion: slot === 'completing-exit'
107
+ ? `To leave stage "${stageLabel}" when a task exits, give this exit { marksStageComplete: false } and enter the next `
108
+ + `stage with rule('selected-stage-exited', { stage: '${stageLabel}' }). To start a replacement task instead, put `
109
+ + "the rule on that task's entry."
110
+ : "Put the rule on the entry of the task that should start, or on an exit of the task's stage with "
111
+ + '{ marksStageComplete: false }, and let the next stage enter on rule(\'selected-stage-exited\').',
112
+ where,
113
+ });
114
+ // The case's flags decide whether the converter lowers the rule at all
115
+ // (CASE_MGMT_CASE_CONDITION_RULE_TASK_EXITED_IGNORED, a warning).
116
+ if (off.length)
117
+ diags.push({
118
+ level: 'warning',
119
+ code: 'TASK_EXITED_IGNORED',
120
+ message: `Rule "task-exited" in ${where} never fires: the case sets ${off.join(' and ')}, and the platform lowers a `
121
+ + 'task-exited rule only when the case both exits on task failure and uses task exit rules.',
122
+ suggestion: `Remove ${off.join(' and ')} (a task-exited rule turns both flags on by itself), or remove the rule.`,
123
+ where,
124
+ });
125
+ else if (missing.length)
126
+ diags.push({
127
+ level: 'warning',
128
+ code: 'TASK_EXITED_IGNORED',
129
+ message: `Rule "task-exited" in ${where} never fires: the plan this source was decompiled from has the rule but not `
130
+ + `${missing.length > 1 ? 'the two task-exit flags' : 'one of the two task-exit flags'}, and the platform reads an absent flag as off. `
131
+ + `Compile keeps the flag out, so the plan behaves as it did. To turn the rule on, add ${missing.join(' and ')} to the case.`,
132
+ suggestion: `Add ${missing.join(' and ')} to the case to turn the rule on, or leave the source as it is to keep it off.`,
133
+ where,
134
+ });
135
+ // No task selected: the rule waits on nothing
136
+ // (CASE_MGMT_ROOT_CASE_CONDITION_RULE_SELECTED_TASK_IDS_MISSING, a warning).
137
+ if (!rule.tasks?.length)
138
+ diags.push({
139
+ level: 'warning',
140
+ code: 'RULE_TASKS_REQUIRED',
141
+ message: 'Rule "task-exited" selects no tasks — pass { tasks: [...] } naming tasks of its own stage. '
142
+ + '`uip maestro case validate` reports it as CASE_MGMT_ROOT_CASE_CONDITION_RULE_SELECTED_TASK_IDS_MISSING.',
143
+ where,
144
+ });
145
+ for (const key of rule.tasks ?? []) {
146
+ const named = index.get(key);
147
+ // An unknown name is the serializer's UNKNOWN_TASK_REF.
148
+ if (named === undefined || stage === undefined)
149
+ continue;
150
+ // Only a task of the rule's own stage can be named
151
+ // (CASE_MGMT_ROOT_CASE_CONDITION_RULE_SELECTED_TASK_MISSING, an error).
152
+ if (named.stage !== stage)
153
+ diags.push({
154
+ level: 'error',
155
+ code: 'TASK_EXITED_TASK_OUTSIDE_STAGE',
156
+ message: `Rule "task-exited" in ${where} names task "${named.task.name}", which is in stage "${named.stage.label}". `
157
+ + `A task-exited rule reacts only to tasks of its own stage ("${stageLabel}"); \`uip maestro case validate\` rejects `
158
+ + 'this as CASE_MGMT_ROOT_CASE_CONDITION_RULE_SELECTED_TASK_MISSING.',
159
+ suggestion: `Name a task of stage "${stageLabel}", or move the rule to a condition in stage "${named.stage.label}".`
160
+ + ((names.get(key) ?? 0) > 1 ? ` More than one stage has a task "${key}"; to name this stage's, write "${stageLabel}/${key}".` : ''),
161
+ where,
162
+ });
163
+ // A task that starts on its own exit re-runs after every failure until
164
+ // the case guardrail stops it. The Designer's task picker leaves the
165
+ // rule's own task out; the SDK can write it, so it says so.
166
+ else if (task !== undefined && named.task === task)
167
+ diags.push({
168
+ level: 'warning',
169
+ code: 'TASK_EXITED_SELF_RERUN',
170
+ message: `Task "${task.name}" starts when it has itself exited, so every failure runs it again until the case `
171
+ + 'guardrail stops the loop (100 repeats in 10 minutes).',
172
+ suggestion: `Name the task whose exit should start "${task.name}", or start a different replacement task. To re-run `
173
+ + 'a failed task, an operator uses the re-run API.',
174
+ where,
175
+ });
176
+ // A longer loop does the same: A starts on B's exit and B on A's.
177
+ else if (task !== undefined && cycles.get(task)?.has(named.task))
178
+ diags.push({
179
+ level: 'warning',
180
+ code: 'TASK_EXITED_SELF_RERUN',
181
+ message: `Task "${task.name}" starts when "${named.task.name}" has exited, and "${named.task.name}" starts, directly or `
182
+ + `through other tasks, when "${task.name}" has exited. Every failure runs the next task of the loop until the case `
183
+ + 'guardrail stops it (100 repeats in 10 minutes).',
184
+ suggestion: 'Break the loop: let one of these tasks start on a rule that is not a task exit, or end the chain in a task a person does.',
185
+ where,
186
+ });
187
+ }
188
+ // Only a failure carries an error, so the category filter applies only to
189
+ // a failures-only rule (CASE_MGMT_CASE_CONDITION_RULE_TASK_EXITED_ERROR_FILTER_IGNORED, a warning).
190
+ const failuresOnly = (rule.exitReasons?.length ?? 0) > 0 && rule.exitReasons.every((reason) => reason === 'failed');
191
+ if (rule.errorCategories?.length && !failuresOnly)
192
+ diags.push({
193
+ level: 'warning',
194
+ code: 'TASK_EXITED_FILTER_IGNORED',
195
+ message: `Rule "task-exited" in ${where} filters on errorCategories but reacts to `
196
+ + (rule.exitReasons?.length ? `exit reasons ${rule.exitReasons.map((r) => `'${r}'`).join(', ')}` : 'every exit reason')
197
+ + "; only a failure carries an error, so the platform applies the filter only when exitReasons is exactly ['failed'] "
198
+ + 'and reports this as CASE_MGMT_CASE_CONDITION_RULE_TASK_EXITED_ERROR_FILTER_IGNORED.',
199
+ suggestion: "Set exitReasons: ['failed'], or drop errorCategories.",
200
+ where,
201
+ });
202
+ }
203
+ }
@@ -10,6 +10,7 @@ import { caseJsonPreservation } from './preserve.js';
10
10
  import { scriptLint } from './script.js';
11
11
  import { httpRequestLint } from './http-request.js';
12
12
  import { checkRuleSemantics } from './check-rule-semantics.js';
13
+ import { checkTaskExit } from './check-task-exit.js';
13
14
  import { serialize } from './serialize.js';
14
15
  import { lintPlanFindings, planReport } from './plan-check/index.js';
15
16
  import { caseExprLints } from './case-expr-check.js';
@@ -257,6 +258,7 @@ export function checkCompiled(built, opts = {}) {
257
258
  // A retry policy compile writes as authored but the platform never runs (lint).
258
259
  checkTaskRetry(built, diags);
259
260
  checkRuleSemantics(built, diags);
261
+ checkTaskExit(built, diags);
260
262
  checkLibraryConnectors(built, opts, diags);
261
263
  const serialized = serializerRefusals(built, opts, diags, reportedReads);
262
264
  diags.push(...serialized.diagnostics);
@@ -585,7 +587,10 @@ function checkStage(stage, diags, refStage, refPlacement) {
585
587
  // fails. So the signature below must include the expression and the refs, not
586
588
  // just the rule name — keying on the rule type alone would reject legal
587
589
  // value-tiered routing, which is the natural way to express "under $25k goes here".
588
- const sig = (c) => JSON.stringify(c.rules.map((g) => g.map((r) => [r.rule, r.stage ?? (r.stages ?? []).join(','), (r.tasks ?? []).join(','), r.expression ?? '', r.businessEvent ?? ''])));
590
+ const sig = (c) => JSON.stringify(c.rules.map((g) => g.map((r) => [
591
+ r.rule, r.stage ?? (r.stages ?? []).join(','), (r.tasks ?? []).join(','), r.expression ?? '', r.businessEvent ?? '',
592
+ (r.exitReasons ?? []).join(','), (r.errorCategories ?? []).join(','),
593
+ ])));
589
594
  const seenExit = new Map();
590
595
  stage.exit.forEach((c, i) => {
591
596
  const k = sig(c);
@@ -52,6 +52,9 @@ interface Rule {
52
52
  slaId?: string;
53
53
  escalationId?: string;
54
54
  businessEventType?: string;
55
+ exitReasons?: unknown;
56
+ errorCategories?: unknown;
57
+ errorRefs?: unknown;
55
58
  }
56
59
  interface Condition {
57
60
  id?: string;
@@ -173,6 +176,8 @@ interface CasePlan {
173
176
  };
174
177
  adhocCaseEndData?: unknown;
175
178
  allowAdhocOptionalStageTasks?: unknown;
179
+ caseExecutionExitsOnTaskFailure?: unknown;
180
+ caseExecutionUsesTaskExitRules?: unknown;
176
181
  waitForHumanSelectNextStageDFConnector?: unknown;
177
182
  [key: string]: unknown;
178
183
  };
@@ -194,7 +199,7 @@ export interface DecompileOptions {
194
199
  bestEffort?: boolean;
195
200
  }
196
201
  export interface CaseDecompileDiagnostic {
197
- code: 'UNSUPPORTED_TASK_KIND' | 'UNKNOWN_STAGE_REFERENCE' | 'UNKNOWN_TASK_REFERENCE' | 'UNKNOWN_EXIT_TARGET';
202
+ code: 'UNSUPPORTED_TASK_KIND' | 'UNKNOWN_STAGE_REFERENCE' | 'UNKNOWN_TASK_REFERENCE' | 'UNKNOWN_EXIT_TARGET' | 'TASK_EXITED_ERROR_REFS_UNSUPPORTED';
198
203
  message: string;
199
204
  location: string;
200
205
  }
@@ -272,7 +277,7 @@ type Preservation = {
272
277
  row: Record<string, unknown>;
273
278
  dangling?: true;
274
279
  }>;
275
- omitMetadata?: Array<'caseAppEnabled' | 'caseIdentifierType' | 'publishVersion' | 'intsvcActivityConfig'>;
280
+ omitMetadata?: Array<'caseAppEnabled' | 'caseIdentifierType' | 'publishVersion' | 'intsvcActivityConfig' | 'caseExecutionExitsOnTaskFailure' | 'caseExecutionUsesTaskExitRules'>;
276
281
  publishVersion?: number;
277
282
  nodeFields?: Record<string, Record<string, unknown>>;
278
283
  variableFields?: Partial<Record<'inputs' | 'outputs' | 'inputOutputs', Record<string, Record<string, unknown>>>>;
@@ -34,6 +34,17 @@ import { bindingIdCandidates, offlineBindingLabel } from './ids.js';
34
34
  import { bindingRefId, isLiftFailure, isMintedWire, liftResourceFolder, liftResourceName, readBindingIds, resourceBindingOf, typedFolder, wireRows, } from './resource-wire.js';
35
35
  import { connectorPlaceholderKindOf } from './connector-placeholder.js';
36
36
  import { raiseTaskOutputReads, referableOutputIds } from './task-output-ref.js';
37
+ /** True when any condition of the document holds a `task-exited` rule. */
38
+ function hasTaskExitedRule(plan) {
39
+ const conditions = [...(plan.metadata?.caseExitRules ?? [])];
40
+ for (const node of plan.nodes ?? []) {
41
+ const data = node.data;
42
+ conditions.push(...(data?.entryConditions ?? []), ...(data?.exitConditions ?? []));
43
+ for (const task of (data?.tasks ?? []).flat())
44
+ conditions.push(...(task?.entryConditions ?? []));
45
+ }
46
+ return conditions.some((c) => (c?.rules ?? []).flat().some((r) => r?.rule === 'task-exited'));
47
+ }
37
48
  const TASK_KIND_METHOD = {
38
49
  process: 'process',
39
50
  agent: 'agent',
@@ -618,6 +629,26 @@ function emitRule(rule, refs) {
618
629
  });
619
630
  entries.push(['tasks', `[${names.join(', ')}]`]);
620
631
  }
632
+ if (rule.rule === 'task-exited') {
633
+ // Each filter comes back as written, an empty list included; a value the
634
+ // SDK's vocabulary lacks is left for compile to refuse by name.
635
+ for (const field of ['exitReasons', 'errorCategories']) {
636
+ const values = rule[field];
637
+ if (values === undefined)
638
+ continue;
639
+ if (!Array.isArray(values) || values.some((value) => typeof value !== 'string'))
640
+ throw new Error(`rule "task-exited" has a ${field} that is not a list of strings, which is not authorable.`);
641
+ entries.push([field, tsLiteral(values)]);
642
+ }
643
+ // `errorRefs` names the case's error definitions (`metadata.errors`, behind
644
+ // `caseExecutionTaskErrorHandling`), which the SDK does not author.
645
+ if (Array.isArray(rule.errorRefs) && rule.errorRefs.length)
646
+ diagnose(refs, {
647
+ code: 'TASK_EXITED_ERROR_REFS_UNSUPPORTED',
648
+ message: `rule "task-exited" filters on ${rule.errorRefs.length} case error definition(s) (errorRefs), which the SDK does not author; the filter is left out.`,
649
+ location: `rule:${rule.id ?? rule.rule}`,
650
+ });
651
+ }
621
652
  if (rule.selectedTriggerIds !== undefined) {
622
653
  // Only `case-entered` reads it: on any other rule it has no authored spelling.
623
654
  if (rule.rule !== 'case-entered')
@@ -3090,6 +3121,7 @@ export function collectPreservation(plan, library) {
3090
3121
  const metadataKnown = new Set([
3091
3122
  'caseIdentifier', 'caseIdentifierType', 'caseAppEnabled', 'caseAppConfig', 'publishVersion', 'caseExitRules', 'slaRules',
3092
3123
  'allowAdhocOptionalStageTasks', 'waitForHumanSelectNextStageDFConnector', 'businessEvents',
3124
+ 'caseExecutionExitsOnTaskFailure', 'caseExecutionUsesTaskExitRules',
3093
3125
  ]);
3094
3126
  const metadata = Object.fromEntries(Object.entries(plan.metadata ?? {}).filter(([name]) => !metadataKnown.has(name)));
3095
3127
  if (Object.keys(metadata).length)
@@ -3098,7 +3130,13 @@ export function collectPreservation(plan, library) {
3098
3130
  // it out (see `omitMetadata` in preserve.ts). `publishVersion` is a platform
3099
3131
  // stamp the builder does not author, so a different source value is carried.
3100
3132
  // `intsvcActivityConfig` absent is a V1 plan, which must stay V1.
3101
- const omitMetadata = ['caseAppEnabled', 'caseIdentifierType', 'publishVersion', 'intsvcActivityConfig']
3133
+ // A `task-exited` rule implies both task-exit flags at compile. The platform
3134
+ // reads an absent flag as off, so a document that has the rule without a
3135
+ // flag records the absence, and compile does not turn the rule on.
3136
+ const omitMetadata = [
3137
+ 'caseAppEnabled', 'caseIdentifierType', 'publishVersion', 'intsvcActivityConfig',
3138
+ ...(hasTaskExitedRule(plan) ? ['caseExecutionExitsOnTaskFailure', 'caseExecutionUsesTaskExitRules'] : []),
3139
+ ]
3102
3140
  .filter((name) => !Object.prototype.hasOwnProperty.call(plan.metadata ?? {}, name));
3103
3141
  if (omitMetadata.length)
3104
3142
  preservation.omitMetadata = [...omitMetadata];
@@ -3595,6 +3633,19 @@ export function decompileWithDiagnostics(plan, options = {}) {
3595
3633
  throw new Error('allowAdhocOptionalStageTasks must be boolean.');
3596
3634
  chain.line(depth, metadata.allowAdhocOptionalStageTasks ? '.allowAdhocTasks()' : '.allowAdhocTasks(false)');
3597
3635
  }
3636
+ // The task-exit flags come back as the explicit calls, `false` included, so
3637
+ // a document that declares them without a task-exited rule keeps them.
3638
+ for (const [key, method] of [
3639
+ ['caseExecutionExitsOnTaskFailure', 'exitOnTaskFailure'],
3640
+ ['caseExecutionUsesTaskExitRules', 'taskExitRules'],
3641
+ ]) {
3642
+ const value = metadata[key];
3643
+ if (value === undefined)
3644
+ continue;
3645
+ if (typeof value !== 'boolean')
3646
+ throw new Error(`${key} must be boolean.`);
3647
+ chain.line(depth, value ? `.${method}()` : `.${method}(false)`);
3648
+ }
3598
3649
  emitVariables(chain, depth, plan, refs.triggerVarById, triggers.map(isTimerTrigger));
3599
3650
  for (const { name } of consts)
3600
3651
  chain.line(depth, `.trigger(${name})`);
@@ -43,7 +43,7 @@ export const CASE_FORMAT_PROFILE = {
43
43
  // Raising either means re-running tests/case-v32-native.test.ts against the
44
44
  // new pin: it proves the output is a fixed point of every migration hop.
45
45
  validationCeiling: {
46
- caseSchemaVersion: '0.1173.0',
46
+ caseSchemaVersion: '0.1233.0',
47
47
  formatVersion: '32.0.4',
48
48
  },
49
49
  };