@elementumai/edk 0.9.19 → 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 (176) hide show
  1. package/README.md +146 -6
  2. package/dist-sdk/src/catalog/factories.d.ts +24 -1
  3. package/dist-sdk/src/catalog/factories.js +30 -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/render.js +6 -6
  9. package/dist-sdk/src/catalog/token.js +7 -0
  10. package/dist-sdk/src/catalog/types.d.ts +34 -1
  11. package/dist-sdk/src/catalog/types.js +11 -0
  12. package/dist-sdk/src/core/triggers/on-demand.d.ts +39 -3
  13. package/dist-sdk/src/core/triggers/on-demand.js +10 -2
  14. package/dist-sdk/src/engine/build/context.d.ts +1 -1
  15. package/dist-sdk/src/engine/ei/run.d.ts +149 -0
  16. package/dist-sdk/src/engine/ei/run.js +1132 -0
  17. package/dist-sdk/src/engine/logging.d.ts +17 -0
  18. package/dist-sdk/src/engine/logging.js +18 -0
  19. package/dist-sdk/src/engine/pull/ref-only.d.ts +5 -0
  20. package/dist-sdk/src/engine/pull/ref-only.js +10 -7
  21. package/dist-sdk/src/engine/pull/result-output.d.ts +6 -0
  22. package/dist-sdk/src/engine/pull/result-output.js +87 -3
  23. package/dist-sdk/src/engine/tf/expr.js +1 -1
  24. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  25. package/dist-sdk/src/engine/tf/index.js +1 -1
  26. package/dist-sdk/src/engine/tf/labels.d.ts +6 -0
  27. package/dist-sdk/src/engine/tf/labels.js +9 -0
  28. package/dist-sdk/src/engine/tf/model.d.ts +22 -1
  29. package/dist-sdk/src/engine/tf/parse.js +92 -4
  30. package/dist-sdk/src/engine/tf/render.d.ts +4 -2
  31. package/dist-sdk/src/engine/tf/render.js +41 -7
  32. package/dist-sdk/src/engine/validation.d.ts +39 -0
  33. package/dist-sdk/src/engine/validation.js +85 -0
  34. package/dist-sdk/src/entities/access-policy/to-tf.js +5 -2
  35. package/dist-sdk/src/entities/agent/build.d.ts +4 -16
  36. package/dist-sdk/src/entities/agent/build.js +40 -5
  37. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +4 -2
  38. package/dist-sdk/src/entities/agent/to-tf.js +6 -3
  39. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +2 -0
  40. package/dist-sdk/src/entities/agent-tool/from-tf.js +7 -1
  41. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  42. package/dist-sdk/src/entities/agent-tool/to-tf.js +27 -5
  43. package/dist-sdk/src/entities/app/build.d.ts +89 -20
  44. package/dist-sdk/src/entities/app/build.js +51 -6
  45. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +16 -0
  46. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -0
  47. package/dist-sdk/src/entities/app/from-tf.js +7 -2
  48. package/dist-sdk/src/entities/app/index.d.ts +6 -6
  49. package/dist-sdk/src/entities/app/index.js +1 -0
  50. package/dist-sdk/src/entities/app/module.js +5 -2
  51. package/dist-sdk/src/entities/app/to-tf.js +19 -11
  52. package/dist-sdk/src/entities/automation/build.d.ts +47 -5
  53. package/dist-sdk/src/entities/automation/build.js +137 -20
  54. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +24 -1
  55. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +314 -39
  56. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  57. package/dist-sdk/src/entities/automation/from-tf.js +428 -48
  58. package/dist-sdk/src/entities/automation/generated/task-output-contracts.d.ts +33 -0
  59. package/dist-sdk/src/entities/automation/generated/task-output-contracts.js +183 -0
  60. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  61. package/dist-sdk/src/entities/automation/index.js +1 -1
  62. package/dist-sdk/src/entities/automation/module.js +37 -8
  63. package/dist-sdk/src/entities/automation/output-field-types.d.ts +7 -0
  64. package/dist-sdk/src/entities/automation/output-field-types.js +36 -0
  65. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +9 -0
  66. package/dist-sdk/src/entities/automation/output-key-wire-name.js +13 -0
  67. package/dist-sdk/src/entities/automation/script-code.d.ts +17 -0
  68. package/dist-sdk/src/entities/automation/script-code.js +91 -5
  69. package/dist-sdk/src/entities/automation/system-ref-name.js +4 -0
  70. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +2 -0
  71. package/dist-sdk/src/entities/automation/task-output-labels.js +9 -0
  72. package/dist-sdk/src/entities/automation/tasks.d.ts +24 -2
  73. package/dist-sdk/src/entities/automation/tasks.js +38 -9
  74. package/dist-sdk/src/entities/automation/to-tf.d.ts +4 -0
  75. package/dist-sdk/src/entities/automation/to-tf.js +489 -83
  76. package/dist-sdk/src/entities/automation/triggers.d.ts +4 -2
  77. package/dist-sdk/src/entities/automation/triggers.js +4 -0
  78. package/dist-sdk/src/entities/chart/to-tf.js +10 -3
  79. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +24 -31
  80. package/dist-sdk/src/entities/element/build.d.ts +25 -13
  81. package/dist-sdk/src/entities/element/build.js +4 -1
  82. package/dist-sdk/src/entities/element/from-tf.d.ts +11 -0
  83. package/dist-sdk/src/entities/element/from-tf.js +58 -1
  84. package/dist-sdk/src/entities/element/index.d.ts +5 -3
  85. package/dist-sdk/src/entities/element/index.js +1 -0
  86. package/dist-sdk/src/entities/element/module.js +9 -3
  87. package/dist-sdk/src/entities/element/to-tf.js +8 -2
  88. package/dist-sdk/src/entities/field/build.d.ts +14 -1
  89. package/dist-sdk/src/entities/field/build.js +3 -0
  90. package/dist-sdk/src/entities/field/from-tf.d.ts +1 -0
  91. package/dist-sdk/src/entities/field/from-tf.js +39 -1
  92. package/dist-sdk/src/entities/field/media-types.d.ts +6 -0
  93. package/dist-sdk/src/entities/field/media-types.js +30 -0
  94. package/dist-sdk/src/entities/field/module.js +1 -0
  95. package/dist-sdk/src/entities/field/to-tf.d.ts +23 -2
  96. package/dist-sdk/src/entities/field/to-tf.js +130 -14
  97. package/dist-sdk/src/entities/file-reader/from-tf.js +14 -5
  98. package/dist-sdk/src/entities/file-reader/module.js +1 -0
  99. package/dist-sdk/src/entities/file-reader/types.d.ts +2 -0
  100. package/dist-sdk/src/entities/file-reader/types.js +1 -1
  101. package/dist-sdk/src/entities/portal/build.d.ts +26 -0
  102. package/dist-sdk/src/entities/portal/build.js +37 -0
  103. package/dist-sdk/src/entities/portal/from-tf.d.ts +27 -0
  104. package/dist-sdk/src/entities/portal/from-tf.js +75 -0
  105. package/dist-sdk/src/entities/portal/index.d.ts +1 -0
  106. package/dist-sdk/src/entities/portal/index.js +1 -0
  107. package/dist-sdk/src/entities/portal/module.d.ts +3 -0
  108. package/dist-sdk/src/entities/portal/module.js +28 -0
  109. package/dist-sdk/src/entities/portal/to-tf.d.ts +12 -0
  110. package/dist-sdk/src/entities/portal/to-tf.js +73 -0
  111. package/dist-sdk/src/entities/portal/types.d.ts +1 -0
  112. package/dist-sdk/src/entities/portal/types.js +1 -0
  113. package/dist-sdk/src/entities/relationship/module.js +2 -0
  114. package/dist-sdk/src/entities/relationship/pair-check.d.ts +7 -0
  115. package/dist-sdk/src/entities/relationship/pair-check.js +68 -0
  116. package/dist-sdk/src/entities/relationship/to-tf.d.ts +2 -0
  117. package/dist-sdk/src/entities/relationship/to-tf.js +12 -3
  118. package/dist-sdk/src/entities/search-table/module.js +1 -0
  119. package/dist-sdk/src/entities/search-table/to-tf.d.ts +1 -0
  120. package/dist-sdk/src/entities/search-table/to-tf.js +1 -1
  121. package/dist-sdk/src/entities/service-account/build.d.ts +15 -2
  122. package/dist-sdk/src/entities/service-account/from-tf.d.ts +2 -4
  123. package/dist-sdk/src/entities/service-account/from-tf.js +17 -5
  124. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +56 -0
  125. package/dist-sdk/src/entities/service-account/role-fidelity.js +243 -0
  126. package/dist-sdk/src/entities/service-account/to-tf.d.ts +14 -0
  127. package/dist-sdk/src/entities/service-account/to-tf.js +17 -0
  128. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +1 -1
  129. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +5 -2
  130. package/dist-sdk/src/entities/shared/filters/ast.d.ts +8 -0
  131. package/dist-sdk/src/entities/shared/filters/index.d.ts +2 -0
  132. package/dist-sdk/src/entities/shared/filters/index.js +14 -4
  133. package/dist-sdk/src/entities/shared/filters/print.js +17 -1
  134. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +2 -0
  135. package/dist-sdk/src/entities/shared/filters/tf-codec.js +5 -1
  136. package/dist-sdk/src/entities/shared/filters/types.d.ts +9 -1
  137. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -5
  138. package/dist-sdk/src/entities/shared/types/field-types.js +4 -0
  139. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +2 -1
  140. package/dist-sdk/src/entities/skill/from-tf.js +66 -13
  141. package/dist-sdk/src/entities/skill/input-coverage.d.ts +7 -0
  142. package/dist-sdk/src/entities/skill/input-coverage.js +11 -0
  143. package/dist-sdk/src/entities/skill/to-tf.js +14 -4
  144. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  145. package/dist-sdk/src/entities/skill-tool/from-tf.js +8 -2
  146. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -2
  147. package/dist-sdk/src/entities/skill-tool/to-tf.js +27 -5
  148. package/dist-sdk/src/entities/table/catalog.d.ts +14 -0
  149. package/dist-sdk/src/entities/table/catalog.js +66 -0
  150. package/dist-sdk/src/entities/table/module.js +2 -1
  151. package/dist-sdk/src/entities/table/to-tf.js +2 -2
  152. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +49 -9
  153. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +71 -18
  154. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +19 -4
  155. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +82 -10
  156. package/dist-sdk/src/entities/view/agent-view-layout.d.ts +53 -23
  157. package/dist-sdk/src/entities/view/agent-view-layout.js +1 -1
  158. package/dist-sdk/src/entities/view/from-tf.d.ts +3 -2
  159. package/dist-sdk/src/entities/view/from-tf.js +124 -12
  160. package/dist-sdk/src/entities/view/module.js +30 -3
  161. package/dist-sdk/src/entities/view/to-tf.d.ts +14 -1
  162. package/dist-sdk/src/entities/view/to-tf.js +67 -10
  163. package/dist-sdk/src/entities/view/types.d.ts +4 -15
  164. package/dist-sdk/src/entities/view/types.js +15 -15
  165. package/dist-sdk/src/entities/widget/build.d.ts +16 -1
  166. package/dist-sdk/src/entities/widget/build.js +11 -1
  167. package/dist-sdk/src/entities/widget/to-tf.js +34 -8
  168. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +16 -5
  169. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  170. package/dist-sdk/src/graph/index.d.ts +11 -0
  171. package/dist-sdk/src/graph/index.js +21 -0
  172. package/dist-sdk/src/graph/modules.js +2 -0
  173. package/dist-sdk/src/graph/types.d.ts +55 -2
  174. package/dist-sdk/src/internal/sdk-package.d.ts +1 -1
  175. package/dist-sdk/src/internal/sdk-package.js +1 -0
  176. package/package.json +10 -1
