@elementumai/edk 0.9.18 → 0.9.20

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 (219) hide show
  1. package/README.md +154 -9
  2. package/dist-sdk/src/catalog/factories.d.ts +35 -1
  3. package/dist-sdk/src/catalog/factories.js +36 -0
  4. package/dist-sdk/src/catalog/from-authoring.d.ts +13 -8
  5. package/dist-sdk/src/catalog/from-authoring.js +34 -9
  6. package/dist-sdk/src/catalog/index.d.ts +2 -2
  7. package/dist-sdk/src/catalog/index.js +2 -2
  8. package/dist-sdk/src/catalog/org.d.ts +39 -1
  9. package/dist-sdk/src/catalog/org.js +460 -50
  10. package/dist-sdk/src/catalog/render.js +6 -6
  11. package/dist-sdk/src/catalog/token.js +7 -0
  12. package/dist-sdk/src/catalog/types.d.ts +44 -1
  13. package/dist-sdk/src/catalog/types.js +13 -0
  14. package/dist-sdk/src/core/triggers/on-demand.d.ts +39 -3
  15. package/dist-sdk/src/core/triggers/on-demand.js +10 -2
  16. package/dist-sdk/src/engine/build/context.d.ts +1 -1
  17. package/dist-sdk/src/engine/ei/run.d.ts +149 -0
  18. package/dist-sdk/src/engine/ei/run.js +1132 -0
  19. package/dist-sdk/src/engine/logging.d.ts +17 -0
  20. package/dist-sdk/src/engine/logging.js +18 -0
  21. package/dist-sdk/src/engine/pull/ref-only.d.ts +5 -0
  22. package/dist-sdk/src/engine/pull/ref-only.js +64 -27
  23. package/dist-sdk/src/engine/pull/result-output.d.ts +8 -0
  24. package/dist-sdk/src/engine/pull/result-output.js +88 -4
  25. package/dist-sdk/src/engine/tf/expr.js +39 -14
  26. package/dist-sdk/src/engine/tf/index.d.ts +3 -3
  27. package/dist-sdk/src/engine/tf/index.js +2 -2
  28. package/dist-sdk/src/engine/tf/labels.d.ts +8 -0
  29. package/dist-sdk/src/engine/tf/labels.js +13 -0
  30. package/dist-sdk/src/engine/tf/model.d.ts +22 -1
  31. package/dist-sdk/src/engine/tf/parse.d.ts +19 -0
  32. package/dist-sdk/src/engine/tf/parse.js +197 -10
  33. package/dist-sdk/src/engine/tf/render.d.ts +4 -2
  34. package/dist-sdk/src/engine/tf/render.js +41 -7
  35. package/dist-sdk/src/engine/validation.d.ts +39 -0
  36. package/dist-sdk/src/engine/validation.js +85 -0
  37. package/dist-sdk/src/engine/workspace/loader.js +49 -12
  38. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +11 -1
  39. package/dist-sdk/src/entities/access-policy/from-tf.js +6 -1
  40. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +11 -0
  41. package/dist-sdk/src/entities/access-policy/to-tf.js +16 -6
  42. package/dist-sdk/src/entities/agent/build.d.ts +4 -16
  43. package/dist-sdk/src/entities/agent/build.js +40 -5
  44. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +4 -2
  45. package/dist-sdk/src/entities/agent/to-tf.js +6 -3
  46. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +2 -0
  47. package/dist-sdk/src/entities/agent-tool/from-tf.js +7 -1
  48. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  49. package/dist-sdk/src/entities/agent-tool/to-tf.js +29 -6
  50. package/dist-sdk/src/entities/app/build.d.ts +98 -19
  51. package/dist-sdk/src/entities/app/build.js +51 -19
  52. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +22 -1
  53. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -0
  54. package/dist-sdk/src/entities/app/from-tf.js +11 -5
  55. package/dist-sdk/src/entities/app/index.d.ts +6 -5
  56. package/dist-sdk/src/entities/app/index.js +2 -0
  57. package/dist-sdk/src/entities/app/module.js +18 -2
  58. package/dist-sdk/src/entities/app/to-tf.js +21 -11
  59. package/dist-sdk/src/entities/automation/build.d.ts +49 -6
  60. package/dist-sdk/src/entities/automation/build.js +163 -19
  61. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +24 -1
  62. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +320 -39
  63. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  64. package/dist-sdk/src/entities/automation/from-tf.js +563 -74
  65. package/dist-sdk/src/entities/automation/generated/task-output-contracts.d.ts +33 -0
  66. package/dist-sdk/src/entities/automation/generated/task-output-contracts.js +183 -0
  67. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  68. package/dist-sdk/src/entities/automation/index.js +1 -1
  69. package/dist-sdk/src/entities/automation/module.d.ts +2 -0
  70. package/dist-sdk/src/entities/automation/module.js +93 -8
  71. package/dist-sdk/src/entities/automation/output-field-types.d.ts +7 -0
  72. package/dist-sdk/src/entities/automation/output-field-types.js +36 -0
  73. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +9 -0
  74. package/dist-sdk/src/entities/automation/output-key-wire-name.js +13 -0
  75. package/dist-sdk/src/entities/automation/script-code.d.ts +17 -0
  76. package/dist-sdk/src/entities/automation/script-code.js +91 -5
  77. package/dist-sdk/src/entities/automation/system-ref-name.d.ts +16 -0
  78. package/dist-sdk/src/entities/automation/system-ref-name.js +48 -0
  79. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +17 -0
  80. package/dist-sdk/src/entities/automation/task-output-labels.js +47 -0
  81. package/dist-sdk/src/entities/automation/tasks.d.ts +53 -4
  82. package/dist-sdk/src/entities/automation/tasks.js +38 -9
  83. package/dist-sdk/src/entities/automation/to-tf.d.ts +4 -0
  84. package/dist-sdk/src/entities/automation/to-tf.js +647 -167
  85. package/dist-sdk/src/entities/automation/triggers.d.ts +4 -2
  86. package/dist-sdk/src/entities/automation/triggers.js +4 -0
  87. package/dist-sdk/src/entities/automation/types.js +1 -0
  88. package/dist-sdk/src/entities/chart/from-tf.js +33 -17
  89. package/dist-sdk/src/entities/chart/module.js +3 -1
  90. package/dist-sdk/src/entities/chart/printer.d.ts +1 -0
  91. package/dist-sdk/src/entities/chart/printer.js +26 -16
  92. package/dist-sdk/src/entities/chart/rebind-owner.d.ts +3 -0
  93. package/dist-sdk/src/entities/chart/rebind-owner.js +42 -0
  94. package/dist-sdk/src/entities/chart/to-tf.js +21 -12
  95. package/dist-sdk/src/entities/dashboard/build.d.ts +4 -0
  96. package/dist-sdk/src/entities/dashboard/from-tf.js +15 -4
  97. package/dist-sdk/src/entities/dashboard/to-tf.d.ts +2 -0
  98. package/dist-sdk/src/entities/dashboard/to-tf.js +13 -0
  99. package/dist-sdk/src/entities/dashboard-widget/module.js +4 -0
  100. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +72 -30
  101. package/dist-sdk/src/entities/dynamic-layout/dialect.d.ts +3 -0
  102. package/dist-sdk/src/entities/dynamic-layout/dialect.js +5 -0
  103. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +9 -6
  104. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +188 -26
  105. package/dist-sdk/src/entities/dynamic-layout/module.js +4 -1
  106. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +5 -1
  107. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +254 -23
  108. package/dist-sdk/src/entities/element/build.d.ts +33 -13
  109. package/dist-sdk/src/entities/element/build.js +5 -1
  110. package/dist-sdk/src/entities/element/from-tf.d.ts +12 -0
  111. package/dist-sdk/src/entities/element/from-tf.js +64 -3
  112. package/dist-sdk/src/entities/element/index.d.ts +5 -2
  113. package/dist-sdk/src/entities/element/index.js +2 -0
  114. package/dist-sdk/src/entities/element/module.js +11 -3
  115. package/dist-sdk/src/entities/element/to-tf.js +20 -2
  116. package/dist-sdk/src/entities/field/build.d.ts +14 -1
  117. package/dist-sdk/src/entities/field/build.js +3 -0
  118. package/dist-sdk/src/entities/field/from-tf.d.ts +3 -0
  119. package/dist-sdk/src/entities/field/from-tf.js +50 -1
  120. package/dist-sdk/src/entities/field/media-types.d.ts +6 -0
  121. package/dist-sdk/src/entities/field/media-types.js +30 -0
  122. package/dist-sdk/src/entities/field/module.js +1 -0
  123. package/dist-sdk/src/entities/field/to-tf.d.ts +23 -2
  124. package/dist-sdk/src/entities/field/to-tf.js +142 -22
  125. package/dist-sdk/src/entities/file-reader/from-tf.js +14 -5
  126. package/dist-sdk/src/entities/file-reader/module.js +1 -0
  127. package/dist-sdk/src/entities/file-reader/types.d.ts +2 -0
  128. package/dist-sdk/src/entities/file-reader/types.js +1 -1
  129. package/dist-sdk/src/entities/portal/build.d.ts +26 -0
  130. package/dist-sdk/src/entities/portal/build.js +37 -0
  131. package/dist-sdk/src/entities/portal/from-tf.d.ts +27 -0
  132. package/dist-sdk/src/entities/portal/from-tf.js +75 -0
  133. package/dist-sdk/src/entities/portal/index.d.ts +1 -0
  134. package/dist-sdk/src/entities/portal/index.js +1 -0
  135. package/dist-sdk/src/entities/portal/module.d.ts +3 -0
  136. package/dist-sdk/src/entities/portal/module.js +28 -0
  137. package/dist-sdk/src/entities/portal/to-tf.d.ts +12 -0
  138. package/dist-sdk/src/entities/portal/to-tf.js +73 -0
  139. package/dist-sdk/src/entities/portal/types.d.ts +1 -0
  140. package/dist-sdk/src/entities/portal/types.js +1 -0
  141. package/dist-sdk/src/entities/relationship/from-tf.d.ts +8 -1
  142. package/dist-sdk/src/entities/relationship/from-tf.js +53 -10
  143. package/dist-sdk/src/entities/relationship/module.js +2 -0
  144. package/dist-sdk/src/entities/relationship/pair-check.d.ts +7 -0
  145. package/dist-sdk/src/entities/relationship/pair-check.js +68 -0
  146. package/dist-sdk/src/entities/relationship/to-tf.d.ts +10 -0
  147. package/dist-sdk/src/entities/relationship/to-tf.js +31 -13
  148. package/dist-sdk/src/entities/search-table/module.js +1 -0
  149. package/dist-sdk/src/entities/search-table/to-tf.d.ts +1 -0
  150. package/dist-sdk/src/entities/search-table/to-tf.js +1 -1
  151. package/dist-sdk/src/entities/service-account/build.d.ts +15 -2
  152. package/dist-sdk/src/entities/service-account/from-tf.d.ts +2 -4
  153. package/dist-sdk/src/entities/service-account/from-tf.js +17 -5
  154. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +56 -0
  155. package/dist-sdk/src/entities/service-account/role-fidelity.js +243 -0
  156. package/dist-sdk/src/entities/service-account/to-tf.d.ts +14 -0
  157. package/dist-sdk/src/entities/service-account/to-tf.js +17 -0
  158. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +1 -1
  159. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +5 -2
  160. package/dist-sdk/src/entities/shared/filters/ast.d.ts +15 -2
  161. package/dist-sdk/src/entities/shared/filters/index.d.ts +25 -2
  162. package/dist-sdk/src/entities/shared/filters/index.js +38 -5
  163. package/dist-sdk/src/entities/shared/filters/print.js +31 -3
  164. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +25 -3
  165. package/dist-sdk/src/entities/shared/filters/tf-codec.js +51 -15
  166. package/dist-sdk/src/entities/shared/filters/types.d.ts +22 -5
  167. package/dist-sdk/src/entities/shared/foreign-ref.d.ts +16 -0
  168. package/dist-sdk/src/entities/shared/foreign-ref.js +17 -1
  169. package/dist-sdk/src/entities/shared/tool-field-ref.js +6 -9
  170. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -5
  171. package/dist-sdk/src/entities/shared/types/field-types.js +4 -0
  172. package/dist-sdk/src/entities/skill/access-policy.d.ts +17 -0
  173. package/dist-sdk/src/entities/skill/access-policy.js +101 -0
  174. package/dist-sdk/src/entities/skill/build.d.ts +3 -0
  175. package/dist-sdk/src/entities/skill/build.js +3 -0
  176. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +4 -1
  177. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +23 -1
  178. package/dist-sdk/src/entities/skill/from-tf.d.ts +2 -0
  179. package/dist-sdk/src/entities/skill/from-tf.js +70 -22
  180. package/dist-sdk/src/entities/skill/index.d.ts +2 -0
  181. package/dist-sdk/src/entities/skill/index.js +1 -0
  182. package/dist-sdk/src/entities/skill/input-coverage.d.ts +7 -0
  183. package/dist-sdk/src/entities/skill/input-coverage.js +11 -0
  184. package/dist-sdk/src/entities/skill/module.js +1 -0
  185. package/dist-sdk/src/entities/skill/to-tf.d.ts +2 -2
  186. package/dist-sdk/src/entities/skill/to-tf.js +19 -6
  187. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  188. package/dist-sdk/src/entities/skill-tool/from-tf.js +8 -2
  189. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -2
  190. package/dist-sdk/src/entities/skill-tool/to-tf.js +29 -6
  191. package/dist-sdk/src/entities/table/catalog.d.ts +14 -0
  192. package/dist-sdk/src/entities/table/catalog.js +66 -0
  193. package/dist-sdk/src/entities/table/module.js +2 -1
  194. package/dist-sdk/src/entities/table/to-tf.js +5 -5
  195. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +89 -0
  196. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +277 -0
  197. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +51 -0
  198. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +360 -0
  199. package/dist-sdk/src/entities/view/agent-view-layout.d.ts +151 -0
  200. package/dist-sdk/src/entities/view/agent-view-layout.js +21 -0
  201. package/dist-sdk/src/entities/view/from-tf.d.ts +6 -3
  202. package/dist-sdk/src/entities/view/from-tf.js +161 -14
  203. package/dist-sdk/src/entities/view/module.js +30 -3
  204. package/dist-sdk/src/entities/view/to-tf.d.ts +24 -2
  205. package/dist-sdk/src/entities/view/to-tf.js +95 -9
  206. package/dist-sdk/src/entities/view/types.d.ts +4 -15
  207. package/dist-sdk/src/entities/view/types.js +17 -15
  208. package/dist-sdk/src/entities/widget/build.d.ts +16 -1
  209. package/dist-sdk/src/entities/widget/build.js +11 -1
  210. package/dist-sdk/src/entities/widget/to-tf.js +36 -10
  211. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +38 -10
  212. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  213. package/dist-sdk/src/graph/index.d.ts +54 -0
  214. package/dist-sdk/src/graph/index.js +30 -0
  215. package/dist-sdk/src/graph/modules.js +2 -0
  216. package/dist-sdk/src/graph/types.d.ts +133 -2
  217. package/dist-sdk/src/internal/sdk-package.d.ts +1 -1
  218. package/dist-sdk/src/internal/sdk-package.js +1 -0
  219. package/package.json +11 -1