@@ -1,8 +1,10 @@
1
1
  import { USER_FIELD_KEYS, USER_GROUP_FIELD_KEYS } from "../../catalog/types.js";
2
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,9 @@ 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";
16
19
  import { systemRefNameRoundTrips } from "./system-ref-name.js";
17
20
  import { taskTfLabel } from "./task-label.js";
18
21
  import { workflowOutputTypeFromFieldType } from "./workflow-output.js";
@@ -123,6 +126,33 @@ const ATTR_TO_ARG = {
123
126
  function isObject(value) {
124
127
  return value !== null && typeof value === "object" && !Array.isArray(value) && !("$expr" in value);
125
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
+ }
126
156
  /**
127
157
  * Map a string output-schema node back to a product scalar.
128
158
  * DATE/DATETIME/EMAIL/UUID4 become date/datetime/email/uuid4. A missing
@@ -171,6 +201,42 @@ function resourceRef(value) {
171
201
  ? { type: value.type, label: value.label, path: value.path }
172
202
  : undefined;
173
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
+ }
174
240
  function references(value, type, label) {
175
241
  const ref = resourceRef(value);
176
242
  return ref?.type === type && ref.label === label;
@@ -281,6 +347,8 @@ const TASK_ATTRIBUTES = new Set([
281
347
  "basic_auth", "bearer_auth", "oauth", "json_body", "form_body", "custom_body", "multipart_body",
282
348
  "query",
283
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"]);
284
352
  const BRANCH_ATTRIBUTES = new Set([
285
353
  "switch_task", "fork_join_task", "label", "is_default", "filter",
286
354
  "previous_case_id", "previous_branch_id",
@@ -312,6 +380,11 @@ const WIRE_REF_SEGMENT_TO_TS = {
312
380
  "Message ID": "messageId",
313
381
  "Message Metadata": "messageMetadata",
314
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
+ };
315
388
  const FIELD_REF_SUFFIX_FROM_WIRE = [
316
389
  [" Manager Email", ["employee", "manager", "email"]],
317
390
  [" Manager Name", ["employee", "manager", "name"]],
@@ -402,6 +475,38 @@ function isDeclaredOnDemandParameter(trigger, wireName) {
402
475
  const parameters = trigger.attrs.parameters;
403
476
  return Array.isArray(parameters) && parameters.some((parameter) => isObject(parameter) && parameter.name === wireName);
404
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
+ }
405
510
  function onDemandRecordParameters(trigger) {
406
511
  if (trigger.type !== "elementum_on_demand_trigger" || !Array.isArray(trigger.attrs.parameters))
407
512
  return [];
@@ -448,7 +553,7 @@ const RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS = {
448
553
  * write side). Only the names that differ from their authoring path are
449
554
  * listed; the rest already read back correctly.
450
555
  */
451
- const RECORD_SEARCH_CALCULATION_REF_NAME_TO_TS = {
556
+ export const RECORD_SEARCH_CALCULATION_REF_NAME_TO_TS = {
452
557
  count: ["totalCount"],
453
558
  recordId: ["record", "recordId"],
454
559
  };
@@ -456,15 +561,30 @@ const RECORD_SEARCH_CALCULATION_REF_NAME_TO_TS = {
456
561
  // RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS: "All Records" is a platform-fixed
457
562
  // wire key on elementum_ai_search_table_task only. A trigger field could
458
563
  // coincidentally share that display name and must not be rewritten here.
459
- 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",
460
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",
461
578
  };
462
579
  // tableRecordsSearch collection output — platform wire key
463
580
  // "All matching table rows" (not recordSearch's "All found records" or
464
581
  // aiSearchTable's "All Records"). Leaving it unmapped prints
465
582
  // `(ctx.actions.x as any)["All matching table rows"]`, which drops the Ref
466
583
  // proxy at build time and omits the script/filter input entirely.
467
- 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",
468
588
  "All matching table rows": "records",
469
589
  };
470
590
  // Platform-fixed output labels → authoring path, inverse of
@@ -476,6 +596,7 @@ const TASK_OUTPUT_LABEL_TO_TS = {
476
596
  elementum_update_field_task: { "Updated record": ["record"] },
477
597
  elementum_execute_script_task: { "Text Result": ["textResult"] },
478
598
  elementum_user_search_task: {
599
+ "Users Size": ["count"],
479
600
  "User's Id": ["user", "id"],
480
601
  "User's Name": ["user", "name"],
481
602
  "User's Email": ["user", "email"],
@@ -833,6 +954,11 @@ function triggerRefPath(path, ctx) {
833
954
  const recordPath = prefixedOnDemandRecordRefPath(wireName, ctx);
834
955
  if (recordPath !== undefined)
835
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];
836
962
  }
837
963
  // An on-demand parameter is an explicitly declared top-level ctx.trigger
838
964
  // property. Check this before record-field inference: a perfectly ordinary
@@ -946,8 +1072,12 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
946
1072
  }
947
1073
  if (block?.type === "elementum_record_search_task" && pathSegments.length >= 1) {
948
1074
  const [head, ...tail] = pathSegments;
949
- if (head === "count") {
950
- 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] };
951
1081
  }
952
1082
  const recordSearchName = RECORD_SEARCH_TASK_REF_SEGMENT_TO_TS[head];
953
1083
  if (recordSearchName !== undefined) {
@@ -996,6 +1126,11 @@ function decodeTaskReferenceFromString(taskIdOrKey, pathSegments, ctx) {
996
1126
  if (groupPath !== undefined)
997
1127
  return { kind: "taskRef", task: refKey, path: [...groupPath] };
998
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
+ }
999
1134
  // createRecord/findRelatedRecords record-id + field outputs (same as the
1000
1135
  // refs["Title"] / refs["Record"] resource-attr path in decodeValue).
1001
1136
  if ((block?.type === "elementum_create_record_task" || block?.type === "elementum_find_related_records_task") &&
@@ -1047,6 +1182,9 @@ function decodeReferenceString(value, ctx) {
1047
1182
  const pieces = value.split(".");
1048
1183
  if (pieces[0] === "trigger" && pieces.length > 1) {
1049
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] };
1050
1188
  if (path[0] === "record" && path.length >= 2 && /^[a-f0-9-]{36}$/.test(path[1])) {
1051
1189
  const sourceFieldId = path[1];
1052
1190
  const field = ctx.fieldById.get(sourceFieldId);
@@ -1109,18 +1247,35 @@ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
1109
1247
  if (!isTfExpr(value) || value.$expr !== "template")
1110
1248
  return undefined;
1111
1249
  const [prefix, fieldPart, suffixPart] = value.parts;
1112
- 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)
1113
1258
  return undefined;
1114
1259
  if (suffixPart !== undefined && typeof suffixPart !== "string")
1115
1260
  return undefined;
1116
- 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
+ }
1117
1272
  if (fieldKey === undefined)
1118
1273
  return undefined;
1119
1274
  const suffix = suffixPart === undefined ? [] : suffixPart.replace(/^\./, "").split(".").filter((s) => s.length > 0);
1120
1275
  if (suffix.length === 1 && suffix[0] === "10000001-2000-4000-a000-800000000000") {
1121
- return { kind: "triggerRef", path: ["record", fieldKey, "recordId"] };
1276
+ return { kind: "triggerRef", path: [root, fieldKey, "recordId"] };
1122
1277
  }
1123
- return { kind: "triggerRef", path: ["record", fieldKey, ...suffix] };
1278
+ return { kind: "triggerRef", path: [root, fieldKey, ...suffix] };
1124
1279
  }