@@ -1,8 +1,10 @@
1
- import { USER_FIELD_KEYS } from "../../catalog/types.js";
2
- import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
1
+ import { USER_FIELD_KEYS, USER_GROUP_FIELD_KEYS } from "../../catalog/types.js";
2
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
3
+ import { normalizeOnDemandParamKey } from "../../../pull/util.js";
3
4
  import { EntityTfError } from "../../engine/entity.js";
5
+ import { dataRefLabel } from "../../engine/pull/context.js";
4
6
  import { procedureDiscriminator } from "../../engine/pull/procedure-refs.js";
5
- import { childPartFromScopedLabel, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
7
+ import { appResourceLabelPrefix, childPartFromScopedLabel, elementResourceLabelPrefix, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
6
8
  import { SUB_TYPE_BY_RESOURCE } from "../field/types.js";
7
9
  import { IMPLEMENTED_FILE_READER_RESOURCE_TYPES } from "../file-reader/types.js";
8
10
  import { connectorIdentityFromTf } from "../shared/connector-from-tf.js";
@@ -11,8 +13,10 @@ import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
11
13
  import { filterFromTf as deserializeFilterFromTf } from "../shared/filters/tf-codec.js";
12
14
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
13
15
  import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
14
- import { outputFieldTypesFromScriptSchema, scriptOutputReferenceIsDeclared } from "./output-field-types.js";
16
+ import { outputFieldTypesFromScriptSchema, repeatedScriptOutputNames, scriptOutputReferenceIsDeclared } from "./output-field-types.js";
15
17
  import { apiTaskRefAuthoringPath, matchesOutputWireKey, OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
18
+ import { RESOURCE_TYPE_TO_EXECUTOR, TASK_OUTPUT_CONTRACTS } from "./generated/task-output-contracts.js";
19
+ import { systemRefNameRoundTrips } from "./system-ref-name.js";
16
20
  import { taskTfLabel } from "./task-label.js";
17
21
  import { workflowOutputTypeFromFieldType } from "./workflow-output.js";
18
22
  import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
@@ -58,6 +62,7 @@ const TASK_FACTORIES = {
58
62
  elementum_ai_transform_task: "aiTransform",
59
63
  elementum_save_attachment_task: "saveAttachment",
60
64
  elementum_user_search_task: "userSearch",
65
+ elementum_user_group_search_task: "userGroupSearch",
61
66
  elementum_calculation_task: "calculation",
62
67
  elementum_execute_script_task: "executeScript",
63
68
  elementum_file_reader_task: "documentModel",
@@ -121,6 +126,33 @@ const ATTR_TO_ARG = {
121
126
  function isObject(value) {
122
127
  return value !== null && typeof value === "object" && !Array.isArray(value) && !("$expr" in value);
123
128
  }
129
+ /**
130
+ * Describe a raw output-schema node for a diagnostic: its type tag, a string
131
+ * format, an object's nested property names, and an array's item shape
132
+ * (`string format "DATETIME"`, `object {step, done}`, `array of bool`).
133
+ */
134
+ function describeScriptOutputNode(node) {
135
+ if (!isObject(node))
136
+ return "unknown";
137
+ const [type, definition] = Object.entries(node)[0] ?? [];
138
+ if (type === undefined || !isObject(definition))
139
+ return type ?? "unknown";
140
+ if (type === "string" && typeof definition.format === "string" && definition.format !== "") {
141
+ return `string format ${JSON.stringify(definition.format)}`;
142
+ }
143
+ if (type === "object") {
144
+ const names = Array.isArray(definition.properties)
145
+ ? definition.properties.map((child) => {
146
+ const childDefinition = isObject(child) ? Object.values(child)[0] : undefined;
147
+ return isObject(childDefinition) && typeof childDefinition.name === "string" ? childDefinition.name : "?";
148
+ })
149
+ : [];
150
+ return `object {${names.join(", ")}}`;
151
+ }
152
+ if (type === "array")
153
+ return definition.item === undefined ? "array" : `array of ${describeScriptOutputNode(definition.item)}`;
154
+ return type;
155
+ }
124
156
  /**
125
157
  * Map a string output-schema node back to a product scalar.
126
158
  * DATE/DATETIME/EMAIL/UUID4 become date/datetime/email/uuid4. A missing
@@ -169,6 +201,42 @@ function resourceRef(value) {
169
201
  ? { type: value.type, label: value.label, path: value.path }
170
202
  : undefined;
171
203
  }
204
+ /**
205
+ * A Run Automation input mapping names its parameter through the trigger (or
206
+ * data lookup) of the automation that owns it, but pulled source only keeps
207
+ * the parameter NAME and build resolves it on the task's target. When the
208
+ * exported owner is provably a different automation than the target, the
209
+ * mapping cannot round-trip; report it instead of re-pointing it silently.
210
+ * Owners that cannot be resolved inside this export are not judged.
211
+ */
212
+ function inputMappingOwnerMismatch(block, parameter, ctx) {
213
+ const automationAddress = (value) => {
214
+ if (!isTfExpr(value))
215
+ return undefined;
216
+ const ref = value;
217
+ if ((ref.$expr === "resource-attr" || ref.$expr === "data-attr") && ref.type === AUTOMATION_RESOURCE_TYPE) {
218
+ return `${ref.$expr === "data-attr" ? "data." : ""}${ref.type}.${ref.label}`;
219
+ }
220
+ return undefined;
221
+ };
222
+ const target = automationAddress(block.attrs.target_automation_id);
223
+ if (target === undefined)
224
+ return undefined;
225
+ if (parameter.$expr === "data-attr") {
226
+ const owner = automationAddress(parameter);
227
+ return owner !== undefined && owner !== target ? { parameterOwner: owner, target } : undefined;
228
+ }
229
+ if (parameter.$expr !== "resource-attr")
230
+ return undefined;
231
+ const triggerAddress = `${parameter.type}.${parameter.label}`;
232
+ const trigger = ctx.resourceBlocks.get(triggerAddress);
233
+ const owningAutomation = resourceRef(trigger?.attrs.automation);
234
+ if (owningAutomation === undefined || owningAutomation.type !== AUTOMATION_RESOURCE_TYPE)
235
+ return undefined;
236
+ return `${owningAutomation.type}.${owningAutomation.label}` !== target
237
+ ? { parameterOwner: triggerAddress, target }
238
+ : undefined;
239
+ }
172
240
  function references(value, type, label) {
173
241
  const ref = resourceRef(value);
174
242
  return ref?.type === type && ref.label === label;
@@ -279,6 +347,8 @@ const TASK_ATTRIBUTES = new Set([
279
347
  "basic_auth", "bearer_auth", "oauth", "json_body", "form_body", "custom_body", "multipart_body",
280
348
  "query",
281
349
  ]);
350
+ /** A notification's description is a value reference like its title and message. */
351
+ const NOTIFICATION_TASK_ATTRIBUTES = new Set([...TASK_ATTRIBUTES, "description"]);
282
352
  const BRANCH_ATTRIBUTES = new Set([
283
353
  "switch_task", "fork_join_task", "label", "is_default", "filter",
284
354
  "previous_case_id", "previous_branch_id",
@@ -310,6 +380,11 @@ const WIRE_REF_SEGMENT_TO_TS = {
310
380
  "Message ID": "messageId",
311
381
  "Message Metadata": "messageMetadata",
312
382
  };
383
+ const ON_DEMAND_TRIGGERED_BY_FROM_WIRE = {
384
+ "Triggered By's Id": ["triggeredBy", "id"],
385
+ "Triggered By's Email": ["triggeredBy", "email"],
386
+ "Triggered By's Name": ["triggeredBy", "name"],
387
+ };
313
388
  const FIELD_REF_SUFFIX_FROM_WIRE = [
314
389
  [" Manager Email", ["employee", "manager", "email"]],
315
390
  [" Manager Name", ["employee", "manager", "name"]],
@@ -354,17 +429,30 @@ function recordFieldRefPath(wireName, ctx, ownerRefName = ctx.appRefName, rootNa
354
429
  continue;
355
430
  const base = wireName.slice(0, wireName.length - suffix.length);
356
431
  const fieldKey = lookupFieldKeyByDisplayName(ownerRefName, base, ctx);
357
- if (fieldKey !== undefined) {
432
+ if (fieldKey !== undefined && systemFieldPathRoundTrips(fieldKey, suffix, wireName)) {
358
433
  return [rootName, fieldKey, ...suffixPath];
359
434
  }
360
435
  }
361
- // System fields have no `*_field` resource block, so they never appear in
362
- // fieldById. Match their provider-default display names explicitly.
436
+ const systemPath = systemFieldRefPath(wireName);
437
+ return systemPath === undefined ? undefined : [rootName, ...systemPath];
438
+ }
439
+ function systemFieldPathRoundTrips(fieldKey, wireSuffix, wireName) {
440
+ return !SYSTEM_FIELD_KEY_SET.has(fieldKey) ||
441
+ systemRefNameRoundTrips(fieldKey, wireSuffix, wireName);
442
+ }
443
+ /**
444
+ * System fields have no `*_field` resource block, so they never appear in
445
+ * fieldById. Match their provider-default display names explicitly, but only
446
+ * when a rebuild of the typed path emits the same refs key; otherwise the
447
+ * caller keeps the org's exact label.
448
+ */
449
+ function systemFieldRefPath(wireName) {
450
+ const wireNameLower = wireName.toLowerCase();
363
451
  for (const key of SYSTEM_FIELD_KEYS) {
364
452
  const defaultName = DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key];
365
453
  for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
366
- if (wireNameLower === `${defaultName}${suffix}`.toLowerCase()) {
367
- return [rootName, key, ...suffixPath];
454
+ if (wireNameLower === `${defaultName}${suffix}`.toLowerCase() && systemRefNameRoundTrips(key, suffix, wireName)) {
455
+ return [key, ...suffixPath];
368
456
  }
369
457
  }
370
458
  }
@@ -387,6 +475,38 @@ function isDeclaredOnDemandParameter(trigger, wireName) {
387
475
  const parameters = trigger.attrs.parameters;
388
476
  return Array.isArray(parameters) && parameters.some((parameter) => isObject(parameter) && parameter.name === wireName);
389
477
  }
478
+ /**
479
+ * The platform stores a reference to an on-demand input under its normalized
480
+ * name (`normalizeOnDemandFilterRefName`: "TICKET_ID" → "ticketId"), whatever
481
+ * spelling the reference was authored with. Map that wire name back to the
482
+ * one declared scalar input it normalizes from, so pulled source addresses
483
+ * the input as declared (`ctx.trigger.TICKET_ID`).
484
+ */
485
+ function declaredOnDemandInputForWireName(trigger, wireName) {
486
+ if (trigger.type !== "elementum_on_demand_trigger" || !Array.isArray(trigger.attrs.parameters))
487
+ return undefined;
488
+ if (isDeclaredOnDemandParameter(trigger, wireName))
489
+ return undefined;
490
+ const matches = trigger.attrs.parameters.flatMap((parameter) => isObject(parameter) && typeof parameter.name === "string" && parameter.type !== "record" &&
491
+ normalizeOnDemandParamKey(parameter.name) === wireName
492
+ ? [parameter.name]
493
+ : []);
494
+ return matches.length === 1 ? matches[0] : undefined;
495
+ }
496
+ /** The declared field type of the scalar on-demand input a trigger reference names (declared or normalized spelling). */
497
+ function declaredOnDemandInputFieldType(trigger, wireName) {
498
+ if (trigger.type !== "elementum_on_demand_trigger" || !Array.isArray(trigger.attrs.parameters))
499
+ return undefined;
500
+ const name = declaredOnDemandInputForWireName(trigger, wireName) ?? wireName;
501
+ const parameter = trigger.attrs.parameters.find((candidate) => isObject(candidate) && candidate.name === name);
502
+ if (!isObject(parameter) || typeof parameter.type !== "string" || parameter.type === "record")
503
+ return undefined;
504
+ return {
505
+ // Inverse of to-tf's on-demand parameter type spelling.
506
+ fieldType: parameter.type === "attachment" ? "ATTACHMENT_ID" : parameter.type.toUpperCase(),
507
+ multiple: parameter.multiple === true,
508
+ };
509
+ }
390
510
  function onDemandRecordParameters(trigger) {
391
511
  if (trigger.type !== "elementum_on_demand_trigger" || !Array.isArray(trigger.attrs.parameters))
392
512
  return [];
@@ -429,11 +549,11 @@ const RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS = {
429
549
  /**
430
550
  * The same outputs as seen from a CALCULATION formula, which addresses a
431
551
  * reference by its WorkflowTaskReference name rather than the refs-map
432
- * display key above (`to-tf.ts`'s `CALCULATION_TASK_OUTPUT_REF_NAME` is the
552
+ * display key above (`task-output-labels.ts`'s `TASK_OUTPUT_REFERENCE_NAMES` is the
433
553
  * write side). Only the names that differ from their authoring path are
434
554
  * listed; the rest already read back correctly.
435
555
  */
436
- const RECORD_SEARCH_CALCULATION_REF_NAME_TO_TS = {
556
+ export const RECORD_SEARCH_CALCULATION_REF_NAME_TO_TS = {
437
557
  count: ["totalCount"],
438
558
  recordId: ["record", "recordId"],
439
559
  };
@@ -441,17 +561,60 @@ const RECORD_SEARCH_CALCULATION_REF_NAME_TO_TS = {
441
561
  // RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS: "All Records" is a platform-fixed
442
562
  // wire key on elementum_ai_search_table_task only. A trigger field could
443
563
  // coincidentally share that display name and must not be rewritten here.
444
- const AI_SEARCH_TABLE_TASK_REF_SEGMENT_TO_TS = {
564
+ export const AI_SEARCH_TABLE_TASK_REF_SEGMENT_TO_TS = {
565
+ // "searchTableRecords" is the CANONICAL output name a workflow output emits
566
+ // (edk#835 — the forward maps the `.records` accessor to it); "All Records" is
567
+ // the legacy display form kept for already-deployed HCL. Both decode to `.records`.
568
+ searchTableRecords: "records",
445
569
  "All Records": "records",
570
+ searchTableRecordsText: "recordsText",
571
+ "All Records Text": "recordsText",
572
+ searchTableRecordsJson: "recordsJson",
573
+ "All Records JSON": "recordsJson",
574
+ firstFoundRecordText: "firstRecordText",
575
+ "First Record Text": "firstRecordText",
576
+ firstFoundRecordJson: "firstRecordJson",
577
+ "First Record JSON": "firstRecordJson",
446
578
  };
447
579
  // tableRecordsSearch collection output — platform wire key
448
580
  // "All matching table rows" (not recordSearch's "All found records" or
449
581
  // aiSearchTable's "All Records"). Leaving it unmapped prints
450
582
  // `(ctx.actions.x as any)["All matching table rows"]`, which drops the Ref
451
583
  // proxy at build time and omits the script/filter input entirely.
452
- const TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS = {
584
+ export const TABLE_RECORDS_SEARCH_TASK_REF_SEGMENT_TO_TS = {
585
+ // Canonical count output `count` → the `totalCount` accessor (edk#835 — same
586
+ // as recordSearch). "All matching table rows" is the legacy display form.
587
+ count: "totalCount",
453
588
  "All matching table rows": "records",
454
589
  };
590
+ // Platform-fixed output labels → authoring path, inverse of
591
+ // task-output-labels.ts and executeScript's "Text Result". Scoped per task
592
+ // type: a field may share a label elsewhere.
593
+ const TASK_OUTPUT_LABEL_TO_TS = {
594
+ elementum_record_search_task: { "First found record": ["record"] },
595
+ elementum_create_record_task: { "Created record": ["record"] },
596
+ elementum_update_field_task: { "Updated record": ["record"] },
597
+ elementum_execute_script_task: { "Text Result": ["textResult"] },
598
+ elementum_user_search_task: {
599
+ "Users Size": ["count"],
600
+ "User's Id": ["user", "id"],
601
+ "User's Name": ["user", "name"],
602
+ "User's Email": ["user", "email"],
603
+ "Manager Name": ["user", "managerName"],
604
+ "Manager Email": ["user", "managerEmail"],
605
+ "All found users": ["users"],
606
+ },
607
+ };
608
+ // userGroupSearch refs-map keys → authoring path; inverse of build.ts's
609
+ // USER_GROUP_SEARCH_REF_WIRE_NAMES. "ID"/"Name" are only these outputs on
610
+ // elementum_user_group_search_task, so the table must stay scoped to it.
611
+ const USER_GROUP_SEARCH_TASK_REF_LABEL_TO_TS = {
612
+ "Groups Size": ["count"],
613
+ "First found group": ["group"],
614
+ ID: ["group", "id"],
615
+ Name: ["group", "name"],
616
+ "All found groups": ["groups"],
617
+ };
455
618
  /**
456
619
  * Restore the public aiAgent `.result` shape from either a provider refs-map
457
620
  * key (`Action Response` / authored schema field) or the nested platform
@@ -791,6 +954,11 @@ function triggerRefPath(path, ctx) {
791
954
  const recordPath = prefixedOnDemandRecordRefPath(wireName, ctx);
792
955
  if (recordPath !== undefined)
793
956
  return recordPath;
957
+ const triggeredBy = ON_DEMAND_TRIGGERED_BY_FROM_WIRE[wireName];
958
+ const declaresTriggeredBy = Array.isArray(ctx.trigger.attrs.parameters) &&
959
+ ctx.trigger.attrs.parameters.some((parameter) => isObject(parameter) && parameter.name === "triggeredBy");
960
+ if (triggeredBy !== undefined && !declaresTriggeredBy)
961
+ return [...triggeredBy];
794
962
  }
795
963
  // An on-demand parameter is an explicitly declared top-level ctx.trigger
796
964
  // property. Check this before record-field inference: a perfectly ordinary
@@ -830,7 +998,8 @@ function forEachItemRefPath(path, ctx) {
830
998
  if (names.length !== 1)
831
999
  return names.flatMap((segment) => segment.split("."));
832
1000
  const wireName = names[0];
833
- if (wireName === "item")
1001
+ // "" is a plain-list loop's whole item (provider Read: `for_each.<id>.`).
1002
+ if (wireName === "item" || wireName === "")
834
1003
  return [];
835
1004
  if (wireName === "Record")
836
1005
  return ["recordId"];
@@ -847,15 +1016,7 @@ function forEachItemRefPath(path, ctx) {
847
1016
  }
848
1017
  }
849
1018
  }
850
- for (const key of SYSTEM_FIELD_KEYS) {
851
- const defaultName = DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key];
852
- for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
853
- if (wireNameLower === `${defaultName}${suffix}`.toLowerCase()) {
854
- return [key, ...suffixPath];
855
- }
856
- }
857
- }
858
- return names.flatMap((segment) => segment.split("."));
1019
+ return systemFieldRefPath(wireName) ?? names.flatMap((segment) => segment.split("."));
859
1020
  }
860
1021
  function resolveTaskRefKey(taskIdOrKey, ctx) {
861
1022
  if (/^[a-f0-9-]{36}$/.test(taskIdOrKey)) {
@@ -911,8 +1072,12 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
911
1072
  }
912
1073
  if (block?.type === "elementum_record_search_task" && pathSegments.length >= 1) {
913
1074
  const [head, ...tail] = pathSegments;
914
- if (head === "count") {
915
- return { kind: "taskRef", task: refKey, path: ["totalCount", ...tail] };
1075
+ // Canonical output names whose authoring path differs from the wire name
1076
+ // (count → .totalCount, recordId → .record.recordId) — the exact inverse of
1077
+ // rewriteCanonicalOutputRefName's forward map (edk#835).
1078
+ const canonicalPath = RECORD_SEARCH_CALCULATION_REF_NAME_TO_TS[head];
1079
+ if (canonicalPath !== undefined) {
1080
+ return { kind: "taskRef", task: refKey, path: [...canonicalPath, ...tail] };
916
1081
  }
917
1082
  const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[head];
918
1083
  if (recordSearchName !== undefined) {
@@ -956,6 +1121,16 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
956
1121
  return { kind: "taskRef", task: refKey, path: [tableSearchName, ...tail] };
957
1122
  }
958
1123
  }
1124
+ if (block?.type === "elementum_user_group_search_task" && pathSegments.length === 1) {
1125
+ const groupPath = USER_GROUP_SEARCH_TASK_REF_LABEL_TO_TS[pathSegments[0]];
1126
+ if (groupPath !== undefined)
1127
+ return { kind: "taskRef", task: refKey, path: [...groupPath] };
1128
+ }
1129
+ if (block?.type === "elementum_user_search_task" && pathSegments.length === 1) {
1130
+ const userPath = TASK_OUTPUT_LABEL_TO_TS.elementum_user_search_task?.[pathSegments[0]];
1131
+ if (userPath !== undefined)
1132
+ return { kind: "taskRef", task: refKey, path: [...userPath] };
1133
+ }
959
1134
  // createRecord/findRelatedRecords record-id + field outputs (same as the
960
1135
  // refs["Title"] / refs["Record"] resource-attr path in decodeValue).
961
1136
  if ((block?.type === "elementum_create_record_task" || block?.type === "elementum_find_related_records_task") &&
@@ -964,10 +1139,7 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
964
1139
  if (pathSegments.length === 1 && (head === "Record" || head === "Record ID")) {
965
1140
  return { kind: "taskRef", task: refKey, path: ["record", "recordId"] };
966
1141
  }
967
- if (block.type === "elementum_create_record_task" &&
968
- head === "record" &&
969
- tail.length >= 1 &&
970
- /^[a-f0-9-]{36}$/i.test(tail[0])) {
1142
+ if (head === "record" && tail.length >= 1 && /^[a-f0-9-]{36}$/i.test(tail[0])) {
971
1143
  const taskAddress = block.label !== undefined ? `${block.type}.${block.label}` : undefined;
972
1144
  const ownerRefName = taskAddress !== undefined
973
1145
  ? ctx.taskTargetOwnerRefNameByAddress?.get(taskAddress) ?? ctx.appRefName
@@ -1010,6 +1182,9 @@ function decodeReferenceString(value, ctx) {
1010
1182
  const pieces = value.split(".");
1011
1183
  if (pieces[0] === "trigger" && pieces.length > 1) {
1012
1184
  const path = pieces.slice(1);
1185
+ const declaredInput = path.length === 1 ? declaredOnDemandInputForWireName(ctx.trigger, path[0]) : undefined;
1186
+ if (declaredInput !== undefined)
1187
+ return { kind: "triggerRef", path: [declaredInput] };
1013
1188
  if (path[0] === "record" && path.length >= 2 && /^[a-f0-9-]{36}$/.test(path[1])) {
1014
1189
  const sourceFieldId = path[1];
1015
1190
  const field = ctx.fieldById.get(sourceFieldId);
@@ -1072,18 +1247,35 @@ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
1072
1247
  if (!isTfExpr(value) || value.$expr !== "template")
1073
1248
  return undefined;
1074
1249
  const [prefix, fieldPart, suffixPart] = value.parts;
1075
- if (prefix !== "trigger.record." || fieldPart === undefined || typeof fieldPart === "string")
1250
+ if (typeof prefix !== "string" || fieldPart === undefined || typeof fieldPart === "string")
1251
+ return undefined;
1252
+ const root = prefix === "trigger.record."
1253
+ ? "record"
1254
+ : onDemandRecordParameters(ctx.trigger)
1255
+ .map((parameter) => parameter.name)
1256
+ .find((name) => prefix === `trigger.${name}.`);
1257
+ if (root === undefined)
1076
1258
  return undefined;
1077
1259
  if (suffixPart !== undefined && typeof suffixPart !== "string")
1078
1260
  return undefined;
1079
- const fieldKey = fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx);
1261
+ const parameter = onDemandRecordParameters(ctx.trigger).find((candidate) => candidate.name === root);
1262
+ const hasTarget = parameter?.default_value !== undefined && parameter.default_value !== null;
1263
+ const fieldKey = hasTarget
1264
+ ? fieldKeyOnRecordParameterTarget(fieldPart, parameter.default_value, ctx)
1265
+ : fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx);
1266
+ if (fieldKey === undefined && hasTarget) {
1267
+ const fieldId = fieldPart.$expr === "resource-attr" ? `${fieldPart.type}.${fieldPart.label}.id`
1268
+ : fieldPart.$expr === "local" ? `local.${fieldPart.name}`
1269
+ : "field";
1270
+ return { kind: "unresolved", uuid: `${prefix}${fieldId}${suffixPart ?? ""}`, hint: `field of on-demand record input "${root}"` };
1271
+ }
1080
1272
  if (fieldKey === undefined)
1081
1273
  return undefined;
1082
1274
  const suffix = suffixPart === undefined ? [] : suffixPart.replace(/^\./, "").split(".").filter((s) => s.length > 0);
1083
1275
  if (suffix.length === 1 && suffix[0] === "10000001-2000-4000-a000-800000000000") {
1084
- return { kind: "triggerRef", path: ["record", fieldKey, "recordId"] };
1276
+ return { kind: "triggerRef", path: [root, fieldKey, "recordId"] };
1085
1277
  }
1086
- return { kind: "triggerRef", path: ["record", fieldKey, ...suffix] };
1278
+ return { kind: "triggerRef", path: [root, fieldKey, ...suffix] };
1087
1279
  }
1088
1280
  /**
1089
1281
  * Inverse of filterReferenceToTf's TASK case: filters render
@@ -1093,9 +1285,10 @@ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
1093
1285
  function decodeTemplateTaskRef(value, ctx) {
1094
1286
  if (!isTfExpr(value) || value.$expr !== "template")
1095
1287
  return undefined;
1096
- const [prefix, idPart, suffixPart] = value.parts;
1288
+ const [prefix, idPart, ...nameTemplate] = mergeAdjacentTemplateStrings(value.parts);
1097
1289
  if (prefix !== "task." || idPart === undefined || typeof idPart === "string")
1098
1290
  return undefined;
1291
+ const suffixPart = nameTemplate[0];
1099
1292
  if (typeof suffixPart !== "string" || !suffixPart.startsWith("."))
1100
1293
  return undefined;
1101
1294
  if (!isTfExpr(idPart) || idPart.$expr !== "resource-attr" || idPart.path[0] !== "id")
@@ -1103,11 +1296,47 @@ function decodeTemplateTaskRef(value, ctx) {
1103
1296
  const task = ctx.taskByAddress.get(`${idPart.type}.${idPart.label}`);
1104
1297
  if (task === undefined)
1105
1298
  return undefined;
1299
+ if (nameTemplate.length > 1) {
1300
+ const path = templateRecordFieldPath([suffixPart.slice(1), ...nameTemplate.slice(1)], task.block, ctx);
1301
+ return path === undefined ? undefined : { kind: "taskRef", task: task.refKey, path };
1302
+ }
1106
1303
  const nameParts = suffixPart.slice(1).split(".").filter((segment) => segment.length > 0);
1107
1304
  if (nameParts.length === 0)
1108
1305
  return undefined;
1109
1306
  return decodeTaskReferenceFromString(task.refKey, nameParts, ctx);
1110
1307
  }
1308
+ function mergeAdjacentTemplateStrings(parts) {
1309
+ const out = [];
1310
+ for (const part of parts) {
1311
+ const last = out[out.length - 1];
1312
+ if (typeof part === "string" && typeof last === "string")
1313
+ out[out.length - 1] = last + part;
1314
+ else
1315
+ out.push(part);
1316
+ }
1317
+ return out;
1318
+ }
1319
+ /**
1320
+ * Inverse of to-tf's `foundRecordFieldReferenceName`: a found record's field
1321
+ * built as `record.${<field id expr>}[.suffix]`. Only the automation's own
1322
+ * app's field labels decode by tf label; another app's do not, so a task
1323
+ * targeting one stays undefined rather than guessing its field.
1324
+ */
1325
+ function templateRecordFieldPath(parts, taskBlock, ctx) {
1326
+ const [head, fieldPart, suffixPart, ...rest] = mergeAdjacentTemplateStrings(parts);
1327
+ if (head !== "record." || fieldPart === undefined || typeof fieldPart === "string" || rest.length > 0)
1328
+ return undefined;
1329
+ if (suffixPart !== undefined && (typeof suffixPart !== "string" || !suffixPart.startsWith(".")))
1330
+ return undefined;
1331
+ const taskAddress = taskBlock.label !== undefined ? `${taskBlock.type}.${taskBlock.label}` : undefined;
1332
+ const ownerRefName = taskAddress !== undefined ? ctx.taskTargetOwnerRefNameByAddress?.get(taskAddress) : undefined;
1333
+ if (ownerRefName !== undefined && ownerRefName !== ctx.appRefName)
1334
+ return undefined;
1335
+ const fieldKey = fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx);
1336
+ if (fieldKey === undefined)
1337
+ return undefined;
1338
+ return ["record", fieldKey, ...(suffixPart ?? "").split(".").filter((segment) => segment.length > 0)];
1339
+ }
1111
1340
  function decodeTemplateForEachRef(value, ctx) {
1112
1341
  if (!isTfExpr(value) || value.$expr !== "template")
1113
1342
  return undefined;
@@ -1122,7 +1351,7 @@ function decodeTemplateForEachRef(value, ctx) {
1122
1351
  if (task === undefined)
1123
1352
  return undefined;
1124
1353
  const nameParts = suffixPart.slice(1).split(".").filter((segment) => segment.length > 0);
1125
- if (nameParts.length === 0)
1354
+ if (nameParts.length === 0 && suffixPart !== ".")
1126
1355
  return undefined;
1127
1356
  return {
1128
1357
  kind: "forEachItemRef",
@@ -1139,6 +1368,35 @@ function decodeTemplateForEachRef(value, ctx) {
1139
1368
  * decodeValue's generic local handling, but resolves to a triggerRef bag key
1140
1369
  * instead of a "field" RefExpr so it stays a valid filter LHS.
1141
1370
  */
1371
+ /**
1372
+ * A field id under an on-demand record input belongs to that input's target
1373
+ * (its `default_value`). Another app's or element's field decodes only when its
1374
+ * label carries that owner's prefix; anything else stays unresolved rather
1375
+ * than becoming a made-up key on the parameter.
1376
+ */
1377
+ function fieldKeyOnRecordParameterTarget(fieldPart, target, ctx) {
1378
+ if (!isTfExpr(target) ||
1379
+ (target.$expr !== "resource-attr" && target.$expr !== "data-attr") ||
1380
+ (target.type !== "elementum_app" && target.type !== "elementum_element") ||
1381
+ target.path[0] !== "id") {
1382
+ return undefined;
1383
+ }
1384
+ if (target.$expr === "resource-attr" && target.label === ctx.appTfLabel) {
1385
+ return fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx);
1386
+ }
1387
+ const scope = target.type === "elementum_element" ? "element" : "app";
1388
+ if (fieldPart.$expr === "resource-attr" && fieldPart.type.endsWith("_field") && fieldPart.path[0] === "id") {
1389
+ const prefix = scope === "element" ? elementResourceLabelPrefix(target.label) : appResourceLabelPrefix(target.label);
1390
+ return fieldPart.label.startsWith(prefix) ? scopedLabelToBagKey(target.label, fieldPart.label, scope) : undefined;
1391
+ }
1392
+ if (fieldPart.$expr === "local") {
1393
+ const prefix = `${target.label}_`;
1394
+ if (fieldPart.name.startsWith(prefix) && fieldPart.name.endsWith("_field_id")) {
1395
+ return tfLabelToTsLabel(fieldPart.name.slice(prefix.length, -"_field_id".length));
1396
+ }
1397
+ }
1398
+ return undefined;
1399
+ }
1142
1400
  function fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx) {
1143
1401
  if (fieldPart.$expr === "resource-attr" && fieldPart.type.endsWith("_field") && fieldPart.path[0] === "id") {
1144
1402
  return scopedLabelToBagKey(ctx.appTfLabel, fieldPart.label);
@@ -1239,6 +1497,22 @@ function decodeSearchTableReference(value, ctx) {
1239
1497
  if (isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_search_table") {
1240
1498
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1241
1499
  const name = typeof lookup?.attrs.name === "string" ? lookup.attrs.name : undefined;
1500
+ const pinnedId = typeof lookup?.attrs.id === "string" && lookup.attrs.id !== "" ? lookup.attrs.id : undefined;
1501
+ const tableLabel = dataRefLabel(lookup?.attrs.table_id, TABLE_RESOURCE_TYPE);
1502
+ if (tableLabel !== undefined) {
1503
+ const tableName = ctx.dataBlocks.get(`${TABLE_RESOURCE_TYPE}.${tableLabel}`)?.attrs.name;
1504
+ const parentName = typeof tableName === "string" && tableName !== "" ? tableName : undefined;
1505
+ const parent = parentName !== undefined ? tfLabelToTsLabel(sanitizeName(parentName)) : tfLabelToTsLabel(tableLabel);
1506
+ return {
1507
+ kind: "searchTable",
1508
+ appHandle: parent,
1509
+ tableKey: name !== undefined ? tfLabelToTsLabel(sanitizeName(name)) : value.label,
1510
+ ...(name !== undefined ? { name } : {}),
1511
+ ...(parentName !== undefined ? { parentName } : {}),
1512
+ ...(pinnedId !== undefined ? { id: pinnedId } : {}),
1513
+ ownerKind: "table",
1514
+ };
1515
+ }
1242
1516
  const objectId = lookup?.attrs.object_id ?? lookup?.attrs.aspect_id;
1243
1517
  const elementHandle = objectId !== undefined
1244
1518
  ? aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames)
@@ -1283,6 +1557,11 @@ function decodeSearchTableReference(value, ctx) {
1283
1557
  }
1284
1558
  return { kind: "unresolved", uuid: typeof value === "string" ? value : JSON.stringify(value), hint: "search table" };
1285
1559
  }
1560
+ /** A `data.elementum_user` reference pulls as `userRef(email)`; a raw id stays a string, which build refuses. */
1561
+ function userIdDefault(value, ctx) {
1562
+ const decoded = decodeValue(value, ctx);
1563
+ return decoded?.kind === "user" ? decoded : value;
1564
+ }
1286
1565
  function decodeValue(value, ctx) {
1287
1566
  if (isTfExpr(value)) {
1288
1567
  if (value.$expr === "template") {
@@ -1313,6 +1592,13 @@ function decodeValue(value, ctx) {
1313
1592
  return { kind: "taskRef", task: task.refKey, path: aiAgentPath };
1314
1593
  }
1315
1594
  }
1595
+ const blockType = task.block.type;
1596
+ const labelPath = rawSegments.length === 1 && blockType !== undefined
1597
+ ? TASK_OUTPUT_LABEL_TO_TS[blockType]?.[rawSegments[0]]
1598
+ : undefined;
1599
+ if (labelPath !== undefined) {
1600
+ return { kind: "taskRef", task: task.refKey, path: [...labelPath] };
1601
+ }
1316
1602
  if (task.block.type === "elementum_record_search_task" && rawSegments.length === 1 && rawSegments[0] === "First found record id") {
1317
1603
  return { kind: "taskRef", task: task.refKey, path: ["record", "recordId"] };
1318
1604
  }
@@ -1369,6 +1655,12 @@ function decodeValue(value, ctx) {
1369
1655
  return { kind: "taskRef", task: task.refKey, path: [tableSearchName] };
1370
1656
  }
1371
1657
  }
1658
+ if (task.block.type === "elementum_user_group_search_task" && rawSegments.length === 1) {
1659
+ const groupPath = USER_GROUP_SEARCH_TASK_REF_LABEL_TO_TS[rawSegments[0]];
1660
+ if (groupPath !== undefined) {
1661
+ return { kind: "taskRef", task: task.refKey, path: [...groupPath] };
1662
+ }
1663
+ }
1372
1664
  // apiRequest's refs map uses display labels ("File", "Content Type",
1373
1665
  // …) that don't match the lowercase authoring property names
1374
1666
  // (`file`, `file.contentType`) - see API_TASK_REF_AUTHORING_NAMES.
@@ -1659,6 +1951,12 @@ function decodeValue(value, ctx) {
1659
1951
  }
1660
1952
  return { kind: "user", email };
1661
1953
  }
1954
+ if (value.$expr === "variable") {
1955
+ if (value.path.length !== 0) {
1956
+ throw new EntityTfError(`unsupported variable reference var.${value.name}`);
1957
+ }
1958
+ return { kind: "requiredSecret", variable: value.name };
1959
+ }
1662
1960
  if (value.$expr === "local") {
1663
1961
  const stageName = stageFilterName(value, ctx);
1664
1962
  if (stageName !== undefined)
@@ -1799,6 +2097,17 @@ function userFieldRef(value, ctx) {
1799
2097
  }
1800
2098
  return fieldRef(value, ctx);
1801
2099
  }
2100
+ const USER_GROUP_FIELD_KEY_SET = new Set(USER_GROUP_FIELD_KEYS);
2101
+ function userGroupFieldRef(value, ctx) {
2102
+ if (typeof value === "string" && USER_GROUP_FIELD_KEY_SET.has(value)) {
2103
+ return { kind: "userGroupField", fieldKey: value };
2104
+ }
2105
+ return fieldRef(value, ctx);
2106
+ }
2107
+ const FILTER_FIELD_SCOPE_BY_FACTORY = {
2108
+ userSearch: "user",
2109
+ userGroupSearch: "userGroup",
2110
+ };
1802
2111
  function picklistOptionLabel(value) {
1803
2112
  if (value === undefined || !isTfExpr(value))
1804
2113
  return undefined;
@@ -2132,6 +2441,15 @@ function decodeFilterReferenceEnvelope(value, ctx, outputName, role) {
2132
2441
  return decoded;
2133
2442
  }
2134
2443
  }
2444
+ if (isObject(taskRef) && isTfExpr(taskRef.name) && taskRef.name.$expr === "template") {
2445
+ const taskIdOrKey = workflowOutputTaskIdOrKey(taskRef.taskId, ctx);
2446
+ const { refKey, block } = taskIdOrKey !== undefined ? resolveTaskRefKey(taskIdOrKey, ctx) : { refKey: undefined, block: undefined };
2447
+ const path = block !== undefined
2448
+ ? templateRecordFieldPath(taskRef.name.parts, block, ctx)
2449
+ : undefined;
2450
+ if (refKey !== undefined && path !== undefined)
2451
+ return { kind: "taskRef", task: refKey, path };
2452
+ }
2135
2453
  const triggerRef = raw.triggerReference;
2136
2454
  if (isObject(triggerRef) && typeof triggerRef.name === "string") {
2137
2455
  return decodeReferenceString(`trigger.${triggerRef.name}`, ctx);
@@ -2204,8 +2522,31 @@ function filterReferenceType(value, fallback, ctx) {
2204
2522
  }
2205
2523
  return typeof raw.fieldType === "string" ? fieldTypeToValueType(raw.fieldType) : fallback;
2206
2524
  }
2525
+ /**
2526
+ * True when a workflow output references an execute-script output whose name
2527
+ * the stored schema lists more than once. Pull keeps the first entry, and
2528
+ * export/provider type the output from it; an older export typed it from the
2529
+ * LAST entry, so its envelope type is not authored intent.
2530
+ */
2531
+ function referencesRepeatedScriptOutput(value, ctx) {
2532
+ const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
2533
+ if (!isObject(raw) || !isObject(raw.taskReference) || typeof raw.taskReference.name !== "string")
2534
+ return false;
2535
+ const taskIdOrKey = workflowOutputTaskIdOrKey(raw.taskReference.taskId, ctx);
2536
+ const task = taskIdOrKey === undefined ? undefined : resolveTaskRefKey(taskIdOrKey, ctx).block;
2537
+ if (task?.type !== "elementum_execute_script_task")
2538
+ return false;
2539
+ const schemaValue = task.attrs.output_schema;
2540
+ const schema = isTfExpr(schemaValue) && schemaValue.$expr === "jsonencode"
2541
+ ? schemaValue.value
2542
+ : schemaValue;
2543
+ return repeatedScriptOutputNames(schema).has(raw.taskReference.name);
2544
+ }
2207
2545
  export function inferredPublishOutputType(value, ctx) {
2208
2546
  const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
2547
+ if (isObject(raw) && isObject(raw.triggerReference) && typeof raw.triggerReference.name === "string") {
2548
+ return declaredOnDemandInputFieldType(ctx.trigger, raw.triggerReference.name) ?? { fieldType: "TEXT", multiple: false };
2549
+ }
2209
2550
  if (!isObject(raw) || !isObject(raw.taskReference) || typeof raw.taskReference.name !== "string") {
2210
2551
  return { fieldType: "TEXT", multiple: false };
2211
2552
  }
@@ -2230,6 +2571,16 @@ export function inferredPublishOutputType(value, ctx) {
2230
2571
  return { fieldType: field.type.toUpperCase(), multiple: false };
2231
2572
  }
2232
2573
  }
2574
+ // Canonical reference model: a workflow OUTPUT carries the platform's canonical
2575
+ // output name — take fieldType + multiple from the generated service_tasks
2576
+ // contract (the display-name heuristics below remain for legacy deployed HCL).
2577
+ // See DESIGN-canonical-reference-model.md.
2578
+ if (task?.type !== undefined) {
2579
+ const executor = RESOURCE_TYPE_TO_EXECUTOR[task.type];
2580
+ const contract = executor !== undefined ? TASK_OUTPUT_CONTRACTS[executor]?.[raw.taskReference.name] : undefined;
2581
+ if (contract !== undefined)
2582
+ return { fieldType: contract.fieldType, multiple: contract.multiple };
2583
+ }
2233
2584
  if ((task?.type === "elementum_create_record_task" || task?.type === "elementum_find_related_records_task") &&
2234
2585
  (raw.taskReference.name === "Record" || raw.taskReference.name === "Record ID")) {
2235
2586
  return { fieldType: "ASPECT_RECORD_ID", multiple: false };
@@ -2248,7 +2599,9 @@ export function inferredPublishOutputType(value, ctx) {
2248
2599
  function decodeFilter(value, ctx, fieldScope = "app") {
2249
2600
  return deserializeFilterFromTf(value, {
2250
2601
  field: (fieldValue, scope) => {
2251
- const field = scope === "user" ? userFieldRef(fieldValue, ctx) : filterFieldRef(fieldValue, ctx);
2602
+ const field = scope === "user"
2603
+ ? userFieldRef(fieldValue, ctx)
2604
+ : scope === "userGroup" ? userGroupFieldRef(fieldValue, ctx) : filterFieldRef(fieldValue, ctx);
2252
2605
  return field ?? { kind: "unresolved", uuid: String(fieldValue), hint: "field" };
2253
2606
  },
2254
2607
  reference: (reference, role) => filterReference(reference, ctx, role),
@@ -2275,8 +2628,11 @@ function triggerFromBlock(block, ctx) {
2275
2628
  // no "attachmentId" spelling at all, but the authoring alias
2276
2629
  // (onDemand's TriggerFieldTypeAlias) does. Map back so printed
2277
2630
  // source uses a type-checkable alias instead of a raw wire string
2278
- // "attachment" that TriggerFieldTypeAlias doesn't accept.
2279
- const type = parameter.type === "attachment" ? "attachmentId" : parameter.type;
2631
+ // "attachment" that TriggerFieldTypeAlias doesn't accept. The
2632
+ // provider's "user" is USER_ID, authored as "userId".
2633
+ const type = parameter.type === "attachment" ? "attachmentId"
2634
+ : parameter.type === "user" ? "userId"
2635
+ : parameter.type;
2280
2636
  const record = type === "record";
2281
2637
  const recordApp = record
2282
2638
  ? aspectRefFromObjectId(parameter.default_value, ctx)
@@ -2290,7 +2646,9 @@ function triggerFromBlock(block, ctx) {
2290
2646
  ...(recordApp !== undefined ? { app: recordApp } : {}),
2291
2647
  ...(parameter.required === true ? { required: true } : {}),
2292
2648
  ...(parameter.multiple === true ? { multiple: true } : {}),
2293
- ...(!record && parameter.default_value !== undefined ? { defaultValue: parameter.default_value } : {}),
2649
+ ...(!record && parameter.default_value !== undefined
2650
+ ? { defaultValue: type === "userId" ? userIdDefault(parameter.default_value, ctx) : parameter.default_value }
2651
+ : {}),
2294
2652
  ...(typeof parameter.description === "string" ? { description: parameter.description } : {}),
2295
2653
  };
2296
2654
  })
@@ -2391,13 +2749,13 @@ function triggerFromBlock(block, ctx) {
2391
2749
  default: throw new EntityTfError(`trigger "${kind}" is outside the Terraform contract`);
2392
2750
  }
2393
2751
  }
2394
- function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2752
+ function taskArgs(block, factory, ctx, taskDiagnostics) {
2395
2753
  const args = {};
2396
2754
  for (const [attr, value] of Object.entries(block.attrs)) {
2397
2755
  if (attr === "parent" || attr === "name" || attr === "depends_on")
2398
2756
  continue;
2399
2757
  if (attr === "filter") {
2400
- args.filter = decodeFilter(value, ctx, factory === "userSearch" ? "user" : "app");
2758
+ args.filter = decodeFilter(value, ctx, FILTER_FIELD_SCOPE_BY_FACTORY[factory] ?? "app");
2401
2759
  continue;
2402
2760
  }
2403
2761
  if (attr === "fields" && (factory === "createRecord" || factory === "updateField")) {
@@ -2464,7 +2822,7 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2464
2822
  // throwing out of taskArgs, which would drop the WHOLE automation
2465
2823
  // (a live-caught regression in an earlier attempt at this fix).
2466
2824
  if (mapping.field_id === undefined) {
2467
- fieldMappingDiagnostics.push(`execute-script input "${item.name}" field_mappings entry ${JSON.stringify(mapping.alias)}: no field_id on the platform; dropped`);
2825
+ taskDiagnostics.push(`execute-script input "${item.name}" field_mappings entry ${JSON.stringify(mapping.alias)}: no field_id on the platform; dropped`);
2468
2826
  continue;
2469
2827
  }
2470
2828
  // A PRESENT but unreconstructable field_id (fieldRef throws) is
@@ -2486,7 +2844,54 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2486
2844
  const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
2487
2845
  const root = isObject(raw) && isObject(raw.object) ? raw.object : undefined;
2488
2846
  const props = Array.isArray(root?.properties) ? root.properties : [];
2489
- const decodeNode = (node) => {
2847
+ // The platform stores (and export/import return) every entry of a
2848
+ // properties list, including a name listed twice. The public `outputs`
2849
+ // option is keyed by name and cannot carry the repeat, so keep the
2850
+ // FIRST occurrence (position and type) and report the collapse: the
2851
+ // rebuilt schema no longer matches live. The provider refreshes
2852
+ // output_schema on every Read, so the next plan shows the in-place
2853
+ // update and applying it removes the repeat. outputFieldTypesFromScriptSchema
2854
+ // resolves a repeated name to the same first entry, so ref typing and
2855
+ // workflow-output inference agree with the pulled `outputs`.
2856
+ const decodeProperties = (nodes, path) => {
2857
+ const nested = path !== "root";
2858
+ // A Map, not `{}`: a platform property named `__proto__` assigned onto
2859
+ // a plain object hits the legacy prototype setter and is dropped (or,
2860
+ // object-shaped, becomes the prototype). Object.fromEntries below
2861
+ // defines every name, `__proto__` included, as an own key.
2862
+ const properties = new Map();
2863
+ const kept = new Map();
2864
+ const repeats = new Map();
2865
+ for (const node of nodes) {
2866
+ if (!isObject(node)) {
2867
+ throw new EntityTfError(nested ? "invalid nested script output property" : "invalid script output schema");
2868
+ }
2869
+ const [type, definition] = Object.entries(node)[0] ?? [];
2870
+ if (type === undefined || !isObject(definition) || typeof definition.name !== "string") {
2871
+ throw new EntityTfError(nested ? "nested script output property requires a name" : "invalid script output property");
2872
+ }
2873
+ const decoded = decodeNode(node, `${path}.${definition.name}`);
2874
+ if (properties.has(definition.name)) {
2875
+ const differs = JSON.stringify(decoded) !== JSON.stringify(properties.get(definition.name));
2876
+ repeats.set(definition.name, [...(repeats.get(definition.name) ?? []), { node, differs }]);
2877
+ continue;
2878
+ }
2879
+ properties.set(definition.name, decoded);
2880
+ kept.set(definition.name, node);
2881
+ }
2882
+ for (const [name, dropped] of repeats) {
2883
+ const droppedShapes = dropped.map(({ node, differs }) => `${describeScriptOutputNode(node)} (${differs ? "differs from" : "identical to"} the kept shape)`);
2884
+ taskDiagnostics.push(`${block.type}.${block.label}: output_schema ${path} lists duplicate property ${JSON.stringify(name)} ` +
2885
+ `${dropped.length + 1} times; outputs is keyed by name, so pulled source keeps only the first, ` +
2886
+ `${describeScriptOutputNode(kept.get(name))}, and drops the later ` +
2887
+ `entr${dropped.length === 1 ? "y" : "ies"} ${droppedShapes.join(", ")} - ` +
2888
+ `the provider reads the live schema, so the next plan updates this task's output_schema in place, ` +
2889
+ `and applying it removes the repeat from the automation's draft; the published workflow keeps it until ` +
2890
+ `the automation's revision is bumped and republished`);
2891
+ }
2892
+ return Object.fromEntries(properties);
2893
+ };
2894
+ const decodeNode = (node, path) => {
2490
2895
  if (!isObject(node))
2491
2896
  throw new EntityTfError("invalid script output schema node");
2492
2897
  const [type, definition] = Object.entries(node)[0] ?? [];
@@ -2499,34 +2904,18 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2499
2904
  : undefined;
2500
2905
  return {
2501
2906
  type: "array",
2502
- items: decodeNode(definition.item),
2907
+ items: decodeNode(definition.item, `${path}[]`),
2503
2908
  ...(itemName !== undefined ? { itemName } : {}),
2504
2909
  };
2505
2910
  }
2506
2911
  if (type === "object" && Array.isArray(definition.properties)) {
2507
- const properties = Object.fromEntries(definition.properties.map((child) => {
2508
- if (!isObject(child))
2509
- throw new EntityTfError("invalid nested script output property");
2510
- const childDefinition = Object.values(child)[0];
2511
- if (!isObject(childDefinition) || typeof childDefinition.name !== "string") {
2512
- throw new EntityTfError("nested script output property requires a name");
2513
- }
2514
- return [childDefinition.name, decodeNode(child)];
2515
- }));
2516
- return { type: "object", properties };
2912
+ return { type: "object", properties: decodeProperties(definition.properties, path) };
2517
2913
  }
2518
2914
  if (type === "string")
2519
2915
  return scriptOutputScalarFromStringNode(definition);
2520
2916
  return type === "bool" ? "boolean" : type;
2521
2917
  };
2522
- const properties = Object.fromEntries(props.map((property) => {
2523
- if (!isObject(property))
2524
- throw new EntityTfError("invalid script output schema");
2525
- const definition = Object.values(property)[0];
2526
- if (!isObject(definition) || typeof definition.name !== "string")
2527
- throw new EntityTfError("invalid script output property");
2528
- return [definition.name, decodeNode(property)];
2529
- }));
2918
+ const properties = decodeProperties(props, "root");
2530
2919
  // The root object's own name is inert to the platform but real stored
2531
2920
  // data, so carry it through rather than rebuilding a schema that
2532
2921
  // differs from the one just read.
@@ -2553,7 +2942,14 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2553
2942
  parameter.path[1] !== null &&
2554
2943
  "index" in parameter.path[1] &&
2555
2944
  typeof parameter.path[1].index === "string") {
2556
- return { name: parameter.path[1].index, value: decodeValue(item.value, ctx) };
2945
+ const name = parameter.path[1].index;
2946
+ const mismatch = inputMappingOwnerMismatch(block, parameter, ctx);
2947
+ if (mismatch !== undefined) {
2948
+ taskDiagnostics.push(`${block.type}.${block.label}: input mapping ${JSON.stringify(name)} names ${mismatch.parameterOwner}'s parameter, ` +
2949
+ `but the task targets ${mismatch.target}; pulled source maps ${JSON.stringify(name)} by name on the target, ` +
2950
+ "so build will not reproduce the exported mapping");
2951
+ }
2952
+ return { name, value: decodeValue(item.value, ctx) };
2557
2953
  }
2558
2954
  // ei emits bare platform parameter UUIDs when the target automation's
2559
2955
  // onDemand trigger is not in this export (foreign / undiscovered).
@@ -3035,8 +3431,10 @@ function taskRefKey(block, automationLabel, appTfLabel) {
3035
3431
  * driving spurious destroys). Deliberately lenient - tolerant of the exact
3036
3432
  * conditions that make real extraction fail (zero triggers, an
3037
3433
  * unrecognized task kind) so it over-collects rather than under-collects.
3038
- * More than one trigger is not one of those cases: it throws
3039
- * {@link UnsupportedMultiTriggerError} and stops the pull. A false positive
3434
+ * More than one trigger throws {@link UnsupportedMultiTriggerError}. The
3435
+ * stream extractor records that as a fatal validation, excludes these
3436
+ * addresses, and continues so every multi-trigger automation is reported.
3437
+ * A false positive
3040
3438
  * here just leaves one more resource unmanaged; a false negative would
3041
3439
  * silently destroy a live automation on apply.
3042
3440
  */
@@ -3091,6 +3489,73 @@ function withExportedVariableId(block, ids) {
3091
3489
  return block;
3092
3490
  return { ...block, attrs: { ...block.attrs, variable_id: exported } };
3093
3491
  }
3492
+ /**
3493
+ * #1320: a task may read the current item of a loop that ENCLOSES it - the
3494
+ * nearest as `ctx.item`, an outer one as `ctx.loops.<name>.item` - but not of
3495
+ * a loop that doesn't (a sibling, already finished when the task runs). The
3496
+ * builder never offers that reference and its validation flags it invalid, so
3497
+ * EDK has no public form for it. Returns the first such reader so the caller
3498
+ * can exclude the automation. Scoping matches print-automation's
3499
+ * selfTaskRefKeys: a forEach's own args (its collection) sit outside its loop;
3500
+ * workflow outputs sit outside every loop.
3501
+ */
3502
+ function forEachItemRefOutsideItsLoop(topTasks, outputValues) {
3503
+ const loopNames = new Map();
3504
+ const collectLoops = (tasks) => {
3505
+ for (const task of tasks) {
3506
+ if (task.factory === "forEach")
3507
+ loopNames.set(task.refKey, task.displayName ?? task.refKey);
3508
+ for (const child of task.children ?? [])
3509
+ collectLoops(child.tasks);
3510
+ }
3511
+ };
3512
+ collectLoops(topTasks);
3513
+ const loopName = (refKey) => loopNames.get(refKey) ?? refKey;
3514
+ const outsideRef = (value, enclosing) => {
3515
+ if (Array.isArray(value)) {
3516
+ for (const item of value) {
3517
+ const found = outsideRef(item, enclosing);
3518
+ if (found !== undefined)
3519
+ return found;
3520
+ }
3521
+ return undefined;
3522
+ }
3523
+ if (!isObject(value))
3524
+ return undefined;
3525
+ if (value.kind === "forEachItemRef" && typeof value.forEachTask === "string" && !enclosing.includes(value.forEachTask)) {
3526
+ return value.forEachTask;
3527
+ }
3528
+ for (const nested of Object.values(value)) {
3529
+ const found = outsideRef(nested, enclosing);
3530
+ if (found !== undefined)
3531
+ return found;
3532
+ }
3533
+ return undefined;
3534
+ };
3535
+ const walk = (tasks, enclosing) => {
3536
+ for (const task of tasks) {
3537
+ const reader = `task "${task.displayName ?? task.refKey}"`;
3538
+ const inArgs = outsideRef(task.args, enclosing);
3539
+ if (inArgs !== undefined)
3540
+ return { reader, loop: loopName(inArgs) };
3541
+ const bodyScope = task.factory === "forEach" ? [...enclosing, task.refKey] : enclosing;
3542
+ for (const child of task.children ?? []) {
3543
+ const inFilter = outsideRef(child.filter, bodyScope);
3544
+ if (inFilter !== undefined)
3545
+ return { reader, loop: loopName(inFilter) };
3546
+ const nested = walk(child.tasks, bodyScope);
3547
+ if (nested !== undefined)
3548
+ return nested;
3549
+ }
3550
+ }
3551
+ return undefined;
3552
+ };
3553
+ const inTasks = walk(topTasks, []);
3554
+ if (inTasks !== undefined)
3555
+ return inTasks;
3556
+ const inOutputs = outsideRef(outputValues, []);
3557
+ return inOutputs === undefined ? undefined : { reader: "a workflow output", loop: loopName(inOutputs) };
3558
+ }
3094
3559
  /** Bridge metadata for required values that GraphQL could not reconstruct. */
3095
3560
  function unresolvedAuthoringValues(doc) {
3096
3561
  const values = [];
@@ -3115,10 +3580,11 @@ function unresolvedAuthoringValues(doc) {
3115
3580
  return values;
3116
3581
  }
3117
3582
  /**
3118
- * Pull stops on this. EDK does not author multi-trigger automations; apps
3119
- * should keep one trigger and call the shared logic with a run-automation
3120
- * action. Callers that otherwise turn extract failures into skips must
3121
- * rethrow it.
3583
+ * EDK does not author multi-trigger automations; apps should keep one
3584
+ * trigger and call the shared logic with a run-automation action. Stream
3585
+ * extraction records every one of these and continues. Direct
3586
+ * `automationFromTf` still throws. Callers that turn other extract failures
3587
+ * into soft skips must not treat this as one of those skips.
3122
3588
  */
3123
3589
  export class UnsupportedMultiTriggerError extends EntityTfError {
3124
3590
  automationName;
@@ -3131,6 +3597,20 @@ export class UnsupportedMultiTriggerError extends EntityTfError {
3131
3597
  this.triggerCount = triggerCount;
3132
3598
  }
3133
3599
  }
3600
+ /**
3601
+ * #1320: a task reads the current item of a loop that doesn't enclose it.
3602
+ * Pull skips the automation like any other exclusion, and additionally
3603
+ * releases it from state if an earlier pull adopted it: no authored source can
3604
+ * ever manage it, so keeping it bound would make the next apply destroy it.
3605
+ */
3606
+ export class ForEachItemOutsideLoopError extends EntityTfError {
3607
+ constructor(automationLabel, reader, loop) {
3608
+ super(`automation "${automationLabel}": ${reader} reads the current item of loop "${loop}", ` +
3609
+ "which does not enclose it (a sibling loop that has already finished); the platform builder never offers " +
3610
+ "this reference and flags it invalid, so the automation is excluded because EDK has no safe authored form for it");
3611
+ this.name = "ForEachItemOutsideLoopError";
3612
+ }
3613
+ }
3134
3614
  /** Extract one app-owned automation graph from an ei app export. */
3135
3615
  function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator, foreignTaskRefNames) {
3136
3616
  const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
@@ -3215,7 +3695,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3215
3695
  throw new EntityTfError(`${unresolved.resource}.${unresolved.field}: ${unresolved.reason}; ` +
3216
3696
  "the automation is excluded because no safe authored value or UUID fallback is available");
3217
3697
  }
3218
- tasks.forEach((block) => assertAllowed(block, TASK_ATTRIBUTES));
3698
+ tasks.forEach((block) => assertAllowed(block, block.type === "elementum_notification_task" ? NOTIFICATION_TASK_ATTRIBUTES : TASK_ATTRIBUTES));
3219
3699
  ownedBranches.forEach((block) => assertAllowed(block, BRANCH_ATTRIBUTES));
3220
3700
  const publishDependencies = Array.isArray(publish?.attrs.depends_on)
3221
3701
  ? publish.attrs.depends_on.map((value) => resourceRef(value)).filter((value) => value !== undefined)
@@ -3358,7 +3838,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3358
3838
  dependencyOrder.set(`${ref.type}.${ref.label}`, index); });
3359
3839
  const triggerAddress = `${trigger.type}.${trigger.label}`;
3360
3840
  const unrebuildableTasks = [];
3361
- const fieldMappingDiagnostics = [];
3841
+ const taskDiagnostics = [];
3362
3842
  // edk#821: resolve each elementum_unmanaged_task_reference this automation's
3363
3843
  // OWN tasks actually parent onto (never the whole doc's data blocks - a
3364
3844
  // sibling automation sharing this export can have its own, edk#785) to its
@@ -3462,7 +3942,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3462
3942
  id: typeof block.attrs.id === "string" ? block.attrs.id : "",
3463
3943
  taskType: typeof block.attrs.task_type === "string" ? block.attrs.task_type : "",
3464
3944
  }
3465
- : taskArgs(block, factory, ctx, fieldMappingDiagnostics);
3945
+ : taskArgs(block, factory, ctx, taskDiagnostics);
3466
3946
  const call = { factory, refKey, args, ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
3467
3947
  visiting.delete(address);
3468
3948
  return [call, ...buildTasks(address)];
@@ -3490,6 +3970,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3490
3970
  if (inferred.fieldType === fieldType && inferred.multiple === multiple) {
3491
3971
  return { name: output.name, value };
3492
3972
  }
3973
+ // A repeated script output name has one public type, its first entry's
3974
+ // (already reported by the duplicate diagnostic); build infers it, and
3975
+ // export/provider read it back the same way.
3976
+ if (referencesRepeatedScriptOutput(output.value, ctx)) {
3977
+ return { name: output.name, value };
3978
+ }
3493
3979
  const explicitType = workflowOutputTypeFromFieldType(fieldType);
3494
3980
  if (explicitType === undefined) {
3495
3981
  outputDiagnostics.push(`automation "${automationLabel}" workflow output "${output.name}" has explicit field type ` +
@@ -3506,6 +3992,9 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3506
3992
  }
3507
3993
  return { name: output.name, value, explicitType, explicitMultiple: multiple };
3508
3994
  }) : undefined;
3995
+ const outOfLoop = forEachItemRefOutsideItsLoop(topTasks, outputs?.map((output) => output.value) ?? []);
3996
+ if (outOfLoop !== undefined)
3997
+ throw new ForEachItemOutsideLoopError(automationLabel, outOfLoop.reader, outOfLoop.loop);
3509
3998
  const exportedRevision = publish?.attrs.workflow_revision;
3510
3999
  if (exportedRevision !== undefined && typeof exportedRevision !== "string") {
3511
4000
  throw new EntityTfError(`${WORKFLOW_PUBLISH_RESOURCE_TYPE}.${automationLabel}: workflow_revision must be a string`);
@@ -3528,12 +4017,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3528
4017
  ast,
3529
4018
  blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
3530
4019
  adoptionAddressAliases,
3531
- ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || fieldMappingDiagnostics.length > 0) && {
4020
+ ...((unrebuildableTasks.length > 0 || placeholderTasks.length > 0 || outputDiagnostics.length > 0 || taskDiagnostics.length > 0) && {
3532
4021
  diagnostics: [
3533
4022
  ...unrebuildableTasks.map((address) => `automation "${automationLabel}": ${address}'s real parent is a task type EDK doesn't support yet, so its authored position couldn't be reconstructed (anchored to the trigger instead) - not rebuildable from this source until that task type is supported`),
3534
4023
  ...placeholderTasks.map(({ name, taskType }) => `automation "${automationLabel}" uses platform task type "${taskType}" ("${name}"), which EDK doesn't implement - kept as an unimplementedTask(...) placeholder; its configuration isn't authorable, but its position and downstream chain are round-trip-safe`),
3535
4024
  ...outputDiagnostics,
3536
- ...fieldMappingDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
4025
+ ...taskDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
3537
4026
  ],
3538
4027
  }),
3539
4028
  };