1125
1280
  /**
1126
1281
  * Inverse of filterReferenceToTf's TASK case: filters render
@@ -1213,6 +1368,35 @@ function decodeTemplateForEachRef(value, ctx) {
1213
1368
  * decodeValue's generic local handling, but resolves to a triggerRef bag key
1214
1369
  * instead of a "field" RefExpr so it stays a valid filter LHS.
1215
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
+ }
1216
1400
  function fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx) {
1217
1401
  if (fieldPart.$expr === "resource-attr" && fieldPart.type.endsWith("_field") && fieldPart.path[0] === "id") {
1218
1402
  return scopedLabelToBagKey(ctx.appTfLabel, fieldPart.label);
@@ -1313,6 +1497,22 @@ function decodeSearchTableReference(value, ctx) {
1313
1497
  if (isTfExpr(value) && value.$expr === "data-attr" && value.type === "elementum_search_table") {
1314
1498
  const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
1315
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
+ }
1316
1516
  const objectId = lookup?.attrs.object_id ?? lookup?.attrs.aspect_id;
1317
1517
  const elementHandle = objectId !== undefined
1318
1518
  ? aspectOwnerRefNameFromObjectId(objectId, ctx.appRefName, ctx.appTfLabel, ctx.dataBlocks, ctx.foreignAppRefNames, ctx.foreignElementRefNames)
@@ -1357,6 +1557,11 @@ function decodeSearchTableReference(value, ctx) {
1357
1557
  }
1358
1558
  return { kind: "unresolved", uuid: typeof value === "string" ? value : JSON.stringify(value), hint: "search table" };
1359
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
+ }
1360
1565
  function decodeValue(value, ctx) {
1361
1566
  if (isTfExpr(value)) {
1362
1567
  if (value.$expr === "template") {
@@ -1746,6 +1951,12 @@ function decodeValue(value, ctx) {
1746
1951
  }
1747
1952
  return { kind: "user", email };
1748
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
+ }
1749
1960
  if (value.$expr === "local") {
1750
1961
  const stageName = stageFilterName(value, ctx);
1751
1962
  if (stageName !== undefined)
@@ -2311,8 +2522,31 @@ function filterReferenceType(value, fallback, ctx) {
2311
2522
  }
2312
2523
  return typeof raw.fieldType === "string" ? fieldTypeToValueType(raw.fieldType) : fallback;
2313
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
+ }
2314
2545
  export function inferredPublishOutputType(value, ctx) {
2315
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
+ }
2316
2550
  if (!isObject(raw) || !isObject(raw.taskReference) || typeof raw.taskReference.name !== "string") {
2317
2551
  return { fieldType: "TEXT", multiple: false };
2318
2552
  }
@@ -2337,6 +2571,16 @@ export function inferredPublishOutputType(value, ctx) {
2337
2571
  return { fieldType: field.type.toUpperCase(), multiple: false };
2338
2572
  }
2339
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
+ }
2340
2584
  if ((task?.type === "elementum_create_record_task" || task?.type === "elementum_find_related_records_task") &&
2341
2585
  (raw.taskReference.name === "Record" || raw.taskReference.name === "Record ID")) {
2342
2586
  return { fieldType: "ASPECT_RECORD_ID", multiple: false };
@@ -2384,8 +2628,11 @@ function triggerFromBlock(block, ctx) {
2384
2628
  // no "attachmentId" spelling at all, but the authoring alias
2385
2629
  // (onDemand's TriggerFieldTypeAlias) does. Map back so printed
2386
2630
  // source uses a type-checkable alias instead of a raw wire string
2387
- // "attachment" that TriggerFieldTypeAlias doesn't accept.
2388
- 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;
2389
2636
  const record = type === "record";
2390
2637
  const recordApp = record
2391
2638
  ? aspectRefFromObjectId(parameter.default_value, ctx)
@@ -2399,7 +2646,9 @@ function triggerFromBlock(block, ctx) {
2399
2646
  ...(recordApp !== undefined ? { app: recordApp } : {}),
2400
2647
  ...(parameter.required === true ? { required: true } : {}),
2401
2648
  ...(parameter.multiple === true ? { multiple: true } : {}),
2402
- ...(!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
+ : {}),
2403
2652
  ...(typeof parameter.description === "string" ? { description: parameter.description } : {}),
2404
2653
  };
2405
2654
  })
@@ -2500,7 +2749,7 @@ function triggerFromBlock(block, ctx) {
2500
2749
  default: throw new EntityTfError(`trigger "${kind}" is outside the Terraform contract`);
2501
2750
  }
2502
2751
  }
2503
- function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2752
+ function taskArgs(block, factory, ctx, taskDiagnostics) {
2504
2753
  const args = {};
2505
2754
  for (const [attr, value] of Object.entries(block.attrs)) {
2506
2755
  if (attr === "parent" || attr === "name" || attr === "depends_on")
@@ -2573,7 +2822,7 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2573
2822
  // throwing out of taskArgs, which would drop the WHOLE automation
2574
2823
  // (a live-caught regression in an earlier attempt at this fix).
2575
2824
  if (mapping.field_id === undefined) {
2576
- 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`);
2577
2826
  continue;
2578
2827
  }
2579
2828
  // A PRESENT but unreconstructable field_id (fieldRef throws) is
@@ -2595,7 +2844,54 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2595
2844
  const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
2596
2845
  const root = isObject(raw) && isObject(raw.object) ? raw.object : undefined;
2597
2846
  const props = Array.isArray(root?.properties) ? root.properties : [];
2598
- 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) => {
2599
2895
  if (!isObject(node))
2600
2896
  throw new EntityTfError("invalid script output schema node");
2601
2897
  const [type, definition] = Object.entries(node)[0] ?? [];
@@ -2608,34 +2904,18 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2608
2904
  : undefined;
2609
2905
  return {
2610
2906
  type: "array",
2611
- items: decodeNode(definition.item),
2907
+ items: decodeNode(definition.item, `${path}[]`),
2612
2908
  ...(itemName !== undefined ? { itemName } : {}),
2613
2909
  };
2614
2910
  }
2615
2911
  if (type === "object" && Array.isArray(definition.properties)) {
2616
- const properties = Object.fromEntries(definition.properties.map((child) => {
2617
- if (!isObject(child))
2618
- throw new EntityTfError("invalid nested script output property");
2619
- const childDefinition = Object.values(child)[0];
2620
- if (!isObject(childDefinition) || typeof childDefinition.name !== "string") {
2621
- throw new EntityTfError("nested script output property requires a name");
2622
- }
2623
- return [childDefinition.name, decodeNode(child)];
2624
- }));
2625
- return { type: "object", properties };
2912
+ return { type: "object", properties: decodeProperties(definition.properties, path) };
2626
2913
  }
2627
2914
  if (type === "string")
2628
2915
  return scriptOutputScalarFromStringNode(definition);
2629
2916
  return type === "bool" ? "boolean" : type;
2630
2917
  };
2631
- const properties = Object.fromEntries(props.map((property) => {
2632
- if (!isObject(property))
2633
- throw new EntityTfError("invalid script output schema");
2634
- const definition = Object.values(property)[0];
2635
- if (!isObject(definition) || typeof definition.name !== "string")
2636
- throw new EntityTfError("invalid script output property");
2637
- return [definition.name, decodeNode(property)];
2638
- }));
2918
+ const properties = decodeProperties(props, "root");
2639
2919
  // The root object's own name is inert to the platform but real stored
2640
2920
  // data, so carry it through rather than rebuilding a schema that
2641
2921
  // differs from the one just read.
@@ -2662,7 +2942,14 @@ function taskArgs(block, factory, ctx, fieldMappingDiagnostics) {
2662
2942
  parameter.path[1] !== null &&
2663
2943
  "index" in parameter.path[1] &&
2664
2944
  typeof parameter.path[1].index === "string") {
2665
- 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) };
2666
2953
  }
2667
2954
  // ei emits bare platform parameter UUIDs when the target automation's
2668
2955
  // onDemand trigger is not in this export (foreign / undiscovered).
@@ -3144,8 +3431,10 @@ function taskRefKey(block, automationLabel, appTfLabel) {
3144
3431
  * driving spurious destroys). Deliberately lenient - tolerant of the exact
3145
3432
  * conditions that make real extraction fail (zero triggers, an
3146
3433
  * unrecognized task kind) so it over-collects rather than under-collects.
3147
- * More than one trigger is not one of those cases: it throws
3148
- * {@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
3149
3438
  * here just leaves one more resource unmanaged; a false negative would
3150
3439
  * silently destroy a live automation on apply.
3151
3440
  */
@@ -3200,6 +3489,73 @@ function withExportedVariableId(block, ids) {
3200
3489
  return block;
3201
3490
  return { ...block, attrs: { ...block.attrs, variable_id: exported } };
3202
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
+ }
3203
3559
  /** Bridge metadata for required values that GraphQL could not reconstruct. */
3204
3560
  function unresolvedAuthoringValues(doc) {
3205
3561
  const values = [];
@@ -3224,10 +3580,11 @@ function unresolvedAuthoringValues(doc) {
3224
3580
  return values;
3225
3581
  }
3226
3582
  /**
3227
- * Pull stops on this. EDK does not author multi-trigger automations; apps
3228
- * should keep one trigger and call the shared logic with a run-automation
3229
- * action. Callers that otherwise turn extract failures into skips must
3230
- * 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.
3231
3588
  */
3232
3589
  export class UnsupportedMultiTriggerError extends EntityTfError {
3233
3590
  automationName;
@@ -3240,6 +3597,20 @@ export class UnsupportedMultiTriggerError extends EntityTfError {
3240
3597
  this.triggerCount = triggerCount;
3241
3598
  }
3242
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
+ }
3243
3614
  /** Extract one app-owned automation graph from an ei app export. */
3244
3615
  function automationFromTfDocument(doc, automationLabel, appRefName, foreignFieldRefsById, foreignFieldRefsByDataAddress, foreignTableRefsById, picklistOptionLabelById, fieldNamesByOwnerRefName, foreignAppRefNames, foreignElementRefNames, procedureKeysByDiscriminator, foreignTaskRefNames) {
3245
3616
  const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
@@ -3324,7 +3695,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3324
3695
  throw new EntityTfError(`${unresolved.resource}.${unresolved.field}: ${unresolved.reason}; ` +
3325
3696
  "the automation is excluded because no safe authored value or UUID fallback is available");
3326
3697
  }
3327
- tasks.forEach((block) => assertAllowed(block, TASK_ATTRIBUTES));
3698
+ tasks.forEach((block) => assertAllowed(block, block.type === "elementum_notification_task" ? NOTIFICATION_TASK_ATTRIBUTES : TASK_ATTRIBUTES));
3328
3699
  ownedBranches.forEach((block) => assertAllowed(block, BRANCH_ATTRIBUTES));
3329
3700
  const publishDependencies = Array.isArray(publish?.attrs.depends_on)
3330
3701
  ? publish.attrs.depends_on.map((value) => resourceRef(value)).filter((value) => value !== undefined)
@@ -3467,7 +3838,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3467
3838
  dependencyOrder.set(`${ref.type}.${ref.label}`, index); });
3468
3839
  const triggerAddress = `${trigger.type}.${trigger.label}`;
3469
3840
  const unrebuildableTasks = [];
3470
- const fieldMappingDiagnostics = [];
3841
+ const taskDiagnostics = [];
3471
3842
  // edk#821: resolve each elementum_unmanaged_task_reference this automation's
3472
3843
  // OWN tasks actually parent onto (never the whole doc's data blocks - a
3473
3844
  // sibling automation sharing this export can have its own, edk#785) to its
@@ -3571,7 +3942,7 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3571
3942
  id: typeof block.attrs.id === "string" ? block.attrs.id : "",
3572
3943
  taskType: typeof block.attrs.task_type === "string" ? block.attrs.task_type : "",
3573
3944
  }
3574
- : taskArgs(block, factory, ctx, fieldMappingDiagnostics);
3945
+ : taskArgs(block, factory, ctx, taskDiagnostics);
3575
3946
  const call = { factory, refKey, args, ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
3576
3947
  visiting.delete(address);
3577
3948
  return [call, ...buildTasks(address)];
@@ -3599,6 +3970,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3599
3970
  if (inferred.fieldType === fieldType && inferred.multiple === multiple) {
3600
3971
  return { name: output.name, value };
3601
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
+ }
3602
3979
  const explicitType = workflowOutputTypeFromFieldType(fieldType);
3603
3980
  if (explicitType === undefined) {
3604
3981
  outputDiagnostics.push(`automation "${automationLabel}" workflow output "${output.name}" has explicit field type ` +
@@ -3615,6 +3992,9 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3615
3992
  }
3616
3993
  return { name: output.name, value, explicitType, explicitMultiple: multiple };
3617
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);
3618
3998
  const exportedRevision = publish?.attrs.workflow_revision;
3619
3999
  if (exportedRevision !== undefined && typeof exportedRevision !== "string") {
3620
4000
  throw new EntityTfError(`${WORKFLOW_PUBLISH_RESOURCE_TYPE}.${automationLabel}: workflow_revision must be a string`);
@@ -3637,12 +4017,12 @@ function automationFromTfDocument(doc, automationLabel, appRefName, foreignField
3637
4017
  ast,
3638
4018
  blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])],
3639
4019
  adoptionAddressAliases,
3640
- ...((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) && {
3641
4021
  diagnostics: [
3642
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`),
3643
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`),
3644
4024
  ...outputDiagnostics,
3645
- ...fieldMappingDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
4025
+ ...taskDiagnostics.map((message) => `automation "${automationLabel}": ${message}`),
3646
4026
  ],
3647
4027
  }),
3648
4028
  };