@elementumai/edk 0.9.19 → 0.10.1

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 (240) hide show
  1. package/README.md +159 -7
  2. package/dist-sdk/src/catalog/factories.d.ts +33 -2
  3. package/dist-sdk/src/catalog/factories.js +40 -1
  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 +11 -0
  10. package/dist-sdk/src/catalog/types.d.ts +40 -1
  11. package/dist-sdk/src/catalog/types.js +12 -0
  12. package/dist-sdk/src/core/triggers/on-demand.d.ts +40 -4
  13. package/dist-sdk/src/core/triggers/on-demand.js +17 -2
  14. package/dist-sdk/src/core/types/app.d.ts +2 -2
  15. package/dist-sdk/src/engine/build/context.d.ts +1 -1
  16. package/dist-sdk/src/engine/coverage-gaps.d.ts +86 -0
  17. package/dist-sdk/src/engine/coverage-gaps.js +156 -0
  18. package/dist-sdk/src/engine/ei/run.d.ts +169 -0
  19. package/dist-sdk/src/engine/ei/run.js +1219 -0
  20. package/dist-sdk/src/engine/logging.d.ts +17 -0
  21. package/dist-sdk/src/engine/logging.js +18 -0
  22. package/dist-sdk/src/engine/pull/catalog-ref.d.ts +16 -0
  23. package/dist-sdk/src/engine/pull/catalog-ref.js +24 -0
  24. package/dist-sdk/src/engine/pull/context.d.ts +68 -6
  25. package/dist-sdk/src/engine/pull/context.js +40 -1
  26. package/dist-sdk/src/engine/pull/procedure-refs.d.ts +8 -0
  27. package/dist-sdk/src/engine/pull/procedure-refs.js +28 -0
  28. package/dist-sdk/src/engine/pull/ref-only.d.ts +5 -0
  29. package/dist-sdk/src/engine/pull/ref-only.js +10 -7
  30. package/dist-sdk/src/engine/pull/result-output.d.ts +6 -0
  31. package/dist-sdk/src/engine/pull/result-output.js +113 -3
  32. package/dist-sdk/src/engine/tf/expr.js +1 -1
  33. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  34. package/dist-sdk/src/engine/tf/index.js +1 -1
  35. package/dist-sdk/src/engine/tf/labels.d.ts +28 -5
  36. package/dist-sdk/src/engine/tf/labels.js +54 -3
  37. package/dist-sdk/src/engine/tf/model.d.ts +22 -1
  38. package/dist-sdk/src/engine/tf/parse.js +93 -4
  39. package/dist-sdk/src/engine/tf/render.d.ts +4 -2
  40. package/dist-sdk/src/engine/tf/render.js +41 -7
  41. package/dist-sdk/src/engine/validation.d.ts +44 -0
  42. package/dist-sdk/src/engine/validation.js +95 -0
  43. package/dist-sdk/src/entities/access-policy/from-tf.js +38 -1
  44. package/dist-sdk/src/entities/access-policy/principal.d.ts +2 -0
  45. package/dist-sdk/src/entities/access-policy/to-tf.js +5 -2
  46. package/dist-sdk/src/entities/agent/build.d.ts +4 -16
  47. package/dist-sdk/src/entities/agent/build.js +40 -5
  48. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +3 -0
  49. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +46 -21
  50. package/dist-sdk/src/entities/agent/from-tf.js +11 -3
  51. package/dist-sdk/src/entities/agent/module.js +2 -0
  52. package/dist-sdk/src/entities/agent/to-tf.js +20 -6
  53. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +10 -1
  54. package/dist-sdk/src/entities/agent-tool/from-tf.js +18 -6
  55. package/dist-sdk/src/entities/agent-tool/module.js +3 -0
  56. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  57. package/dist-sdk/src/entities/agent-tool/to-tf.js +27 -5
  58. package/dist-sdk/src/entities/app/auto-share.d.ts +38 -0
  59. package/dist-sdk/src/entities/app/auto-share.js +49 -0
  60. package/dist-sdk/src/entities/app/build.d.ts +105 -22
  61. package/dist-sdk/src/entities/app/build.js +107 -10
  62. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +22 -1
  63. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -0
  64. package/dist-sdk/src/entities/app/from-tf.js +11 -2
  65. package/dist-sdk/src/entities/app/index.d.ts +7 -6
  66. package/dist-sdk/src/entities/app/index.js +2 -8
  67. package/dist-sdk/src/entities/app/module.js +5 -2
  68. package/dist-sdk/src/entities/app/to-tf.d.ts +6 -0
  69. package/dist-sdk/src/entities/app/to-tf.js +40 -13
  70. package/dist-sdk/src/entities/automation/build.d.ts +56 -6
  71. package/dist-sdk/src/entities/automation/build.js +230 -26
  72. package/dist-sdk/src/entities/automation/calculation-expression.d.ts +7 -7
  73. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +41 -5
  74. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +470 -58
  75. package/dist-sdk/src/entities/automation/from-tf.d.ts +37 -8
  76. package/dist-sdk/src/entities/automation/from-tf.js +791 -131
  77. package/dist-sdk/src/entities/automation/generated/task-output-contracts.d.ts +33 -0
  78. package/dist-sdk/src/entities/automation/generated/task-output-contracts.js +183 -0
  79. package/dist-sdk/src/entities/automation/index.d.ts +2 -2
  80. package/dist-sdk/src/entities/automation/index.js +1 -1
  81. package/dist-sdk/src/entities/automation/module.d.ts +3 -0
  82. package/dist-sdk/src/entities/automation/module.js +107 -15
  83. package/dist-sdk/src/entities/automation/output-field-types.d.ts +7 -0
  84. package/dist-sdk/src/entities/automation/output-field-types.js +36 -0
  85. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +9 -0
  86. package/dist-sdk/src/entities/automation/output-key-wire-name.js +13 -0
  87. package/dist-sdk/src/entities/automation/script-code.d.ts +20 -0
  88. package/dist-sdk/src/entities/automation/script-code.js +109 -5
  89. package/dist-sdk/src/entities/automation/system-ref-name.js +4 -0
  90. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +39 -0
  91. package/dist-sdk/src/entities/automation/task-output-labels.js +85 -0
  92. package/dist-sdk/src/entities/automation/tasks.d.ts +116 -22
  93. package/dist-sdk/src/entities/automation/tasks.js +86 -24
  94. package/dist-sdk/src/entities/automation/to-tf.d.ts +24 -3
  95. package/dist-sdk/src/entities/automation/to-tf.js +1082 -132
  96. package/dist-sdk/src/entities/automation/triggers.d.ts +12 -6
  97. package/dist-sdk/src/entities/automation/triggers.js +4 -0
  98. package/dist-sdk/src/entities/automation/types.d.ts +9 -0
  99. package/dist-sdk/src/entities/automation/types.js +19 -0
  100. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +1 -1
  101. package/dist-sdk/src/entities/automation/value-ref-tf.js +1 -1
  102. package/dist-sdk/src/entities/chart/from-tf.js +9 -1
  103. package/dist-sdk/src/entities/chart/to-tf.js +10 -3
  104. package/dist-sdk/src/entities/data-lookup/module.js +2 -0
  105. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +24 -31
  106. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +1 -0
  107. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +7 -5
  108. package/dist-sdk/src/entities/element/build.d.ts +28 -13
  109. package/dist-sdk/src/entities/element/build.js +5 -1
  110. package/dist-sdk/src/entities/element/from-tf.d.ts +11 -0
  111. package/dist-sdk/src/entities/element/from-tf.js +62 -1
  112. package/dist-sdk/src/entities/element/index.d.ts +5 -3
  113. package/dist-sdk/src/entities/element/index.js +1 -0
  114. package/dist-sdk/src/entities/element/module.js +9 -3
  115. package/dist-sdk/src/entities/element/to-tf.d.ts +1 -1
  116. package/dist-sdk/src/entities/element/to-tf.js +16 -16
  117. package/dist-sdk/src/entities/field/build.d.ts +17 -3
  118. package/dist-sdk/src/entities/field/build.js +3 -0
  119. package/dist-sdk/src/entities/field/calc.d.ts +7 -7
  120. package/dist-sdk/src/entities/field/from-tf.d.ts +5 -4
  121. package/dist-sdk/src/entities/field/from-tf.js +244 -49
  122. package/dist-sdk/src/entities/field/media-types.d.ts +6 -0
  123. package/dist-sdk/src/entities/field/media-types.js +30 -0
  124. package/dist-sdk/src/entities/field/module.js +2 -0
  125. package/dist-sdk/src/entities/field/options.js +6 -1
  126. package/dist-sdk/src/entities/field/to-tf.d.ts +26 -5
  127. package/dist-sdk/src/entities/field/to-tf.js +137 -15
  128. package/dist-sdk/src/entities/field/types.d.ts +2 -0
  129. package/dist-sdk/src/entities/field/types.js +27 -0
  130. package/dist-sdk/src/entities/file-reader/from-tf.js +14 -5
  131. package/dist-sdk/src/entities/file-reader/module.js +1 -0
  132. package/dist-sdk/src/entities/file-reader/types.d.ts +2 -0
  133. package/dist-sdk/src/entities/file-reader/types.js +1 -1
  134. package/dist-sdk/src/entities/portal/build.d.ts +26 -0
  135. package/dist-sdk/src/entities/portal/build.js +37 -0
  136. package/dist-sdk/src/entities/portal/from-tf.d.ts +27 -0
  137. package/dist-sdk/src/entities/portal/from-tf.js +75 -0
  138. package/dist-sdk/src/entities/portal/index.d.ts +1 -0
  139. package/dist-sdk/src/entities/portal/index.js +1 -0
  140. package/dist-sdk/src/entities/portal/module.d.ts +3 -0
  141. package/dist-sdk/src/entities/portal/module.js +28 -0
  142. package/dist-sdk/src/entities/portal/to-tf.d.ts +12 -0
  143. package/dist-sdk/src/entities/portal/to-tf.js +73 -0
  144. package/dist-sdk/src/entities/portal/types.d.ts +1 -0
  145. package/dist-sdk/src/entities/portal/types.js +1 -0
  146. package/dist-sdk/src/entities/relationship/module.js +2 -0
  147. package/dist-sdk/src/entities/relationship/pair-check.d.ts +7 -0
  148. package/dist-sdk/src/entities/relationship/pair-check.js +68 -0
  149. package/dist-sdk/src/entities/relationship/to-tf.d.ts +2 -0
  150. package/dist-sdk/src/entities/relationship/to-tf.js +12 -3
  151. package/dist-sdk/src/entities/role/from-tf.js +3 -3
  152. package/dist-sdk/src/entities/role/to-tf.d.ts +2 -0
  153. package/dist-sdk/src/entities/role/to-tf.js +12 -4
  154. package/dist-sdk/src/entities/search-table/module.js +1 -0
  155. package/dist-sdk/src/entities/search-table/to-tf.d.ts +1 -0
  156. package/dist-sdk/src/entities/search-table/to-tf.js +1 -1
  157. package/dist-sdk/src/entities/service-account/build.d.ts +15 -2
  158. package/dist-sdk/src/entities/service-account/from-tf.d.ts +2 -4
  159. package/dist-sdk/src/entities/service-account/from-tf.js +20 -8
  160. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +56 -0
  161. package/dist-sdk/src/entities/service-account/role-fidelity.js +243 -0
  162. package/dist-sdk/src/entities/service-account/to-tf.d.ts +14 -0
  163. package/dist-sdk/src/entities/service-account/to-tf.js +17 -0
  164. package/dist-sdk/src/entities/service-account/workspace-owner.d.ts +16 -0
  165. package/dist-sdk/src/entities/service-account/workspace-owner.js +22 -0
  166. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +1 -1
  167. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +5 -2
  168. package/dist-sdk/src/entities/shared/filters/ast.d.ts +23 -1
  169. package/dist-sdk/src/entities/shared/filters/ast.js +2 -0
  170. package/dist-sdk/src/entities/shared/filters/index.d.ts +7 -0
  171. package/dist-sdk/src/entities/shared/filters/index.js +19 -4
  172. package/dist-sdk/src/entities/shared/filters/print.js +24 -3
  173. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +7 -0
  174. package/dist-sdk/src/entities/shared/filters/tf-codec.js +46 -7
  175. package/dist-sdk/src/entities/shared/filters/types.d.ts +15 -2
  176. package/dist-sdk/src/entities/shared/ref.d.ts +5 -7
  177. package/dist-sdk/src/entities/shared/ref.js +5 -7
  178. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +9 -0
  179. package/dist-sdk/src/entities/shared/tool-field-ref.js +35 -2
  180. package/dist-sdk/src/entities/shared/types/field-types.d.ts +20 -5
  181. package/dist-sdk/src/entities/shared/types/field-types.js +8 -0
  182. package/dist-sdk/src/entities/skill/access-policy.js +3 -3
  183. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +3 -0
  184. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +14 -6
  185. package/dist-sdk/src/entities/skill/from-tf.js +70 -15
  186. package/dist-sdk/src/entities/skill/input-coverage.d.ts +7 -0
  187. package/dist-sdk/src/entities/skill/input-coverage.js +11 -0
  188. package/dist-sdk/src/entities/skill/module.js +2 -0
  189. package/dist-sdk/src/entities/skill/to-tf.js +14 -4
  190. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  191. package/dist-sdk/src/entities/skill-tool/from-tf.js +49 -10
  192. package/dist-sdk/src/entities/skill-tool/module.js +3 -0
  193. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -8
  194. package/dist-sdk/src/entities/skill-tool/to-tf.js +49 -14
  195. package/dist-sdk/src/entities/table/catalog.d.ts +14 -0
  196. package/dist-sdk/src/entities/table/catalog.js +66 -0
  197. package/dist-sdk/src/entities/table/module.js +2 -1
  198. package/dist-sdk/src/entities/table/to-tf.js +2 -2
  199. package/dist-sdk/src/entities/task/build.d.ts +8 -0
  200. package/dist-sdk/src/entities/task/build.js +10 -1
  201. package/dist-sdk/src/entities/task/from-tf.d.ts +4 -2
  202. package/dist-sdk/src/entities/task/from-tf.js +7 -2
  203. package/dist-sdk/src/entities/task/module.js +2 -2
  204. package/dist-sdk/src/entities/task/to-tf.d.ts +8 -4
  205. package/dist-sdk/src/entities/task/to-tf.js +28 -1
  206. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +49 -9
  207. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +71 -18
  208. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +19 -4
  209. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +82 -10
  210. package/dist-sdk/src/entities/view/agent-view-layout.d.ts +53 -23
  211. package/dist-sdk/src/entities/view/agent-view-layout.js +1 -1
  212. package/dist-sdk/src/entities/view/from-tf.d.ts +3 -2
  213. package/dist-sdk/src/entities/view/from-tf.js +133 -13
  214. package/dist-sdk/src/entities/view/module.js +30 -3
  215. package/dist-sdk/src/entities/view/to-tf.d.ts +20 -8
  216. package/dist-sdk/src/entities/view/to-tf.js +86 -18
  217. package/dist-sdk/src/entities/view/types.d.ts +4 -15
  218. package/dist-sdk/src/entities/view/types.js +15 -15
  219. package/dist-sdk/src/entities/visual-flow/build.d.ts +16 -1
  220. package/dist-sdk/src/entities/visual-flow/build.js +9 -0
  221. package/dist-sdk/src/entities/visual-flow/from-tf.d.ts +14 -0
  222. package/dist-sdk/src/entities/visual-flow/from-tf.js +51 -3
  223. package/dist-sdk/src/entities/visual-flow/index.d.ts +1 -1
  224. package/dist-sdk/src/entities/visual-flow/index.js +1 -1
  225. package/dist-sdk/src/entities/visual-flow/printer.js +19 -0
  226. package/dist-sdk/src/entities/visual-flow/to-tf.js +87 -3
  227. package/dist-sdk/src/entities/widget/build.d.ts +16 -1
  228. package/dist-sdk/src/entities/widget/build.js +11 -1
  229. package/dist-sdk/src/entities/widget/from-tf.js +3 -3
  230. package/dist-sdk/src/entities/widget/to-tf.d.ts +2 -0
  231. package/dist-sdk/src/entities/widget/to-tf.js +41 -14
  232. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +148 -13
  233. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  234. package/dist-sdk/src/graph/index.d.ts +12 -0
  235. package/dist-sdk/src/graph/index.js +21 -0
  236. package/dist-sdk/src/graph/modules.js +2 -0
  237. package/dist-sdk/src/graph/types.d.ts +83 -4
  238. package/dist-sdk/src/internal/sdk-package.d.ts +1 -1
  239. package/dist-sdk/src/internal/sdk-package.js +1 -0
  240. package/package.json +16 -3
@@ -1,7 +1,9 @@
1
1
  import { EntityTfError, recordFieldContextOf } from "../../engine/entity.js";
2
+ import { currentValidationMode, recordValidations, ValidationFailureError } from "../../engine/validation.js";
2
3
  import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
4
+ import { ELEMENT_AUDIT_SYSTEM_FIELD_KEYS } from "../element/system-fields.js";
3
5
  import { isUnsafePlatformId } from "../../core/platform-id.js";
4
- import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, scopedResourceLabel, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
6
+ import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, stableIdSuffix, scopedResourceLabel, tfLabelToTsLabel, tsLabelToTfLabel, } from "../../engine/tf/index.js";
5
7
  import { workspaceAspectKey } from "../../engine/build/context.js";
6
8
  import { SEARCH_TABLE_RESOURCE_TYPES } from "../search-table/types.js";
7
9
  import { fieldRefToTfValue } from "../field/to-tf.js";
@@ -9,18 +11,46 @@ import { SERVICE_ACCOUNT_RESOURCE_TYPE } from "../service-account/module.js";
9
11
  import { foreignFieldDataLabel, resolveForeignRef } from "../shared/foreign-ref.js";
10
12
  import { filterToTf as serializeFilterToTf } from "../shared/filters/tf-codec.js";
11
13
  import { referenceValueTypeForField } from "../shared/filters/index.js";
12
- import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES } from "./output-key-wire-name.js";
14
+ import { API_TASK_REF_AUTHORING_NAMES, API_TASK_REF_WIRE_NAMES, OUTPUT_KEY_CANONICAL, OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
13
15
  import { outputFieldTypesFromScriptSchema, scriptOutputReferenceIsDeclared } from "./output-field-types.js";
16
+ import { RESOURCE_TYPE_TO_EXECUTOR, TASK_OUTPUT_CONTRACTS } from "./generated/task-output-contracts.js";
14
17
  import { CONNECTOR_ORG_BAG } from "../org/connector.js";
18
+ import { GROUP_ORG_BAG } from "../org/group.js";
15
19
  import { FILE_READER_SUB_TYPE_BY_RESOURCE, FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
16
20
  import { UNRESOLVED_FIELD_MARKER } from "../shared/ref.js";
21
+ import { ELEMENT_SYSTEM_FIELD_KEYS } from "../element/system-fields.js";
17
22
  import { TABLE_RESOURCE_TYPE } from "../table/module.js";
18
- import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE } from "./types.js";
19
- import { TASK_OUTPUT_REFERENCE_NAMES, USER_SEARCH_REF_WIRE_NAMES } from "./task-output-labels.js";
23
+ import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE, automationResourceLabel } from "./types.js";
24
+ import { AI_SEARCH_TABLE_OUTPUT_NAMES, TASK_OUTPUT_REFERENCE_NAMES, TRIGGER_WHOLE_RECORD_MARKER, USER_SEARCH_REF_WIRE_NAMES, triggerAttachmentPayloadRef, triggerWholeRecordRefJson, } from "./task-output-labels.js";
20
25
  import { onDemandTriggerRefKey } from "./value-ref-tf.js";
26
+ import { normalizeOnDemandParamKey } from "../../../pull/util.js";
21
27
  import { PROVIDER_FIXED_SYSTEM_FIELD_KEYS, recordFieldWireRefName } from "./system-ref-name.js";
22
28
  import { taskTfLabel } from "./task-label.js";
23
29
  import { isOnDemandRecordType } from "../shared/types/field-types.js";
30
+ /** The context for reading records of `appRefName` (a `kind`), retargeted from the owner. */
31
+ /**
32
+ * Wire WorkflowFieldType -> elementum_on_demand_trigger `parameters[].type`.
33
+ * Keys are exactly the provider's OneOf enum; anything else (JSON, OBJECT)
34
+ * is refused at build rather than lowercased into an invalid value (#1415).
35
+ */
36
+ const ON_DEMAND_TF_PARAM_TYPES = new Map([
37
+ ["TEXT", "text"], ["NUMBER", "number"], ["DECIMAL", "decimal"], ["BOOLEAN", "boolean"],
38
+ ["DATE", "date"], ["DATETIME", "datetime"], ["USER", "user"], ["USER_ID", "user"],
39
+ ["GROUP_ID", "group"], ["ATTACHMENT_ID", "attachment"], ["ASPECT_RECORD", "record"],
40
+ // Already-provider spellings pass through unchanged.
41
+ ...["text", "number", "decimal", "boolean", "date", "datetime", "user", "group", "attachment", "record"]
42
+ .map((t) => [t, t]),
43
+ ]);
44
+ function recordOwnerContext(owner, appRefName, kind, fieldNames) {
45
+ if (appRefName === owner.appRefName && (kind === undefined || kind === owner.parentScope))
46
+ return owner;
47
+ return {
48
+ ...owner,
49
+ appRefName,
50
+ fieldNames: fieldNames ?? new Map(),
51
+ recordLacksAuditFields: kind === "element" && owner.elementsWithoutAuditFields?.has(appRefName) === true,
52
+ };
53
+ }
24
54
  function scopedLabel(appTfLabel, label) {
25
55
  return appScopedResourceLabel(appTfLabel, label);
26
56
  }
@@ -33,6 +63,41 @@ function labelHash(value) {
33
63
  }
34
64
  return (hash >>> 0).toString(36);
35
65
  }
66
+ /**
67
+ * Terraform data label for a vault key. Keep this in lockstep with the
68
+ * exporter's VaultEntryLabel: readable for conventional uppercase keys and
69
+ * hash-suffixed whenever normalization could collide.
70
+ */
71
+ export function vaultEntryLabel(key) {
72
+ let label = key.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
73
+ if (label === "" || /^[0-9]/.test(label))
74
+ label = `vault_${label}`;
75
+ if (label.toUpperCase() === key)
76
+ return label;
77
+ let hash = 0x811c9dc5;
78
+ for (const byte of new TextEncoder().encode(key)) {
79
+ hash ^= byte;
80
+ hash = Math.imul(hash, 0x01000193);
81
+ }
82
+ return `${label}_${(hash >>> 0).toString(16).padStart(8, "0")}`;
83
+ }
84
+ function vaultEntryRefToTf(key, refs) {
85
+ if (key === "")
86
+ throw new EntityTfError("secret() requires a vault entry key");
87
+ const label = vaultEntryLabel(key);
88
+ if (refs.owner.orgRefs !== undefined) {
89
+ refs.owner.orgRefs.rawLookup("elementum_vault_entry", label, key);
90
+ }
91
+ else {
92
+ refs.dataBlocks.set(`elementum_vault_entry.${label}`, {
93
+ kind: "data",
94
+ type: "elementum_vault_entry",
95
+ label,
96
+ attrs: { key },
97
+ });
98
+ }
99
+ return expr.dataAttr("elementum_vault_entry", label, ["value_reference"]);
100
+ }
36
101
  function scopedOptionLocalName(localName, owner) {
37
102
  for (const suffix of ["_options_by_label", "_option_ids_by_label"]) {
38
103
  if (!localName.endsWith(suffix))
@@ -63,9 +128,16 @@ const TRIGGER_RESOURCES = {
63
128
  survey: "elementum_survey_trigger",
64
129
  schedule: "elementum_schedule_trigger",
65
130
  };
131
+ /**
132
+ * The live platform id of a created variable: `variables[<index>].id` on its
133
+ * elementum_variable_task (edk#1456; was the single-variable `variable_id`).
134
+ */
135
+ function variableIdAttr(target) {
136
+ return expr.resourceAttr(target.type, target.label, ["variables", { index: String(target.index) }, "id"]);
137
+ }
66
138
  /**
67
139
  * setVariable tasks share one wire key ("variable") but two distinct
68
- * resource types depending on create vs. update — TASK_RESOURCES can't
140
+ * resource types depending on whether they create any variable — TASK_RESOURCES can't
69
141
  * carry both under one key. Shared by preRegister (so an explicit
70
142
  * hclParent onto an update-variant task resolves to the right type — see
71
143
  * edk#287) and emitTasks's own block emission, so the two can never
@@ -74,14 +146,18 @@ const TRIGGER_RESOURCES = {
74
146
  function variableTaskResourceType(taskBody, refKey) {
75
147
  const creates = Array.isArray(taskBody.create) ? taskBody.create : [];
76
148
  const updates = Array.isArray(taskBody.update) ? taskBody.update : [];
77
- if (creates.length + updates.length !== 1) {
78
- throw new EntityTfError(`setVariable task "${refKey}" must contain exactly one create or update for Terraform`);
149
+ if (creates.length + updates.length === 0) {
150
+ throw new EntityTfError(`setVariable task "${refKey}" must contain at least one create or update for Terraform`);
79
151
  }
80
- return creates.length === 1 ? "elementum_variable_task" : "elementum_update_variable_task";
152
+ // edk#1456: a task with any create entry is an elementum_variable_task
153
+ // (variables, plus updates when mixed); update-only is
154
+ // elementum_update_variable_task (updates).
155
+ return creates.length > 0 ? "elementum_variable_task" : "elementum_update_variable_task";
81
156
  }
82
157
  const TASK_RESOURCES = {
83
158
  message: "elementum_message_task",
84
159
  updateField: "elementum_update_field_task",
160
+ bulkUpdateFields: "elementum_bulk_update_fields_task",
85
161
  variable: "elementum_variable_task",
86
162
  createRecord: "elementum_create_record_task",
87
163
  recordSearch: "elementum_record_search_task",
@@ -104,6 +180,7 @@ const TASK_RESOURCES = {
104
180
  aiSearchTable: "elementum_ai_search_table_task",
105
181
  aiTransform: "elementum_ai_transform_task",
106
182
  saveAttachment: "elementum_save_attachment_task",
183
+ unzip: "elementum_unzip_file_task",
107
184
  userSearch: "elementum_user_search_task",
108
185
  userGroupSearch: "elementum_user_group_search_task",
109
186
  calculation: "elementum_calculation_task",
@@ -167,6 +244,7 @@ const CONFIG_ATTRS = {
167
244
  categorySource: "category_source",
168
245
  titleReference: "title",
169
246
  messageReference: "message",
247
+ descriptionReference: "description",
170
248
  notifyWatchers: "notify_watchers",
171
249
  fieldId: "field_id",
172
250
  userId: "user_id",
@@ -376,7 +454,7 @@ function crossAppFieldToTf(value, ctx, dataBlocks) {
376
454
  // table-owned search table has to be distinguishable from an element-owned
377
455
  // one.
378
456
  if (sibling !== undefined && sibling.kind !== "table" && sibling.kind !== "task") {
379
- const fieldValue = fieldRefToTfValue(value.fieldType ?? "", value.refName, sibling.tfLabel, sibling.kind);
457
+ const fieldValue = fieldRefToTfValue(value.fieldType ?? "", value.refName, sibling.tfLabel, sibling.kind, sibling.kind === "element" ? fieldNamesForAppRefName(ctx.fieldAddressesByAppRefName, value.parent) : undefined);
380
458
  if (fieldValue === undefined) {
381
459
  throw new EntityTfError(`field ref "${value.refName}" on sibling ${sibling.kind} "${value.parent}" has no terraform field resource mapping (fieldType ${JSON.stringify(value.fieldType ?? "")})`);
382
460
  }
@@ -443,8 +521,11 @@ function automationTargetToTf(value, ctx, dataBlocks) {
443
521
  ? sibling.tfLabel
444
522
  : undefined;
445
523
  if (managedOwnerLabel !== undefined) {
446
- const managedLabel = scopedLabel(managedOwnerLabel, tsLabelToTfLabel(value.refName));
447
524
  const targetOwner = ctx.workspaceAspects?.get(workspaceAspectKey(ownerKind, isOwn ? ctx.appRefName : value.parent ?? ""));
525
+ const managedHandle = ownerKind === "element"
526
+ ? elementHandleOf(isOwn ? ctx.ownerHandle : undefined, targetOwner?.streamRootEntity?.payload)
527
+ : undefined;
528
+ const managedLabel = automationResourceLabel(managedOwnerLabel, value.refName, ownerKind === "element" ? "element" : "app", managedHandle);
448
529
  const targetActiveRefs = targetOwner?.activeAutomationRefNames;
449
530
  const isActive = targetActiveRefs !== undefined
450
531
  ? targetActiveRefs.has(value.refName)
@@ -465,7 +546,11 @@ function automationTargetToTf(value, ctx, dataBlocks) {
465
546
  type: AUTOMATION_RESOURCE_TYPE,
466
547
  label: currentBindingLabel,
467
548
  attrs: {
468
- app_id: expr.resourceAttr(ownerKind === "element" ? "elementum_element" : "elementum_app", managedOwnerLabel, ["id"]),
549
+ // The owner id comes from the target automation itself. Referencing
550
+ // the app/element resource would defer this read whenever the app
551
+ // record has a pending change, making every parameter id unknown
552
+ // (edk#1514). `depends_on` still orders the read after publish.
553
+ app_id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, managedLabel, ["app_id"]),
469
554
  id: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, managedLabel, ["id"]),
470
555
  depends_on: [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, managedLabel)],
471
556
  },
@@ -759,14 +844,49 @@ function tokenToTf(value, ctx, dataBlocks) {
759
844
  const variant = value.__variant ?? "snowflake";
760
845
  const element = aspects.get(workspaceAspectKey("element", owner));
761
846
  const table = aspects.get(workspaceAspectKey("table", owner));
762
- if (variant === "table") {
763
- if (table === undefined) {
764
- throw new EntityTfError(`search table "${owner}.${value.refName}" is table-owned, but "${owner}" is not a table in this build` +
765
- `${element !== undefined ? ` (it is an element — use searchTable, not tableSearchTable)` : ""}`);
766
- }
847
+ const pinnedId = typeof value.id === "string" && value.id !== "" ? value.id : undefined;
848
+ if (variant === "table" && table !== undefined && pinnedId === undefined) {
767
849
  // Label shape mirrors search-table/to-tf.ts's own table branch.
768
850
  return expr.resourceAttr(SEARCH_TABLE_RESOURCE_TYPES.table, `tables_${table.tfLabel}_${tsLabelToTfLabel(value.refName)}`, ["id"]);
769
851
  }
852
+ // A table outside this build has no managed elementum_table_search_table.
853
+ // Pin by id when the name is ambiguous; otherwise keep the name lookup
854
+ // a unique name already used. An element that merely shares the refName
855
+ // is still the wrong owner.
856
+ if (variant === "table") {
857
+ if (pinnedId === undefined && element !== undefined) {
858
+ throw new EntityTfError(`search table "${owner}.${value.refName}" is table-owned, but "${owner}" is not a table in this build (it is an element — use searchTable, not tableSearchTable)`);
859
+ }
860
+ const tableName = typeof value.parentName === "string" && value.parentName !== "" ? value.parentName : owner;
861
+ const tableLabel = sanitizeName(tableName);
862
+ const searchName = value.name ?? value.refName;
863
+ const label = pinnedId === undefined
864
+ ? `${tableLabel}_${sanitizeName(searchName)}`
865
+ : `${tableLabel}_${sanitizeName(searchName)}_${stableIdSuffix(pinnedId)}`;
866
+ const tableId = expr.dataAttr(TABLE_RESOURCE_TYPE, tableLabel, ["id"]);
867
+ const searchAttrs = { table_id: tableId, name: searchName };
868
+ if (pinnedId !== undefined)
869
+ searchAttrs.id = pinnedId;
870
+ if (ctx.orgRefs !== undefined) {
871
+ ctx.orgRefs.rawLookup(TABLE_RESOURCE_TYPE, tableLabel, tableName);
872
+ ctx.orgRefs.rawLookup("elementum_search_table", label, searchName, searchAttrs);
873
+ }
874
+ else {
875
+ dataBlocks.set(`${TABLE_RESOURCE_TYPE}.${tableLabel}`, {
876
+ kind: "data",
877
+ type: TABLE_RESOURCE_TYPE,
878
+ label: tableLabel,
879
+ attrs: { name: tableName },
880
+ });
881
+ dataBlocks.set(`elementum_search_table.${label}`, {
882
+ kind: "data",
883
+ type: "elementum_search_table",
884
+ label,
885
+ attrs: searchAttrs,
886
+ });
887
+ }
888
+ return expr.dataAttr("elementum_search_table", label, ["id"]);
889
+ }
770
890
  if (element !== undefined) {
771
891
  return expr.resourceAttr(SEARCH_TABLE_RESOURCE_TYPES[variant], scopedResourceLabel(element.tfLabel, tsLabelToTfLabel(value.refName), "element"), ["id"]);
772
892
  }
@@ -787,7 +907,24 @@ function tokenToTf(value, ctx, dataBlocks) {
787
907
  // label (see ApprovalChainRef); preferring it rewrote live pulls to UUIDs.
788
908
  const refName = typeof value.refName === "string" ? value.refName.trim() : "";
789
909
  if (refName !== "") {
790
- return expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(refName)), ["id"]);
910
+ const address = `elementum_approval_process.${scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(refName))}`;
911
+ // Never emit a reference to an approval process this build doesn't
912
+ // declare (edk#1416). The build records the app's discovered
913
+ // approval-chain files; direct callers without that information keep
914
+ // the managed reference.
915
+ const declared = ctx.workspaceAspects
916
+ ?.get(workspaceAspectKey("app", ctx.appRefName))
917
+ ?.managedChildRefNames?.get("approval-chain");
918
+ if (declared === undefined || declared.has(refName)) {
919
+ return expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(refName)), ["id"]);
920
+ }
921
+ if (value.unresolvedId !== undefined) {
922
+ ctx.diagnostics.push(`automation ${ctx.automationTfLabel}: approval chain "${refName}" is not declared in this build (${address} would be undeclared); ` +
923
+ `using its pulled platform id ${value.unresolvedId} instead`);
924
+ return value.unresolvedId;
925
+ }
926
+ throw new EntityTfError(`automation ${ctx.automationTfLabel}: approval chain "${refName}" is not declared in this build (${address} is undeclared) ` +
927
+ `and the reference has no unresolvedId — add approval-chains/${refName}.ts to app "${ctx.appRefName}" or reference an existing approval process`);
791
928
  }
792
929
  if (value.unresolvedId !== undefined)
793
930
  return value.unresolvedId;
@@ -805,6 +942,33 @@ function tokenToTf(value, ctx, dataBlocks) {
805
942
  }
806
943
  return expr.resourceAttr(subType.resourceType, scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
807
944
  }
945
+ case "group": {
946
+ // Static notification/add-watcher recipients (edk#1389). An org.ts
947
+ // group resolves to its catalog lookup (or the managed resource), by
948
+ // key for an org.groups token or by name for a standalone
949
+ // groupRef({ name }) (whose refName is the display name). A group
950
+ // org.ts doesn't carry still builds as a name lookup, which is what
951
+ // the provider resolves anyway.
952
+ const refName = typeof value.refName === "string" ? value.refName : "";
953
+ const name = typeof value.name === "string" && value.name !== "" ? value.name : refName;
954
+ if (name === "")
955
+ throw new EntityTfError("group token has neither refName nor name");
956
+ const resolved = (refName !== "" ? ctx.orgRefs?.byTsLabel(GROUP_ORG_BAG, refName) : undefined)
957
+ ?? ctx.orgRefs?.byName(GROUP_ORG_BAG, name);
958
+ if (resolved !== undefined) {
959
+ return resolved.managed === true
960
+ ? expr.resourceAttr("elementum_group", resolved.tfLabel, ["id"])
961
+ : expr.dataAttr("elementum_group", resolved.tfLabel, ["id"]);
962
+ }
963
+ const label = sanitizeName(name);
964
+ if (ctx.orgRefs !== undefined) {
965
+ ctx.orgRefs.rawLookup("elementum_group", label, name);
966
+ }
967
+ else {
968
+ dataBlocks.set(`elementum_group.${label}`, { kind: "data", type: "elementum_group", label, attrs: { name } });
969
+ }
970
+ return expr.dataAttr("elementum_group", label, ["id"]);
971
+ }
808
972
  default:
809
973
  throw new EntityTfError(`catalog ref kind "${value.__kind}" has no automation HCL representation`);
810
974
  }
@@ -979,7 +1143,7 @@ function calculationFormulaRefToParts(value, refs) {
979
1143
  refs.owner.diagnostics.push(`automation unresolved variable ref ${JSON.stringify(value.variableReference.id)} preserved as a literal calculation reference`);
980
1144
  return [`variable.${value.variableReference.id}`];
981
1145
  }
982
- return ["variable.", expr.resourceAttr(target.type, target.label, ["variable_id"])];
1146
+ return ["variable.", variableIdAttr(target)];
983
1147
  }
984
1148
  if (isObject(value.templateReference))
985
1149
  return calculationTemplateToParts(value.templateReference, refs);
@@ -1068,8 +1232,9 @@ const FOUND_RECORD_TASK_TYPES = new Set([
1068
1232
  /**
1069
1233
  * A short-form `task.<id>.<name>` value reference addresses a found record's
1070
1234
  * field by its platform reference name `record.<fieldId>` (as ei exports it),
1071
- * not by the refs-map display label. Undefined when the field's id cannot be
1072
- * resolved in this build, which keeps the display-label form.
1235
+ * not by the refs-map display label. A record of an app/element outside this
1236
+ * build gets its field id from a `data.elementum_field` lookup. Undefined when
1237
+ * the field's id cannot be resolved, which keeps the display-label form.
1073
1238
  */
1074
1239
  function foundRecordFieldReferenceName(targetType, name, taskRefKey, refs) {
1075
1240
  const segments = name.split(".");
@@ -1083,11 +1248,41 @@ function foundRecordFieldReferenceName(targetType, name, taskRefKey, refs) {
1083
1248
  }
1084
1249
  catch (error) {
1085
1250
  if (error instanceof EntityTfError)
1086
- return undefined;
1251
+ return foreignFoundRecordFieldReferenceName(segments, taskRefKey, refs);
1087
1252
  throw error;
1088
1253
  }
1089
1254
  }
1255
+ function foreignFoundRecordFieldReferenceName(segments, taskRefKey, refs) {
1256
+ const target = refs.tasks.get(taskRefKey)?.recordTarget;
1257
+ if (target === undefined || (target.__kind !== "app" && target.__kind !== "element") || target.name === undefined) {
1258
+ return undefined;
1259
+ }
1260
+ if (refs.owner.workspaceAspects?.has(workspaceAspectKey(target.__kind, target.refName)))
1261
+ return undefined;
1262
+ const fieldKey = segments[1];
1263
+ const fieldName = refs.fieldNamesByAppRefName?.get(target.refName)?.get(fieldKey);
1264
+ if (fieldName === undefined)
1265
+ return undefined;
1266
+ const fieldToken = {
1267
+ __kind: "field",
1268
+ refName: fieldKey,
1269
+ name: fieldName,
1270
+ parent: target.refName,
1271
+ parentKind: target.__kind,
1272
+ parentName: target.name,
1273
+ ...(target.namespace !== undefined ? { parentNamespace: target.namespace } : {}),
1274
+ };
1275
+ const suffix = segments.slice(2).join(".");
1276
+ return [
1277
+ "record.",
1278
+ expr.dataAttr("elementum_field", registerForeignFieldLookup(fieldToken, refs.owner, refs.dataBlocks), ["id"]),
1279
+ ...(suffix.length > 0 ? [`.${suffix}`] : []),
1280
+ ];
1281
+ }
1090
1282
  function calculationTriggerMustache(name, refs) {
1283
+ const onDemandName = onDemandTriggerRefName(name, refs);
1284
+ if (onDemandName !== undefined)
1285
+ return [`{{trigger name="${onDemandName}"}}`];
1091
1286
  const parts = name.split(".");
1092
1287
  if (parts[0] !== "record" || parts.length < 2) {
1093
1288
  return [`{{trigger name="${name}"}}`];
@@ -1147,6 +1342,11 @@ const TS_TRIGGER_REF_TO_WIRE = {
1147
1342
  // onto FIELD_REF_SUFFIX_TO_WIRE — that table's `id` suffix is " ID", which
1148
1343
  // would emit the wrong wire key "Attachment ID" and fail live validation.
1149
1344
  "attachment.id": "Attachment Id",
1345
+ // Pull decodes refs["Record"] (ASPECT_RECORD_ID) as the branded accessor
1346
+ // ctx.trigger.recordId (from-tf wireName "Record" → ["recordId"]). Rebuild
1347
+ // must emit the live key — without this entry wireRefName leaves "recordId"
1348
+ // verbatim and plan fails with Invalid index on refs["recordId"].
1349
+ recordId: "Record",
1150
1350
  // NOT createdByEmail/updatedByManagerEmail: the real record-field path
1151
1351
  // ("record.createdBy.email") never reaches this flat lookup table (see
1152
1352
  // from-tf.ts's matching comment) — this table is for genuine trigger-level
@@ -1166,7 +1366,14 @@ const TS_TRIGGER_REF_TO_WIRE = {
1166
1366
  body: "Body (Plain Text)",
1167
1367
  body_html: "Body (Rich Text)",
1168
1368
  };
1169
- const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE).map((value) => [value.toLowerCase(), value]));
1369
+ // Exclude "Attachment Id" (attachment-trigger ATTACHMENT_ID): its
1370
+ // case-insensitive key collides with save_attachment's distinct live ref
1371
+ // "Attachment ID". Trigger paths resolve via TS_TRIGGER_REF_TO_WIRE
1372
+ // ("attachment.id") before this map; bracket-access "Attachment ID" must
1373
+ // pass through unchanged (#1651).
1374
+ const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE)
1375
+ .filter((value) => value !== "Attachment Id")
1376
+ .map((value) => [value.toLowerCase(), value]));
1170
1377
  const FIELD_REF_SUFFIX_TO_WIRE = {
1171
1378
  "": "",
1172
1379
  id: " ID",
@@ -1223,6 +1430,14 @@ function wireRefName(name, ctx) {
1223
1430
  const systemFieldKey = SYSTEM_FIELD_KEY_SET.has(fieldKey)
1224
1431
  ? fieldKey
1225
1432
  : undefined;
1433
+ if (systemFieldKey !== undefined &&
1434
+ ctx.recordLacksAuditFields === true &&
1435
+ ELEMENT_AUDIT_SYSTEM_FIELD_KEYS.includes(systemFieldKey) &&
1436
+ !ctx.fieldNames.has(fieldKey)) {
1437
+ throw new EntityTfError(`automation reference "${name}" reads audit field "${systemFieldKey}" on element "${ctx.appRefName}", which has no audit fields. ` +
1438
+ "The platform adds them to apps but only to some elements, and EDK cannot create them. " +
1439
+ "Remove the reference, or set systemFields: { audit: true } on an element the platform did give them to.");
1440
+ }
1226
1441
  const fieldName = systemFieldKey !== undefined && PROVIDER_FIXED_SYSTEM_FIELD_KEYS.has(systemFieldKey)
1227
1442
  ? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[systemFieldKey]
1228
1443
  : ctx.fieldNames.get(fieldKey) ??
@@ -1407,15 +1622,11 @@ function taskWireRefName(name, taskRefKey, refs) {
1407
1622
  return handleKey;
1408
1623
  const normalized = normalizeIndexedRecordsFieldPath(name);
1409
1624
  const taskApp = refs.recordFieldContext?.taskAppRefNameByRefKey?.[taskRefKey];
1410
- if (taskApp === undefined || taskApp === refs.owner.appRefName) {
1625
+ if (taskApp === undefined)
1411
1626
  return wireRefName(normalized, refs.owner);
1412
- }
1413
- const foreignNames = fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp);
1414
- return wireRefName(normalized, {
1415
- ...refs.owner,
1416
- appRefName: taskApp,
1417
- fieldNames: foreignNames ?? new Map(),
1418
- });
1627
+ return wireRefName(normalized, recordOwnerContext(refs.owner, taskApp, taskTargetKind(taskRefKey, refs), taskApp === refs.owner.appRefName
1628
+ ? refs.owner.fieldNames
1629
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, taskApp)));
1419
1630
  }
1420
1631
  /**
1421
1632
  * The platform refs-map key for one task output, given the emitting task's
@@ -1444,6 +1655,9 @@ function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1444
1655
  if (targetType === "elementum_ai_search_table_task" && (name === "records" || name === "All Records")) {
1445
1656
  return "All Records";
1446
1657
  }
1658
+ if (targetType === "elementum_ai_search_table_task" && AI_SEARCH_TABLE_OUTPUT_NAMES[name] !== undefined) {
1659
+ return AI_SEARCH_TABLE_OUTPUT_NAMES[name][0];
1660
+ }
1447
1661
  // tableRecordsSearch uses yet another wire key: "All matching table rows".
1448
1662
  if (targetType === "elementum_table_records_search_task" &&
1449
1663
  (name === "records" || name === "All matching table rows")) {
@@ -1451,7 +1665,32 @@ function taskOutputWireRefKey(targetType, name, taskRefKey, refs) {
1451
1665
  }
1452
1666
  return taskWireRefName(name, taskRefKey, refs);
1453
1667
  }
1668
+ /** The platform's own on-demand "Triggered By" refs (live refs-map keys). */
1669
+ const ON_DEMAND_TRIGGERED_BY_REFS = {
1670
+ "triggeredBy": "Triggered By's Id",
1671
+ "triggeredBy.id": "Triggered By's Id",
1672
+ "triggeredBy.email": "Triggered By's Email",
1673
+ "triggeredBy.name": "Triggered By's Name",
1674
+ };
1675
+ /**
1676
+ * The refs-map name of an on-demand `ctx.trigger.triggeredBy` read, which
1677
+ * every trigger reference (task input, calculation, publish output) shares.
1678
+ * A userId input has no reference at all, so reading one is refused.
1679
+ */
1680
+ function onDemandTriggerRefName(name, refs) {
1681
+ if (refs.trigger.type !== TRIGGER_RESOURCES.onDemand)
1682
+ return undefined;
1683
+ const userParam = refs.userParamNames.find((param) => name === param || name.startsWith(`${param}.`));
1684
+ if (userParam !== undefined) {
1685
+ throw new EntityTfError(`ctx.trigger.${name}: the platform publishes no reference for on-demand userId input "${userParam}", ` +
1686
+ `so a task cannot read it. Use ctx.trigger.triggeredBy (id/email/name) for the user who ran the automation.`);
1687
+ }
1688
+ return ON_DEMAND_TRIGGERED_BY_REFS[name];
1689
+ }
1454
1690
  function triggerWireRefName(name, refs) {
1691
+ const onDemandName = onDemandTriggerRefName(name, refs);
1692
+ if (onDemandName !== undefined)
1693
+ return onDemandName;
1455
1694
  const scalarParams = refs.triggerParamNames.filter((param) => !refs.recordParamNames.includes(param));
1456
1695
  const declared = onDemandTriggerRefKey(name, scalarParams);
1457
1696
  if (declared !== name || scalarParams.includes(name))
@@ -1480,20 +1719,110 @@ function recordParamFieldWireName(paramName, suffix, refs) {
1480
1719
  const targetFieldNames = targetRefName === refs.owner.appRefName && target.__kind === refs.owner.parentScope
1481
1720
  ? refs.owner.fieldNames
1482
1721
  : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, targetRefName);
1483
- return wireRefName(`record.${suffix}`, {
1484
- ...refs.owner,
1485
- appRefName: targetRefName,
1486
- fieldNames: targetFieldNames ?? new Map(),
1487
- });
1722
+ return wireRefName(`record.${suffix}`, recordOwnerContext(refs.owner, targetRefName, target.__kind === "element" || target.__kind === "app" ? target.__kind : undefined, targetFieldNames));
1488
1723
  }
1489
1724
  /** Run-automation targets reference publish for ACTIVE automations, automation for draft/inactive. */
1490
- export function automationRunTargetResourceAttr(appTfLabel, automationRefName, activeAutomationRefNames) {
1491
- const label = appScopedResourceLabel(appTfLabel, tsLabelToTfLabel(automationRefName));
1725
+ export function automationRunTargetResourceAttr(appTfLabel, automationRefName, activeAutomationRefNames, scope = "app", handle) {
1726
+ const label = automationResourceLabel(appTfLabel, automationRefName, scope, handle);
1492
1727
  if (activeAutomationRefNames?.has(automationRefName) === true) {
1493
1728
  return expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, label, ["id"]);
1494
1729
  }
1495
1730
  return expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label, ["id"]);
1496
1731
  }
1732
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1733
+ const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
1734
+ /** The provider's `ValidateFieldValue` datetime shape: seconds and a timezone are required. */
1735
+ const ISO_DATETIME_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
1736
+ /**
1737
+ * A literal the platform cannot coerce into the target field only fails at
1738
+ * apply. Checked for the field types where free text is never accepted:
1739
+ * user and group fields take ids, date fields ISO dates, datetime fields
1740
+ * ISO timestamps.
1741
+ */
1742
+ function assertLiteralFitsFieldType(value, field) {
1743
+ if (field === undefined || value === undefined)
1744
+ return;
1745
+ const fieldType = field.fieldType;
1746
+ const accepts = {
1747
+ USER: { test: (text) => UUID_PATTERN.test(text), expected: "a user id, or a user reference such as ctx.trigger.record.<userField>" },
1748
+ GROUP: { test: (text) => UUID_PATTERN.test(text), expected: "a group id, or a group reference" },
1749
+ DATE: { test: (text) => ISO_DATE_PATTERN.test(text) && !Number.isNaN(Date.parse(text)), expected: "an ISO date (YYYY-MM-DD) or a date reference" },
1750
+ DATETIME: {
1751
+ test: (text) => ISO_DATETIME_PATTERN.test(text) && !Number.isNaN(Date.parse(text)),
1752
+ expected: "an ISO timestamp with seconds and a timezone (YYYY-MM-DDTHH:MM:SS[.fff]Z or ±HH:MM) or a datetime reference",
1753
+ },
1754
+ };
1755
+ const rule = fieldType === undefined ? undefined : accepts[fieldType];
1756
+ if (rule === undefined)
1757
+ return;
1758
+ const label = field.name ?? field.refName ?? "unknown";
1759
+ if (isObject(value) && typeof value.__kind === "string") {
1760
+ const tokenKind = value.__kind;
1761
+ if ((fieldType === "USER" && tokenKind === "user") || (fieldType === "GROUP" && tokenKind === "group"))
1762
+ return;
1763
+ if (tokenKind === "user" || tokenKind === "group") {
1764
+ const identity = tokenKind === "user" && typeof value.email === "string"
1765
+ ? value.email
1766
+ : typeof value.name === "string" ? value.name : tokenKind;
1767
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given a ${tokenKind} token ${JSON.stringify(identity)}; it needs ${rule.expected}`);
1768
+ }
1769
+ }
1770
+ const text = isObject(value) && value.kind === "literal" && typeof value.value === "string" ? value.value : value;
1771
+ if (typeof text !== "string") {
1772
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given a ${typeof text} literal; it needs ${rule.expected}`);
1773
+ }
1774
+ // The provider refuses `${...}` templates on these four types too, so a
1775
+ // template string is not left to the platform here.
1776
+ if (rule.test(text))
1777
+ return;
1778
+ throw new EntityTfError(`automation field "${label}" (${fieldType}) is given the text ${JSON.stringify(text)}; it needs ${rule.expected}`);
1779
+ }
1780
+ /**
1781
+ * The platform refuses an element record create that leaves the title system
1782
+ * field empty, but only at apply and only as "Unable to validate". Fields
1783
+ * given by raw id cannot be identified, so those creates are left alone.
1784
+ */
1785
+ function assertElementCreateSetsTitle(target, fields) {
1786
+ if (!isObject(target) || target.__kind !== "element")
1787
+ return;
1788
+ const element = typeof target.name === "string" ? target.name : String(target.refName);
1789
+ let title;
1790
+ for (const field of fields) {
1791
+ if (!isObject(field) || !isObject(field.aspectFieldId) || typeof field.aspectFieldId.__kind !== "string")
1792
+ return;
1793
+ const token = field.aspectFieldId;
1794
+ if (token.tags?.includes("TITLE") === true || token.refName === "title")
1795
+ title = field;
1796
+ }
1797
+ if (title === undefined) {
1798
+ throw new EntityTfError(`createRecord on element "${element}" does not set its title field; the platform requires it and rejects the record at apply ("Unable to validate")`);
1799
+ }
1800
+ const reference = title.valueReference;
1801
+ const staticValue = isObject(reference) && "value" in reference ? reference.value : undefined;
1802
+ if (reference === undefined || reference === null || staticValue === "" || staticValue === null) {
1803
+ throw new EntityTfError(`createRecord on element "${element}" sets its title field to an empty value; the platform requires a title and rejects the record at apply ("Unable to validate")`);
1804
+ }
1805
+ }
1806
+ /**
1807
+ * The platform publishes outputs only from tasks at the top level of the
1808
+ * workflow, never from a task inside a switch case or for-each loop, and
1809
+ * rejects an output whose task is not in the workflow at all.
1810
+ */
1811
+ function assertPublishableOutputTask(outputName, value, topLevelTasks, refs) {
1812
+ while (isObject(value) && "value" in value && Object.keys(value).length === 1) {
1813
+ value = value.value;
1814
+ }
1815
+ if (!isObject(value) || !isObject(value.taskReference) || typeof value.taskReference.taskRefKey !== "string")
1816
+ return;
1817
+ const taskRefKey = value.taskReference.taskRefKey;
1818
+ if (!refs.tasks.has(taskRefKey)) {
1819
+ throw new EntityTfError(`automation output "${outputName}" references task "${taskRefKey}", which is not in this automation`);
1820
+ }
1821
+ if (!topLevelTasks.some((task) => task.refKey === taskRefKey)) {
1822
+ throw new EntityTfError(`automation output "${outputName}" references task "${taskRefKey}" inside a switch case or for-each loop; ` +
1823
+ "the platform publishes outputs only from top-level tasks. Copy the value into a variable at the top level and output that.");
1824
+ }
1825
+ }
1497
1826
  /**
1498
1827
  * workflow_publish outputs must match provider Read / ei export: a typed
1499
1828
  * `jsonencode({ fieldType, multiple, taskReference|... })` envelope — not
@@ -1554,55 +1883,92 @@ function createRecordOwnFieldRefTfValue(target, name, refs) {
1554
1883
  return undefined;
1555
1884
  return expr.template(["record.", fieldId, `.${suffix}`]);
1556
1885
  }
1886
+ /**
1887
+ * The canonical reference envelope for a workflow-OUTPUT task reference —
1888
+ * `{ fieldType, multiple, taskReference:{ name:<canonical>, taskId }, … }`.
1889
+ * By the time an output reaches here its `taskReference.name` is already the
1890
+ * platform's CANONICAL service_tasks output name (build.ts's
1891
+ * `rewriteCanonicalOutputRefName`): the platform validates the published output
1892
+ * against that name (edk#835), so EDK emits it directly instead of the refs-map
1893
+ * display label. The exceptions keep their existing resolution, since they
1894
+ * reference FIELDS / declared values by EDK-owned names, not the mobius
1895
+ * display-label drift class: a task's own record field (`record.<field>`),
1896
+ * aiAgent (platform-nested via {@link aiAgentPlatformRefName}), and file-reader
1897
+ * (arbitrary schema field names). `fieldType`/`multiple` come from the generated
1898
+ * service_tasks contract (via {@link publishOutputType}). Returns undefined when
1899
+ * the target task is unresolved so the caller keeps its own fallback.
1900
+ */
1901
+ function taskReferenceEnvelope(value, refs) {
1902
+ const taskRef = value.taskReference;
1903
+ if (taskRef.name.includes('"')) {
1904
+ throw new EntityTfError(`task output name "${taskRef.name}" contains a double quote`);
1905
+ }
1906
+ const target = refs.tasks.get(taskRef.taskRefKey);
1907
+ if (target === undefined)
1908
+ return undefined;
1909
+ const canonicalName = taskRef.name;
1910
+ const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
1911
+ const isAiAgentTask = target.type === "elementum_ai_agent_task";
1912
+ // A task's OWN just-created/found record FIELD (`record.<field>`) is not a
1913
+ // task-output name — it resolves by the field's own id/display name. No
1914
+ // canonical output is ever spelled `record.<field>` (the contract has
1915
+ // record/records/recordId), so that dotted prefix uniquely marks it.
1916
+ const isOwnRecordFieldRef = canonicalName.startsWith("record.");
1917
+ const ownRecordFieldRef = createRecordOwnFieldRefTfValue(target, canonicalName, refs);
1918
+ const platformRefName = ownRecordFieldRef
1919
+ ?? (isFileReaderTask
1920
+ ? canonicalName
1921
+ : isOwnRecordFieldRef
1922
+ ? taskWireRefName(canonicalName, taskRef.taskRefKey, refs)
1923
+ : isAiAgentTask
1924
+ ? aiAgentPlatformRefName(canonicalName)
1925
+ : canonicalName);
1926
+ const typed = publishOutputType(value, target, canonicalName);
1927
+ return {
1928
+ fieldType: typed.fieldType,
1929
+ multiple: typed.multiple,
1930
+ taskReference: {
1931
+ name: platformRefName,
1932
+ taskId: expr.resourceAttr(target.type, target.label, ["id"]),
1933
+ },
1934
+ // ei export always pads the unused reference arms with null.
1935
+ triggerReference: null,
1936
+ variableReference: null,
1937
+ };
1938
+ }
1557
1939
  function workflowPublishOutputEnvelope(value, refs) {
1558
1940
  if (!isObject(value))
1559
1941
  return undefined;
1560
1942
  if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
1561
- if (value.taskReference.name.includes('"')) {
1562
- throw new EntityTfError(`task output name "${value.taskReference.name}" contains a double quote`);
1563
- }
1564
- const target = refs.tasks.get(value.taskReference.taskRefKey);
1565
- if (target === undefined)
1566
- return undefined;
1567
- const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
1568
- const isAiAgentTask = target.type === "elementum_ai_agent_task";
1569
- const isAiSearchTableRecords = target.type === "elementum_ai_search_table_task" &&
1570
- (value.taskReference.name === "records" || value.taskReference.name === "All Records");
1571
- const isTableRecordsSearchRecords = target.type === "elementum_table_records_search_task" &&
1572
- (value.taskReference.name === "records" || value.taskReference.name === "All matching table rows");
1573
- const refsKey = isFileReaderTask || isAiAgentTask
1574
- ? value.taskReference.name
1575
- : isAiSearchTableRecords
1576
- ? "All Records"
1577
- : isTableRecordsSearchRecords
1578
- ? value.taskReference.name === "All matching table rows"
1579
- ? "All matching table rows"
1580
- : "records"
1581
- : taskWireRefName(value.taskReference.name, value.taskReference.taskRefKey, refs);
1582
- const ownRecordFieldRef = createRecordOwnFieldRefTfValue(target, value.taskReference.name, refs);
1583
- const platformRefName = ownRecordFieldRef ?? (isAiAgentTask
1584
- ? aiAgentPlatformRefName(refsKey)
1585
- : refsKey);
1586
- const typed = publishOutputType(value, target, refsKey);
1587
- return {
1588
- fieldType: typed.fieldType,
1589
- multiple: typed.multiple,
1590
- taskReference: {
1591
- name: platformRefName,
1592
- taskId: expr.resourceAttr(target.type, target.label, ["id"]),
1593
- },
1594
- // ei export always pads the unused reference arms with null.
1595
- triggerReference: null,
1596
- variableReference: null,
1597
- };
1943
+ return taskReferenceEnvelope(value, refs);
1598
1944
  }
1599
1945
  if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
1946
+ const inputName = onDemandTriggerRefKey(value.triggerReference.name, [...refs.triggerParamFieldTypes.keys()]);
1947
+ const input = refs.triggerParamFieldTypes.get(inputName);
1948
+ if (input !== undefined) {
1949
+ // The platform stores a reference to an on-demand input under the
1950
+ // input's normalized name ("TICKET_ID" → "ticketId") and reads it back
1951
+ // that way, so emit that name rather than the declared one; the
1952
+ // envelope carries the input's declared type.
1953
+ const typed = typeof value.fieldType === "string"
1954
+ ? { fieldType: value.fieldType, multiple: value.multiple === true }
1955
+ : input;
1956
+ return {
1957
+ fieldType: typed.fieldType,
1958
+ multiple: typed.multiple,
1959
+ taskReference: null,
1960
+ triggerReference: { name: normalizeOnDemandParamKey(inputName) },
1961
+ variableReference: null,
1962
+ };
1963
+ }
1600
1964
  const typed = publishOutputType(value, undefined, value.triggerReference.name);
1601
1965
  return {
1602
1966
  fieldType: typed.fieldType,
1603
1967
  multiple: typed.multiple,
1604
1968
  taskReference: null,
1605
- triggerReference: { name: wireRefName(value.triggerReference.name, refs.owner) },
1969
+ triggerReference: {
1970
+ name: onDemandTriggerRefName(value.triggerReference.name, refs) ?? wireRefName(value.triggerReference.name, refs.owner),
1971
+ },
1606
1972
  variableReference: null,
1607
1973
  };
1608
1974
  }
@@ -1631,7 +1997,7 @@ function workflowPublishOutputEnvelope(value, refs) {
1631
1997
  return {
1632
1998
  taskReference: null,
1633
1999
  triggerReference: null,
1634
- variableReference: { name: expr.template(["variable|", expr.resourceAttr(target.type, target.label, ["variable_id"])]) },
2000
+ variableReference: { name: expr.template(["variable|", variableIdAttr(target)]) },
1635
2001
  };
1636
2002
  }
1637
2003
  const name = typeof value.variableReference.name === "string" ? value.variableReference.name : undefined;
@@ -1670,6 +2036,16 @@ function publishOutputType(value, target, wireName) {
1670
2036
  if (fromSchema !== undefined)
1671
2037
  return fromSchema;
1672
2038
  }
2039
+ // Canonical reference model: for a workflow OUTPUT, `wireName` is the platform's
2040
+ // canonical output name — take fieldType + multiple straight from the generated
2041
+ // service_tasks contract. The display-name heuristics below stay for the legacy
2042
+ // forms. See DESIGN-canonical-reference-model.md.
2043
+ if (target !== undefined) {
2044
+ const executor = RESOURCE_TYPE_TO_EXECUTOR[target.type];
2045
+ const contract = executor !== undefined ? TASK_OUTPUT_CONTRACTS[executor]?.[wireName] : undefined;
2046
+ if (contract !== undefined)
2047
+ return { fieldType: contract.fieldType, multiple: contract.multiple };
2048
+ }
1673
2049
  if (target !== undefined) {
1674
2050
  if ((target.type === "elementum_create_record_task" || target.type === "elementum_find_related_records_task") &&
1675
2051
  (wireName === "Record" || wireName === "Record ID")) {
@@ -1686,6 +2062,183 @@ function publishOutputType(value, target, wireName) {
1686
2062
  }
1687
2063
  return { fieldType: "TEXT", multiple: value.multiple === true };
1688
2064
  }
2065
+ function collectUnresolvedForEachItems(value, found) {
2066
+ if (Array.isArray(value)) {
2067
+ for (const item of value)
2068
+ collectUnresolvedForEachItems(item, found);
2069
+ return;
2070
+ }
2071
+ if (!isObject(value))
2072
+ return;
2073
+ if (typeof value.__edkUnresolvedForEachItem === "string") {
2074
+ const path = Array.isArray(value.path) ? value.path.filter((segment) => typeof segment === "string").join(".") : "";
2075
+ found.push({ ref: value.__edkUnresolvedForEachItem, path });
2076
+ }
2077
+ for (const nested of Object.values(value))
2078
+ collectUnresolvedForEachItems(nested, found);
2079
+ }
2080
+ /** The onDemand trigger's record parameters: they expose only a record ID. */
2081
+ function onDemandRecordParamNames(trigger) {
2082
+ const inputs = trigger?.onDemand?.inputs;
2083
+ if (!Array.isArray(inputs))
2084
+ return new Set();
2085
+ return new Set(inputs.flatMap((input) => {
2086
+ const param = input;
2087
+ return typeof param?.name === "string" && isOnDemandRecordType(typeof param.type === "string" ? param.type : undefined) ? [param.name] : [];
2088
+ }));
2089
+ }
2090
+ /** refKey → task kind (`findRelatedRecords`, …) for every task, nested ones included. */
2091
+ function collectPayloadTaskKinds(value, kinds) {
2092
+ if (Array.isArray(value)) {
2093
+ for (const item of value)
2094
+ collectPayloadTaskKinds(item, kinds);
2095
+ return kinds;
2096
+ }
2097
+ if (!isObject(value))
2098
+ return kinds;
2099
+ if (typeof value.refKey === "string" && isObject(value.task)) {
2100
+ const kind = Object.keys(value.task)[0];
2101
+ if (kind !== undefined)
2102
+ kinds.set(value.refKey, kind);
2103
+ }
2104
+ for (const nested of Object.values(value))
2105
+ collectPayloadTaskKinds(nested, kinds);
2106
+ return kinds;
2107
+ }
2108
+ /**
2109
+ * edk#1499: script-input field mappings read fields off a whole record. A
2110
+ * value that exposes only a record ID (an onDemand record parameter, or
2111
+ * findRelatedRecords' `.record`) deploys refs["Record"] (ASPECT_RECORD_ID)
2112
+ * plus field mappings, and the script receives `{}` at runtime. Record
2113
+ * triggers' `ctx.trigger.record` and the `.record` of recordSearch,
2114
+ * createRecord and updateField carry the whole record (#1284, #1489).
2115
+ */
2116
+ export function recordIdFieldMappingFailures(entity, payload, address) {
2117
+ const onDemandRecordParams = onDemandRecordParamNames(payload.trigger);
2118
+ const taskKinds = collectPayloadTaskKinds(payload, new Map());
2119
+ const name = "name" in payload && typeof payload.name === "string" && payload.name !== "" ? payload.name : entity.refName;
2120
+ const failures = [];
2121
+ const visit = (value, action) => {
2122
+ if (Array.isArray(value)) {
2123
+ for (const item of value)
2124
+ visit(item, action);
2125
+ return;
2126
+ }
2127
+ if (!isObject(value))
2128
+ return;
2129
+ const here = typeof value.refKey === "string" && isObject(value.task) ? value.refKey : action;
2130
+ if (Array.isArray(value.field_mappings) && isObject(value.value)) {
2131
+ let source;
2132
+ const trigger = value.value.triggerReference;
2133
+ if (isObject(trigger) && typeof trigger.name === "string" && onDemandRecordParams.has(trigger.name)) {
2134
+ source = `ctx.trigger.${trigger.name} (an on-demand record parameter)`;
2135
+ }
2136
+ const task = value.value.taskReference;
2137
+ if (isObject(task) && typeof task.taskRefKey === "string" && task.name === "record" && taskKinds.get(task.taskRefKey) === "findRelatedRecords") {
2138
+ source = `ctx.actions.${task.taskRefKey}.record (findRelatedRecords)`;
2139
+ }
2140
+ if (source !== undefined) {
2141
+ failures.push({
2142
+ severity: "fatal",
2143
+ address,
2144
+ name,
2145
+ ownerKind: "automation",
2146
+ message: `action "${here ?? "?"}" input "${typeof value.name === "string" ? value.name : "?"}": withFieldMappings(${source}) maps fields off a value that is only a record ID, ` +
2147
+ "so the script would receive {} at runtime. Look the record up first with a recordSearch on that ID " +
2148
+ "(e.g. .recordSearch(\"lookup\", …) filtered on the record id) and pass withFieldMappings(ctx.actions.lookup.record, …).",
2149
+ });
2150
+ }
2151
+ }
2152
+ for (const nested of Object.values(value))
2153
+ visit(nested, here);
2154
+ };
2155
+ visit(payload, undefined);
2156
+ return failures;
2157
+ }
2158
+ function unresolvedForEachFailures(entity, payload, address) {
2159
+ const found = [];
2160
+ collectUnresolvedForEachItems(payload, found);
2161
+ if (found.length === 0)
2162
+ return [];
2163
+ const name = "name" in payload && typeof payload.name === "string" && payload.name !== "" ? payload.name : entity.refName;
2164
+ return found.map((item) => ({
2165
+ severity: "fatal",
2166
+ address,
2167
+ name,
2168
+ ownerKind: "automation",
2169
+ message: `unresolved forEach item reference to "${item.ref}"${item.path !== "" ? `.${item.path}` : ""}: ` +
2170
+ "EDK cannot express a reference to a sibling loop's current item (only an enclosing loop, as " +
2171
+ "ctx.loops.<name>.item) - re-express this by hand " +
2172
+ "(e.g. restructure the loops, or pass the value through a variable) before this automation can build",
2173
+ }));
2174
+ }
2175
+ /**
2176
+ * execute_script `inputs[].value` only. Provider Read stores the
2177
+ * Mobius-normalized short name (`reasonForClosingEarly`) for on-demand
2178
+ * scalars; emitting refs["Reason for Closing Early"] drifts when that
2179
+ * display name also labels an app field. Other attrs keep refs["…"].
2180
+ */
2181
+ function executeScriptInputValueToTf(value, refs) {
2182
+ if (isObject(value) &&
2183
+ isObject(value.triggerReference) &&
2184
+ typeof value.triggerReference.name === "string" &&
2185
+ value[TRIGGER_WHOLE_RECORD_MARKER] !== true &&
2186
+ refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2187
+ const inputName = onDemandTriggerRefKey(value.triggerReference.name, [...refs.triggerParamFieldTypes.keys()]);
2188
+ const input = refs.triggerParamFieldTypes.get(inputName);
2189
+ // userId params publish no refs — fall through so valueToTf refuses them.
2190
+ if (input !== undefined &&
2191
+ !refs.recordParamNames.includes(inputName) &&
2192
+ !refs.userParamNames.includes(inputName)) {
2193
+ const typed = typeof value.fieldType === "string"
2194
+ ? { fieldType: value.fieldType, multiple: value.multiple === true }
2195
+ : input;
2196
+ return expr.jsonencode({
2197
+ fieldType: typed.fieldType,
2198
+ multiple: typed.multiple,
2199
+ triggerReference: { name: normalizeOnDemandParamKey(inputName) },
2200
+ });
2201
+ }
2202
+ }
2203
+ return valueToTf(value, refs);
2204
+ }
2205
+ /**
2206
+ * Pulled createRecord / updateField values sometimes embed a JSON envelope
2207
+ * string whose `triggerReference.name` is `recordId` and whose `fieldType`
2208
+ * is still `TEXT`. Live provider state for that record-trigger identity is
2209
+ * `ASPECT_RECORD_ID` (#1626). `record.id` is the TEXT handle (`refs["ID"]`)
2210
+ * and an on-demand text input that happens to be named `recordId` stays
2211
+ * TEXT, so neither is rewritten. Sibling keys and their order are kept.
2212
+ */
2213
+ function normalizeTriggerRecordIdEnvelopeString(raw, refs) {
2214
+ const trimmed = raw.trim();
2215
+ if (!trimmed.startsWith("{"))
2216
+ return raw;
2217
+ let parsed;
2218
+ try {
2219
+ parsed = JSON.parse(trimmed);
2220
+ }
2221
+ catch {
2222
+ return raw;
2223
+ }
2224
+ if (!isObject(parsed) || typeof parsed.fieldType !== "string")
2225
+ return raw;
2226
+ if (!isObject(parsed.triggerReference) || typeof parsed.triggerReference.name !== "string")
2227
+ return raw;
2228
+ if (parsed.triggerReference.name !== "recordId")
2229
+ return raw;
2230
+ if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2231
+ const inputName = onDemandTriggerRefKey(parsed.triggerReference.name, [...refs.triggerParamFieldTypes.keys()]);
2232
+ if (refs.triggerParamFieldTypes.has(inputName))
2233
+ return raw;
2234
+ }
2235
+ if (parsed.fieldType === "ASPECT_RECORD_ID" && parsed.multiple === false)
2236
+ return raw;
2237
+ const envelope = parsed;
2238
+ envelope.fieldType = "ASPECT_RECORD_ID";
2239
+ envelope.multiple = false;
2240
+ return JSON.stringify(envelope);
2241
+ }
1689
2242
  function valueToTf(value, refs) {
1690
2243
  const catalog = token(value);
1691
2244
  if (catalog !== undefined)
@@ -1698,14 +2251,16 @@ function valueToTf(value, refs) {
1698
2251
  throw new EntityTfError(`unsupported automation value ${String(value)}`);
1699
2252
  if (typeof value.__edkUnresolvedForEachItem === "string") {
1700
2253
  // Printed by print-automation.ts for a forEachItemRef pointing at a
1701
- // sibling or non-nearest-ancestor loop - EDK has no authoring primitive
1702
- // for "another loop's current item". Fail the build loudly instead of
1703
- // silently reinterpreting this as a task-output reference: `ctx.actions`
1704
- // would have turned ANY property-access shape into a real, but WRONG,
1705
- // task ref (review feedback on PR #1097, cursor[bot]).
2254
+ // sibling loop - one that doesn't enclose the task. EDK has no
2255
+ // authoring form for it (an enclosing loop is ctx.loops.<name>.item,
2256
+ // #1320). Fail the build loudly instead of silently reinterpreting
2257
+ // this as a task-output reference: `ctx.actions` would have turned ANY
2258
+ // property-access shape into a real, but WRONG, task ref (review
2259
+ // feedback on PR #1097, cursor[bot]).
1706
2260
  const path = Array.isArray(value.path) ? value.path.join(".") : "";
1707
2261
  throw new EntityTfError(`unresolved forEach item reference to "${value.__edkUnresolvedForEachItem}"${path ? `.${path}` : ""}: ` +
1708
- `EDK cannot express a reference to another loop's current item - re-express this by hand ` +
2262
+ `EDK cannot express a reference to a sibling loop's current item (only an enclosing loop, as ` +
2263
+ `ctx.loops.<name>.item) - re-express this by hand ` +
1709
2264
  `(e.g. restructure the loops, or pass the value through a variable) before this automation can build`);
1710
2265
  }
1711
2266
  if (value.__unsafe === "platformId" && typeof value.value === "string") {
@@ -1714,6 +2269,10 @@ function valueToTf(value, refs) {
1714
2269
  }
1715
2270
  if ("value" in value && Object.keys(value).length === 1)
1716
2271
  return valueToTf(value.value, refs);
2272
+ if (value.kind === "requiredSecret" && typeof value.variable === "string") {
2273
+ refs.requiredSecrets.add(value.variable);
2274
+ return expr.variable(value.variable);
2275
+ }
1717
2276
  if (isObject(value.variableReference) && typeof value.variableReference.id === "string") {
1718
2277
  const target = refs.variableById.get(value.variableReference.id);
1719
2278
  if (target === undefined)
@@ -1721,6 +2280,17 @@ function valueToTf(value, refs) {
1721
2280
  return expr.resourceAttr(target.type, target.label, ["refs", { index: target.name }]);
1722
2281
  }
1723
2282
  if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
2283
+ // A record trigger's whole record has no refs key of its own: refs["Record"]
2284
+ // is the record ID (edk#1284). On-demand triggers name record params, not
2285
+ // `record`, so they keep their refs keys.
2286
+ if (value[TRIGGER_WHOLE_RECORD_MARKER] === true && refs.trigger.type !== TRIGGER_RESOURCES.onDemand) {
2287
+ return triggerWholeRecordRefJson(value.triggerReference.name);
2288
+ }
2289
+ if (refs.trigger.type === TRIGGER_RESOURCES.attachment && value.triggerReference.name.startsWith("attachment.")) {
2290
+ const payloadRef = triggerAttachmentPayloadRef(value.triggerReference.name.slice("attachment.".length));
2291
+ if (payloadRef !== undefined)
2292
+ return expr.jsonencode(payloadRef);
2293
+ }
1724
2294
  return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: triggerWireRefName(value.triggerReference.name, refs) }]);
1725
2295
  }
1726
2296
  if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
@@ -1739,13 +2309,19 @@ function valueToTf(value, refs) {
1739
2309
  const target = refs.tasks.get(value.forEachReference.forEachTaskRefKey);
1740
2310
  if (target === undefined)
1741
2311
  throw new EntityTfError(`unresolved forEach ref "${value.forEachReference.forEachTaskRefKey}"`);
1742
- const index = forEachWireRefName(value.forEachReference.name, refs.owner, refs.recordItemForEachRefKeys.has(value.forEachReference.forEachTaskRefKey));
2312
+ const source = refs.recordItemForEachSourceByRefKey.get(value.forEachReference.forEachTaskRefKey);
2313
+ const sourceApp = source === undefined ? undefined : refs.recordFieldContext?.taskAppRefNameByRefKey?.[source];
2314
+ const index = forEachWireRefName(value.forEachReference.name, source === undefined || sourceApp === undefined
2315
+ ? refs.owner
2316
+ : recordOwnerContext(refs.owner, sourceApp, taskTargetKind(source, refs), sourceApp === refs.owner.appRefName
2317
+ ? refs.owner.fieldNames
2318
+ : fieldNamesForAppRefName(refs.fieldNamesByAppRefName, sourceApp) ?? refs.owner.fieldNames), refs.recordItemForEachRefKeys.has(value.forEachReference.forEachTaskRefKey));
1743
2319
  return expr.resourceAttr(target.type, target.label, ["inner", "refs", { index }]);
1744
2320
  }
1745
2321
  if (isObject(value.templateReference))
1746
2322
  return templateToTf(value.templateReference, refs);
1747
2323
  if (isObject(value.secretReference) && typeof value.secretReference.secretId === "string") {
1748
- throw new EntityTfError("secret references have no provider HCL representation");
2324
+ return vaultEntryRefToTf(value.secretReference.secretId, refs);
1749
2325
  }
1750
2326
  if (typeof value.kind === "string") {
1751
2327
  if (value.kind === "localRef" && typeof value.localName === "string" && Array.isArray(value.path)) {
@@ -1773,6 +2349,79 @@ function unwrapDefault(value) {
1773
2349
  function isOptionBearingPicklist(metadata) {
1774
2350
  return metadata?.fieldType === "PICKLIST" && (metadata.options?.length ?? 0) > 0;
1775
2351
  }
2352
+ /** A person or group field's bare reference is the whole value, which DEV fails to null-check as a uuid; its id is not. */
2353
+ function isIdentityField(metadata) {
2354
+ return metadata?.fieldType === "USER" || metadata?.fieldType === "GROUP";
2355
+ }
2356
+ /**
2357
+ * A filter on an on-demand record input's field. The platform names it
2358
+ * `<parameter>.<fieldId>` (the internal path `availableReferences` reports
2359
+ * for every record input, `record.<fieldId>` included), so the short form is
2360
+ * `trigger.<parameter>.<fieldId>[.<suffix>]`. `filter_refs` only carries
2361
+ * whole parameters and has no key for a field.
2362
+ */
2363
+ function onDemandRecordFieldPath(name, refs) {
2364
+ const paramName = refs.recordParamNames
2365
+ .filter((param) => name.startsWith(`${param}.`))
2366
+ .sort((a, b) => b.length - a.length)[0];
2367
+ if (paramName === undefined)
2368
+ return undefined;
2369
+ const [fieldKey, ...rest] = name.slice(paramName.length + 1).split(".");
2370
+ if (fieldKey === undefined || fieldKey === "")
2371
+ return undefined;
2372
+ const target = refs.recordParamTargets.get(paramName);
2373
+ if (target === undefined) {
2374
+ throw new EntityTfError(`onDemand record parameter "${paramName}" is missing its target app/element`);
2375
+ }
2376
+ const isOwner = target.refName === refs.owner.appRefName && (target.__kind ?? refs.owner.parentScope) === refs.owner.parentScope;
2377
+ return { paramName, fieldKey, suffix: rest.join("."), target, isOwner };
2378
+ }
2379
+ function onDemandRecordFieldFilterReference(name, refs, operator) {
2380
+ const path = onDemandRecordFieldPath(name, refs);
2381
+ if (path === undefined)
2382
+ return undefined;
2383
+ const { paramName, fieldKey, suffix, target, isOwner } = path;
2384
+ if (fieldKey.startsWith(UNRESOLVED_FIELD_MARKER))
2385
+ return `trigger.${name.replace(UNRESOLVED_FIELD_MARKER, "")}`;
2386
+ const fieldAddresses = isOwner ? refs.owner.fieldAddresses : fieldNamesForAppRefName(refs.fieldAddressesByAppRefName, target.refName);
2387
+ if (suffix.length === 0 && isOwner && isOptionBearingPicklist(refs.owner.fieldMetadata.get(fieldKey)) && operator !== "is_null") {
2388
+ throw new EntityTfError(`filter reference to picklist field "${fieldKey}" is ambiguous — write ".id" ` +
2389
+ `(ctx.trigger.${paramName}.${fieldKey}.id) or ".label" (ctx.trigger.${paramName}.${fieldKey}.label) explicitly.`);
2390
+ }
2391
+ const wireSuffix = suffix === "recordId"
2392
+ ? "10000001-2000-4000-a000-800000000000"
2393
+ : suffix.length === 0 && isOwner && isOptionBearingPicklist(refs.owner.fieldMetadata.get(fieldKey)) ? "id"
2394
+ : suffix.length === 0 && isOwner && operator === "is_null" && isIdentityField(refs.owner.fieldMetadata.get(fieldKey)) ? "id" : suffix;
2395
+ const tail = wireSuffix.length > 0 ? [`.${wireSuffix}`] : [];
2396
+ const address = fieldAddresses?.get(fieldKey);
2397
+ if (address !== undefined) {
2398
+ return expr.template([`trigger.${paramName}.`, addressExpr(address, ["id"]), ...tail]);
2399
+ }
2400
+ const targetTfLabel = isOwner
2401
+ ? refs.owner.appTfLabel
2402
+ : refs.owner.workspaceAspects?.get(workspaceAspectKey(target.__kind === "element" ? "element" : "app", target.refName))?.tfLabel;
2403
+ const isSystemField = (target.__kind ?? refs.owner.parentScope) === "element"
2404
+ ? ELEMENT_SYSTEM_FIELD_KEYS.includes(fieldKey)
2405
+ : SYSTEM_FIELD_KEY_SET.has(fieldKey);
2406
+ if (isSystemField && targetTfLabel !== undefined) {
2407
+ return expr.template([`trigger.${paramName}.`, expr.local(`${targetTfLabel}_${tsLabelToTfLabel(fieldKey)}_field_id`), ...tail]);
2408
+ }
2409
+ if (isUuid(fieldKey))
2410
+ return `trigger.${name}`;
2411
+ throw new EntityTfError(`filter reference to "${fieldKey}" on on-demand record input "${paramName}": ${target.refName} is not built in this ` +
2412
+ `workspace or has no field "${fieldKey}", so its field id cannot be resolved`);
2413
+ }
2414
+ /**
2415
+ * The canonical (`service_tasks`) name of a single-output AI task's output,
2416
+ * when `wireName` is that output's refs display label. The filter short form
2417
+ * `task.<id>.<name>` uses it (`response`), not the label (`Response`).
2418
+ */
2419
+ function canonicalSingleOutputName(resourceType, wireName) {
2420
+ const taskKey = Object.keys(TASK_RESOURCES).find((key) => TASK_RESOURCES[key] === resourceType);
2421
+ if (taskKey === undefined || OUTPUT_KEY_WIRE_NAME[taskKey] !== wireName)
2422
+ return undefined;
2423
+ return OUTPUT_KEY_CANONICAL[taskKey];
2424
+ }
1776
2425
  function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1777
2426
  // Raw pass-through for a filter left side the pull-time deserializer
1778
2427
  // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
@@ -1792,6 +2441,11 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1792
2441
  // convention from the `.refs[...]` map lookup used for task inputs.
1793
2442
  // Reproduce it via a template so the field id stays a real reference
1794
2443
  // (never hardcoded), matching the actual export byte-for-byte.
2444
+ if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2445
+ const recordField = onDemandRecordFieldFilterReference(value.name, refs, operator);
2446
+ if (recordField !== undefined)
2447
+ return recordField;
2448
+ }
1795
2449
  const parts = value.name.split(".");
1796
2450
  if (parts[0] === "record" && parts.length >= 2) {
1797
2451
  const fieldKey = parts[1];
@@ -1810,6 +2464,8 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1810
2464
  `(ctx.trigger.record.${fieldKey}.label, compare by display text) explicitly.`);
1811
2465
  }
1812
2466
  }
2467
+ if (suffix.length === 0 && operator === "is_null" && isIdentityField(refs.owner.fieldMetadata.get(fieldKey)))
2468
+ wireSuffix = "id";
1813
2469
  if (refs.trigger.type === TRIGGER_RESOURCES.datamine && refs.triggerDatamineTable !== undefined) {
1814
2470
  const table = refs.triggerDatamineTable;
1815
2471
  const tableAttr = resolveTableColumnFieldExpr({
@@ -1870,8 +2526,24 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1870
2526
  return `trigger.${value.name.replace(UNRESOLVED_FIELD_MARKER, "")}`;
1871
2527
  }
1872
2528
  }
2529
+ // Whole-record ID in a FILTER on a record-event trigger: ei exports the
2530
+ // short form `trigger.recordId`. Task inputs correctly use refs["Record"]
2531
+ // (ASPECT_RECORD_ID), but that JSON envelope plans as drift against the
2532
+ // short form after every pull. On-demand must NOT take this path —
2533
+ // `record` / `recordId` there are declared inputs that belong in
2534
+ // filter_refs["Record"] (edk#1524).
2535
+ if (refs.trigger.type !== TRIGGER_RESOURCES.onDemand &&
2536
+ (value.name === "recordId" || value.name === "record")) {
2537
+ return "trigger.recordId";
2538
+ }
1873
2539
  const triggerRefKey = triggerWireRefName(value.name, refs);
1874
2540
  if (refs.trigger.type === TRIGGER_RESOURCES.onDemand) {
2541
+ // filter_refs holds only declared inputs, so the clicking user has no key there.
2542
+ if (ON_DEMAND_TRIGGERED_BY_REFS[value.name] !== undefined) {
2543
+ throw new EntityTfError(`filter on ctx.trigger.${value.name}: an on-demand filter can only reference declared inputs, ` +
2544
+ `and the platform publishes no filter reference for the user who ran the automation. ` +
2545
+ `Read ctx.trigger.triggeredBy in a task input instead.`);
2546
+ }
1875
2547
  return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["filter_refs", { index: triggerRefKey }]);
1876
2548
  }
1877
2549
  return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: triggerRefKey }]);
@@ -1928,6 +2600,66 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1928
2600
  },
1929
2601
  });
1930
2602
  }
2603
+ // A file reader's `refs` keys each parsed value by its own name; the
2604
+ // `jsonValues.<key>` path exists only as a stored envelope.
2605
+ if (isFileReaderTask && wireName.startsWith("jsonValues.")) {
2606
+ return expr.jsonencode({
2607
+ fieldType: (realType ?? "TEXT").toUpperCase(),
2608
+ multiple: false,
2609
+ taskReference: {
2610
+ name: wireName,
2611
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2612
+ },
2613
+ });
2614
+ }
2615
+ // An explicit filter.text() on a runAutomation output is a TEXT
2616
+ // envelope. A missing realType stays on .refs; the provider's refs
2617
+ // map is already TEXT for outputs ei stores that way.
2618
+ if (task.type === TASK_RESOURCES.runAutomation && realType?.toUpperCase() === "TEXT") {
2619
+ return expr.jsonencode({
2620
+ fieldType: "TEXT",
2621
+ multiple: false,
2622
+ taskReference: {
2623
+ name: wireName,
2624
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2625
+ },
2626
+ });
2627
+ }
2628
+ // A text comparison of a boolean, integer, or script-number output
2629
+ // stores a TEXT envelope, while `refs` carries the declared type.
2630
+ // A script `number` output is declared DECIMAL; NUMBER is the integer
2631
+ // projection. Id-typed outputs keep their own type.
2632
+ const envelopeName = TASK_OUTPUT_REFERENCE_NAMES[task.type]?.[wireName] ?? wireName;
2633
+ const executor = RESOURCE_TYPE_TO_EXECUTOR[task.type];
2634
+ const declared = task.outputFieldTypes?.get(wireName) ??
2635
+ (executor === undefined ? undefined : TASK_OUTPUT_CONTRACTS[executor]?.[envelopeName]);
2636
+ if (realType?.toUpperCase() === "TEXT" && (declared?.fieldType === "BOOLEAN" || declared?.fieldType === "NUMBER" || declared?.fieldType === "DECIMAL")) {
2637
+ return expr.jsonencode({
2638
+ fieldType: "TEXT",
2639
+ multiple: declared.multiple,
2640
+ taskReference: {
2641
+ name: envelopeName,
2642
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2643
+ },
2644
+ });
2645
+ }
2646
+ // `filter.number()` on an execute-script `number` output: the platform
2647
+ // stores the NUMBER envelope the author wrote, while `refs` types the
2648
+ // output from its schema as DECIMAL. Building from `refs` plans
2649
+ // `fieldType` NUMBER -> DECIMAL on every pulled case (#1618: 29
2650
+ // cases across 5 apps, 15 in signatureenvelope). Only this observed
2651
+ // direction is handled; no live DECIMAL envelope on a NUMBER output
2652
+ // has been seen.
2653
+ if (realType?.toUpperCase() === "NUMBER" && declared?.fieldType === "DECIMAL") {
2654
+ return expr.jsonencode({
2655
+ fieldType: "NUMBER",
2656
+ multiple: declared.multiple,
2657
+ taskReference: {
2658
+ name: envelopeName,
2659
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2660
+ },
2661
+ });
2662
+ }
1931
2663
  const ambiguousRecordField = recordRefKeyIsAmbiguous(value.name, wireName, value.taskRefKey, refs)
1932
2664
  ? foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs)
1933
2665
  : undefined;
@@ -1954,14 +2686,37 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1954
2686
  },
1955
2687
  });
1956
2688
  }
2689
+ // A text comparison of a found record's field stores a TEXT envelope
2690
+ // named by field id, while `refs` carries the field's own type
2691
+ // (JSON_TEXT, PICKLIST_ID).
2692
+ const textCastRecordField = realType?.toUpperCase() === "TEXT"
2693
+ ? foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs)
2694
+ : undefined;
2695
+ if (textCastRecordField !== undefined) {
2696
+ return expr.jsonencode({
2697
+ fieldType: "TEXT",
2698
+ multiple: false,
2699
+ taskReference: {
2700
+ name: expr.template(textCastRecordField),
2701
+ taskId: expr.resourceAttr(task.type, task.label, ["id"]),
2702
+ },
2703
+ });
2704
+ }
1957
2705
  return expr.resourceAttr(task.type, task.label, ["refs", { index: wireName }]);
1958
2706
  }
1959
2707
  const recordFieldName = foundRecordFieldReferenceName(task.type, value.name, value.taskRefKey, refs);
1960
- // The short form addresses user-search outputs by path; only `.refs`
1961
- // is keyed by their display labels.
2708
+ // The short form addresses user-search outputs by path, and an AI task's
2709
+ // single output by its canonical name (`response`, edk#1509); only
2710
+ // `.refs` is keyed by their display labels. recordSearch's ASPECT_RECORD_ID
2711
+ // is keyed `First found record id` in refs, but filter RHS / ei export use
2712
+ // the canonical short name `recordId` (service_tasks) — emitting the
2713
+ // display label here plans drift after every pull (edk#1524).
1962
2714
  const shortName = task.type === TASK_RESOURCES.userSearch
1963
2715
  ? USER_SEARCH_PATH_BY_WIRE_NAME.get(wireName) ?? wireName
1964
- : wireName;
2716
+ : task.type === TASK_RESOURCES.recordSearch &&
2717
+ (wireName === "First found record id" || value.name === "record.recordId" || value.name === "recordId")
2718
+ ? "recordId"
2719
+ : canonicalSingleOutputName(task.type, wireName) ?? wireName;
1965
2720
  return expr.template([
1966
2721
  "task.",
1967
2722
  expr.resourceAttr(task.type, task.label, ["id"]),
@@ -1999,7 +2754,7 @@ function filterReferenceToTf(value, refs, role = "value", realType, operator) {
1999
2754
  if (target === undefined) {
2000
2755
  throw new EntityTfError("variable filter reference could not be resolved to a variable task — the referenced workflow variable must be created by a setVariable task in the same automation");
2001
2756
  }
2002
- return expr.template(["variable.", expr.resourceAttr(target.type, target.label, ["variable_id"])]);
2757
+ return expr.template(["variable.", variableIdAttr(target)]);
2003
2758
  }
2004
2759
  default:
2005
2760
  throw new EntityTfError(`unsupported filter reference type "${value.type}"`);
@@ -2050,9 +2805,9 @@ function picklistFilterValueToTf(value, field, refs) {
2050
2805
  // Table siblings excluded for the same reason as in `crossAppFieldToTf`: a
2051
2806
  // picklist field's owner is an app or an element, never a table.
2052
2807
  if (sibling !== undefined && sibling.kind !== "table" && sibling.kind !== "task") {
2053
- const localName = field.tags?.includes("STATUS")
2808
+ const localName = sibling.kind === "app" && field.tags?.includes("STATUS")
2054
2809
  ? `${sibling.tfLabel}_status_options_by_label`
2055
- : field.tags?.includes("STAGE")
2810
+ : sibling.kind === "app" && field.tags?.includes("STAGE")
2056
2811
  ? `${sibling.tfLabel}_stage_options_by_label`
2057
2812
  : `${scopedResourceLabel(sibling.tfLabel, tsLabelToTfLabel(field.refName), sibling.kind)}_options_by_label`;
2058
2813
  return expr.local(localName, [{ index: value }]);
@@ -2066,16 +2821,22 @@ function picklistFilterValueToTf(value, field, refs) {
2066
2821
  const fieldLabel = registerForeignFieldLookup(field, refs.owner, refs.dataBlocks);
2067
2822
  return expr.local(fieldLabel + "_options_by_label", [{ index: value }]);
2068
2823
  }
2069
- const localName = field.tags?.includes("STATUS")
2824
+ const localName = refs.owner.parentScope === "app" && field.tags?.includes("STATUS")
2070
2825
  ? `${refs.owner.appTfLabel}_status_options_by_label`
2071
- : field.tags?.includes("STAGE")
2826
+ : refs.owner.parentScope === "app" && field.tags?.includes("STAGE")
2072
2827
  ? `${refs.owner.appTfLabel}_stage_options_by_label`
2073
- : `${scopedLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName))}_options_by_label`;
2828
+ : `${scopedResourceLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName), refs.owner.parentScope)}_options_by_label`;
2074
2829
  return expr.local(localName, [{ index: value }]);
2075
2830
  }
2076
- function triggerRecordFieldPath(reference) {
2831
+ function triggerRecordFieldPath(reference, refs) {
2077
2832
  if (!isObject(reference) || typeof reference.name !== "string")
2078
2833
  return undefined;
2834
+ if (refs.trigger.type === TRIGGER_RESOURCES.onDemand && reference.type?.toString().toUpperCase() === "TRIGGER") {
2835
+ const onDemandPath = onDemandRecordFieldPath(reference.name, refs);
2836
+ // Field metadata is only known for the automation's own app or element.
2837
+ if (onDemandPath !== undefined)
2838
+ return onDemandPath.isOwner ? onDemandPath : undefined;
2839
+ }
2079
2840
  const path = reference.name.split(".");
2080
2841
  if (path[0] !== "record" || path.length < 2)
2081
2842
  return undefined;
@@ -2092,7 +2853,7 @@ function fieldFromFilterLeftValue(value, refs) {
2092
2853
  taskSearchesOwnerApp(value.value.taskRefKey, refs);
2093
2854
  if (referenceType !== "TRIGGER" && !ownAppTask)
2094
2855
  return undefined;
2095
- const parsed = triggerRecordFieldPath(value.value);
2856
+ const parsed = triggerRecordFieldPath(value.value, refs);
2096
2857
  if (parsed === undefined)
2097
2858
  return undefined;
2098
2859
  const { fieldKey: refName, suffix } = parsed;
@@ -2143,20 +2904,23 @@ function filterToTf(value, refs) {
2143
2904
  referenceRealType: (reference, _role, authored) => {
2144
2905
  if (!isObject(reference) || reference.type?.toString().toUpperCase() !== "TRIGGER")
2145
2906
  return authored;
2146
- const parsed = triggerRecordFieldPath(reference);
2907
+ const parsed = triggerRecordFieldPath(reference, refs);
2147
2908
  if (parsed === undefined)
2148
2909
  return authored;
2149
2910
  const metadata = refs.owner.fieldMetadata.get(parsed.fieldKey);
2150
- // A suffix-less option picklist is a UUID. A bare dynamic dropdown is stored as text.
2151
- if (parsed.suffix === "" && metadata?.fieldType === "PICKLIST" && !isOptionBearingPicklist(metadata)) {
2911
+ // An option picklist's bare or `.id` reference is a UUID. A dynamic dropdown's is stored as text.
2912
+ if ((parsed.suffix === "" || parsed.suffix === "id") && metadata?.fieldType === "PICKLIST" && !isOptionBearingPicklist(metadata)) {
2152
2913
  return authored;
2153
2914
  }
2154
2915
  const inferred = referenceValueTypeForField(metadata?.fieldType, parsed.suffix);
2155
2916
  if (inferred === undefined)
2156
2917
  return authored;
2157
- // Operator fallbacks and `filter.text()` are TEXT. Field metadata is
2158
- // the authority for a known trigger-record field (PICKLIST .id → UUID).
2159
- // Explicit non-TEXT wrappers (`filter.uuid()`, `filter.number()`, …) win.
2918
+ // This hook only sees unmarked references. `filter.text()` and the
2919
+ // other typed wrappers set `explicit`, and the filter codec keeps that
2920
+ // type before calling here. What remains is the operator fallback:
2921
+ // TEXT on an unwrapped trigger-record field yields to field metadata
2922
+ // (PICKLIST `.id` → UUID). A non-TEXT fallback (`gt` → NUMBER) already
2923
+ // names its type.
2160
2924
  const authoredNorm = authored?.toUpperCase();
2161
2925
  if (authoredNorm !== undefined && authoredNorm !== "TEXT")
2162
2926
  return authored;
@@ -2165,6 +2929,22 @@ function filterToTf(value, refs) {
2165
2929
  literal: (literal, field) => picklistFilterValueToTf(literal, token(field), refs) ?? valueToTf(literal, refs),
2166
2930
  });
2167
2931
  }
2932
+ /**
2933
+ * System fields a record-updated trigger cannot meaningfully watch: these never
2934
+ * change after create, or change on every update. Closed At and Closed By change
2935
+ * once, on close, and the platform stores them in changed_fields.
2936
+ */
2937
+ const UNWATCHABLE_SYSTEM_FIELD_KEYS = new Set(["id", "createdAt", "createdBy", "updatedAt", "updatedBy"]);
2938
+ function isRunAutomationValueReference(raw) {
2939
+ if (!isObject(raw))
2940
+ return false;
2941
+ return (isObject(raw.triggerReference) ||
2942
+ isObject(raw.taskReference) ||
2943
+ isObject(raw.forEachReference) ||
2944
+ isObject(raw.templateReference) ||
2945
+ isObject(raw.secretReference) ||
2946
+ isObject(raw.variableReference));
2947
+ }
2168
2948
  function configAttrs(kind, config, refs) {
2169
2949
  const attrs = {};
2170
2950
  for (const [key, raw] of Object.entries(config)) {
@@ -2214,6 +2994,27 @@ function configAttrs(kind, config, refs) {
2214
2994
  attrs.code = raw;
2215
2995
  continue;
2216
2996
  }
2997
+ // execute_script input values: provider Read stores Mobius-normalized
2998
+ // short names for on-demand scalars. Keep that envelope here only —
2999
+ // templates, notifications, and other attrs still use refs["…"].
3000
+ if (key === "inputs" && kind === "elementum_execute_script_task") {
3001
+ if (!Array.isArray(raw))
3002
+ throw new EntityTfError("executeScript inputs must be an array");
3003
+ attrs.inputs = raw.map((item) => {
3004
+ if (!isObject(item) || typeof item.name !== "string") {
3005
+ throw new EntityTfError("invalid executeScript input");
3006
+ }
3007
+ const mapped = {
3008
+ name: item.name,
3009
+ value: executeScriptInputValueToTf(item.value, refs),
3010
+ };
3011
+ if (item.field_mappings !== undefined) {
3012
+ mapped.field_mappings = valueToTf(item.field_mappings, refs);
3013
+ }
3014
+ return mapped;
3015
+ });
3016
+ continue;
3017
+ }
2217
3018
  if (key === "inputMappings" && kind === "elementum_run_automation_task") {
2218
3019
  if (!Array.isArray(raw))
2219
3020
  throw new EntityTfError("runAutomation inputMappings must be an array");
@@ -2248,12 +3049,22 @@ function configAttrs(kind, config, refs) {
2248
3049
  continue;
2249
3050
  }
2250
3051
  if (key === "targetAutomationRef" && kind === "elementum_run_automation_task") {
3052
+ // A Dynamic Reference is a serialized value reference (trigger, task,
3053
+ // loop, template, secret, variable). `{ type: "DYNAMIC" }` is not one;
3054
+ // that shape still has to be a STATIC catalog target.
3055
+ if (isRunAutomationValueReference(raw)) {
3056
+ if (config.synchronous !== true) {
3057
+ throw new EntityTfError("runAutomation Dynamic Reference target requires synchronous: true");
3058
+ }
3059
+ attrs["target_automation_ref"] = valueToTf(raw, refs);
3060
+ continue;
3061
+ }
2251
3062
  if (!isObject(raw) || raw.type !== "STATIC") {
2252
3063
  throw new EntityTfError("runAutomation targetAutomationRef must be { type: \"STATIC\", value: ... }");
2253
3064
  }
2254
3065
  const target = token(raw.value);
2255
3066
  if (target?.__kind === "automation") {
2256
- attrs["target_automation_ref"] = automationRunTargetResourceAttr(refs.owner.appTfLabel, target.refName, refs.owner.activeAutomationRefNames);
3067
+ attrs["target_automation_ref"] = automationRunTargetResourceAttr(refs.owner.appTfLabel, target.refName, refs.owner.activeAutomationRefNames, refs.owner.parentScope, refs.owner.ownerHandle);
2257
3068
  continue;
2258
3069
  }
2259
3070
  // Pull may leave a bare platform UUID when the target automation was
@@ -2412,20 +3223,41 @@ function configAttrs(kind, config, refs) {
2412
3223
  });
2413
3224
  continue;
2414
3225
  }
3226
+ if (key === "changedFieldIds" && Array.isArray(raw)) {
3227
+ const watched = raw.filter((field) => {
3228
+ const fieldToken = token(field);
3229
+ if (fieldToken?.__kind !== "field" ||
3230
+ !UNWATCHABLE_SYSTEM_FIELD_KEYS.has(fieldToken.refName) ||
3231
+ refs.owner.fieldAddresses.has(fieldToken.refName))
3232
+ return true;
3233
+ refs.owner.diagnostics.push(`changedFields: system field "${fieldToken.name ?? fieldToken.refName}" is platform-managed and cannot be watched; dropped`);
3234
+ return false;
3235
+ });
3236
+ // An omitted or empty changed_fields fires the trigger on every field change.
3237
+ if (watched.length === 0 && raw.length > 0) {
3238
+ throw new EntityTfError("changedFields lists only platform-managed system fields, which cannot be watched; " +
3239
+ "list at least one other field, or leave changedFields out to fire on any change");
3240
+ }
3241
+ attrs.changed_fields = valueToTf(watched, refs);
3242
+ continue;
3243
+ }
2415
3244
  if (key === "inputs" && kind === "elementum_on_demand_trigger") {
2416
3245
  if (!Array.isArray(raw))
2417
3246
  throw new EntityTfError("onDemand inputs must be an array");
2418
3247
  const parameters = raw.map((input) => {
2419
3248
  if (!isObject(input))
2420
3249
  throw new EntityTfError("onDemand input must be an object");
3250
+ if (typeof input.type !== "string" || !ON_DEMAND_TF_PARAM_TYPES.has(input.type)) {
3251
+ throw new EntityTfError(`onDemand parameter ${JSON.stringify(input.name)} has type ${JSON.stringify(input.type)}, which ` +
3252
+ `elementum_on_demand_trigger does not support (allowed: text, number, decimal, boolean, date, ` +
3253
+ `datetime, userId, attachmentId, record). Use "text" for a JSON string.`);
3254
+ }
2421
3255
  const mapped = Object.fromEntries(Object.entries(input)
2422
3256
  .filter(([k]) => k !== "app")
2423
3257
  .map(([k, v]) => [
2424
3258
  CONFIG_ATTRS[k] ?? snake(k),
2425
3259
  valueToTf(k === "defaultValue" ? unwrapDefault(v) :
2426
- k === "type" && v === "ATTACHMENT_ID" ? "attachment" :
2427
- k === "type" && v === "ASPECT_RECORD" ? "record" :
2428
- k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
3260
+ k === "type" && typeof v === "string" ? ON_DEMAND_TF_PARAM_TYPES.get(v) : v, refs),
2429
3261
  ]));
2430
3262
  if (isOnDemandRecordType(typeof input.type === "string" ? input.type : undefined)) {
2431
3263
  const target = token(input.app);
@@ -2445,6 +3277,8 @@ function configAttrs(kind, config, refs) {
2445
3277
  if (key === "workflowFields") {
2446
3278
  if (!Array.isArray(raw))
2447
3279
  throw new EntityTfError("workflowFields must be an array");
3280
+ if (kind === "elementum_create_record_task")
3281
+ assertElementCreateSetsTitle(config.aspectId, raw);
2448
3282
  attrs.fields = raw.map((field) => {
2449
3283
  if (!isObject(field))
2450
3284
  throw new EntityTfError("workflow field must be an object");
@@ -2476,12 +3310,20 @@ function configAttrs(kind, config, refs) {
2476
3310
  ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
2477
3311
  };
2478
3312
  }
3313
+ assertLiteralFitsFieldType(staticValue, fieldToken);
2479
3314
  const optionValue = staticValue !== undefined
2480
3315
  ? picklistFilterValueToTf(staticValue, fieldToken, refs)
2481
3316
  : undefined;
3317
+ let reference = field.valueReference;
3318
+ if (typeof reference === "string") {
3319
+ reference = normalizeTriggerRecordIdEnvelopeString(reference, refs);
3320
+ }
3321
+ else if (isObject(reference) && typeof reference.value === "string" && Object.keys(reference).length === 1) {
3322
+ reference = { value: normalizeTriggerRecordIdEnvelopeString(reference.value, refs) };
3323
+ }
2482
3324
  return {
2483
3325
  field_id: valueToTf(field.aspectFieldId, refs),
2484
- value: optionValue ?? valueToTf(field.valueReference, refs),
3326
+ value: optionValue ?? valueToTf(reference, refs),
2485
3327
  ...(field.operation === "ADD" ? { update_mode: "add" } : {}),
2486
3328
  };
2487
3329
  });
@@ -2547,12 +3389,34 @@ function configAttrs(kind, config, refs) {
2547
3389
  if (key === "basicAuth" && kind === "elementum_api_task") {
2548
3390
  if (!isObject(raw))
2549
3391
  throw new EntityTfError("apiRequest basicAuth must be an object");
3392
+ // A requiredSecret username is write-only on the platform: emit the
3393
+ // provider's write-only username_wo so a null read never plans a
3394
+ // change (edk#1400).
3395
+ // A secret("KEY") username is bound to a vault entry: emit
3396
+ // reference_username so the platform resolves it at runtime instead of
3397
+ // storing the lookup as a static username (edk#1283).
2550
3398
  attrs.basic_auth = {
2551
- username: valueToTf(raw.username, refs),
3399
+ ...(isVaultSecretRaw(raw.username)
3400
+ ? { reference_username: valueToTf(raw.username, refs) }
3401
+ : isRequiredSecretRaw(raw.username)
3402
+ ? { username_wo: valueToTf(raw.username, refs) }
3403
+ : { username: valueToTf(raw.username, refs) }),
2552
3404
  ...(raw.referencePassword !== undefined ? { reference_password: valueToTf(raw.referencePassword, refs) } : {}),
2553
3405
  };
2554
3406
  continue;
2555
3407
  }
3408
+ if (key === "headers" && kind === "elementum_api_task" && Array.isArray(raw)) {
3409
+ // A requiredSecret header value is unreadable on the platform: emit the
3410
+ // write-only value_wo so the imported null never plans a change (edk#1400).
3411
+ attrs.headers = raw.map((h) => {
3412
+ if (!isObject(h))
3413
+ throw new EntityTfError("invalid apiRequest header");
3414
+ const header = { name: valueToTf(h.name, refs) };
3415
+ header[isRequiredSecretRaw(h.value) ? "value_wo" : "value"] = valueToTf(h.value, refs);
3416
+ return header;
3417
+ });
3418
+ continue;
3419
+ }
2556
3420
  if (key === "bearerAuth" && kind === "elementum_api_task") {
2557
3421
  if (!isObject(raw))
2558
3422
  throw new EntityTfError("apiRequest bearerAuth must be an object");
@@ -2575,8 +3439,15 @@ function configAttrs(kind, config, refs) {
2575
3439
  attrs.oauth = {
2576
3440
  request_type: valueToTf(raw.requestType, refs),
2577
3441
  ...(raw.url !== undefined ? { url: valueToTf(raw.url, refs) } : {}),
2578
- ...(raw.clientId !== undefined ? { client_id: valueToTf(raw.clientId, refs) } : {}),
2579
- ...(raw.clientSecret !== undefined ? { client_secret: valueToTf(raw.clientSecret, refs) } : {}),
3442
+ // secret("KEY") client credentials bind to vault entries through the
3443
+ // reference_ attributes; a static string stays client_id/client_secret
3444
+ // (edk#1283).
3445
+ ...(raw.clientId !== undefined
3446
+ ? { [isVaultSecretRaw(raw.clientId) ? "reference_client_id" : "client_id"]: valueToTf(raw.clientId, refs) }
3447
+ : {}),
3448
+ ...(raw.clientSecret !== undefined
3449
+ ? { [isVaultSecretRaw(raw.clientSecret) ? "reference_client_secret" : "client_secret"]: valueToTf(raw.clientSecret, refs) }
3450
+ : {}),
2580
3451
  ...(headers !== undefined ? { headers } : {}),
2581
3452
  };
2582
3453
  continue;
@@ -2608,6 +3479,12 @@ function configAttrs(kind, config, refs) {
2608
3479
  };
2609
3480
  continue;
2610
3481
  }
3482
+ // The platform stores whatever string it is given and the trigger or task
3483
+ // then never matches an alias, so an alias name instead of its id only
3484
+ // shows up as mail that is silently not ingested.
3485
+ if (key === "emailAliasId" && typeof raw === "string" && !UUID_PATTERN.test(raw)) {
3486
+ throw new EntityTfError(`emailAliasId "${raw}" is not an email alias id; pass the alias's platform id (a UUID), not its name or address`);
3487
+ }
2611
3488
  const attr = CONFIG_ATTRS[key] ?? snake(key);
2612
3489
  attrs[attr] = valueToTf(raw, refs);
2613
3490
  }
@@ -2641,11 +3518,20 @@ function fileReaderDependsOn(blocks) {
2641
3518
  return deps;
2642
3519
  }
2643
3520
  /** App- or element-owned `automation` entity → provider HCL blocks. */
3521
+ function elementHandleOf(explicit, payload) {
3522
+ if (explicit !== undefined && explicit !== "")
3523
+ return explicit;
3524
+ if (payload === null || typeof payload !== "object" || !("handle" in payload))
3525
+ return undefined;
3526
+ const handle = payload.handle;
3527
+ return typeof handle === "string" && handle !== "" ? handle : undefined;
3528
+ }
2644
3529
  export function automationToTf(entity, ctx) {
2645
- const automationTfLabel = scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(entity.refName));
3530
+ const automationTfLabel = automationResourceLabel(ctx.appTfLabel, entity.refName, ctx.parentScope, ctx.parentScope === "element" ? ctx.ownerHandle : undefined);
2646
3531
  const owner = {
2647
3532
  appRefName: ctx.appRefName ?? entity.parent,
2648
3533
  parentScope: ctx.parentScope ?? "app",
3534
+ ownerHandle: ctx.ownerHandle,
2649
3535
  appTfLabel: ctx.appTfLabel,
2650
3536
  automationTfLabel,
2651
3537
  fieldAddresses: ctx.fieldAddresses ?? new Map(),
@@ -2656,6 +3542,9 @@ export function automationToTf(entity, ctx) {
2656
3542
  workspaceAspects: ctx.workspaceAspects,
2657
3543
  diagnostics: ctx.diagnostics ?? [],
2658
3544
  activeAutomationRefNames: ctx.activeAutomationRefNames,
3545
+ ...(ctx.elementsWithoutAuditFields !== undefined ? { elementsWithoutAuditFields: ctx.elementsWithoutAuditFields } : {}),
3546
+ ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
3547
+ recordLacksAuditFields: ctx.parentScope === "element" && ctx.ownerAuditFields !== true,
2659
3548
  };
2660
3549
  if (entity.kind !== "automation")
2661
3550
  throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}"`);
@@ -2665,6 +3554,19 @@ export function automationToTf(entity, ctx) {
2665
3554
  const payload = entity.payload;
2666
3555
  if (payload === null || typeof payload !== "object" || Array.isArray(payload))
2667
3556
  throw new EntityTfError(`automation "${entity.refName}" has a non-object payload`);
3557
+ const unresolved = unresolvedForEachFailures(entity, payload, `${AUTOMATION_RESOURCE_TYPE}.${automationTfLabel}`);
3558
+ if (unresolved.length > 0)
3559
+ throw new ValidationFailureError(unresolved);
3560
+ const recordIdMappings = recordIdFieldMappingFailures(entity, payload, `${AUTOMATION_RESOURCE_TYPE}.${automationTfLabel}`);
3561
+ if (recordIdMappings.length > 0) {
3562
+ // Fatal for build/plan/apply. Pull is a read of live config: it warns by
3563
+ // name and keeps emitting the live shape, so the source is still written
3564
+ // and the user can fix it (edk#1499).
3565
+ if (currentValidationMode() === "pull")
3566
+ recordValidations(recordIdMappings.map((failure) => ({ ...failure, severity: "warning" })));
3567
+ else
3568
+ throw new ValidationFailureError(recordIdMappings);
3569
+ }
2668
3570
  if (typeof payload.workflowRevision !== "string")
2669
3571
  throw new EntityTfError(`automation "${entity.refName}" has no workflowRevision`);
2670
3572
  const label = automationTfLabel;
@@ -2742,18 +3644,22 @@ export function automationToTf(entity, ctx) {
2742
3644
  ? [[field.name, { fieldType: field.type, multiple: false }]]
2743
3645
  : []))
2744
3646
  : undefined;
3647
+ const recordTarget = FOUND_RECORD_TASK_TYPES.has(resourceType)
3648
+ ? token(taskBody.aspectId ?? taskBody.relatedAspectId)
3649
+ : undefined;
2745
3650
  taskRefs.set(refKey, {
2746
3651
  type: resourceType,
2747
3652
  label: registeredLabel,
2748
3653
  ...(wireType === "unimplementedTask" ? { isData: true } : {}),
2749
3654
  ...(outputFieldTypes !== undefined && outputFieldTypes.size > 0 ? { outputFieldTypes } : {}),
3655
+ ...(recordTarget !== undefined ? { recordTarget } : {}),
2750
3656
  });
2751
3657
  if (wireType === "variable" && Array.isArray(taskBody.create)) {
2752
- for (const candidate of taskBody.create) {
3658
+ taskBody.create.forEach((candidate, index) => {
2753
3659
  if (isObject(candidate) && typeof candidate.id === "string" && typeof candidate.name === "string") {
2754
- variableById.set(candidate.id, { type: "elementum_variable_task", label: registeredLabel, name: candidate.name });
3660
+ variableById.set(candidate.id, { type: "elementum_variable_task", label: registeredLabel, name: candidate.name, index });
2755
3661
  }
2756
- }
3662
+ });
2757
3663
  }
2758
3664
  for (const child of task.children ?? [])
2759
3665
  preRegister(child.tasks ?? []);
@@ -2764,7 +3670,7 @@ export function automationToTf(entity, ctx) {
2764
3670
  // output. Everything else - a script array, a file-reader payload, an API
2765
3671
  // response, a variable, a nested item sub-array - keys its items by their
2766
3672
  // own keys, so their names pass through untouched.
2767
- const recordItemForEachRefKeys = new Set([...forEachCollectionByRefKey].flatMap(([refKey, collection]) => {
3673
+ const recordItemForEachSourceByRefKey = new Map([...forEachCollectionByRefKey].flatMap(([refKey, collection]) => {
2768
3674
  if (!isObject(collection) || !isObject(collection.taskReference))
2769
3675
  return [];
2770
3676
  const sourceRefKey = collection.taskReference.taskRefKey;
@@ -2772,9 +3678,10 @@ export function automationToTf(entity, ctx) {
2772
3678
  return [];
2773
3679
  const sourceWireType = wireTypeByRefKey.get(sourceRefKey);
2774
3680
  return sourceWireType !== undefined && RECORD_COLLECTION_TASK_WIRE_TYPES.has(sourceWireType)
2775
- ? [refKey]
3681
+ ? [[refKey, sourceRefKey]]
2776
3682
  : [];
2777
3683
  }));
3684
+ const recordItemForEachRefKeys = new Set(recordItemForEachSourceByRefKey.keys());
2778
3685
  const dataBlocks = new Map();
2779
3686
  const recordFieldContext = recordFieldContextOf(entity);
2780
3687
  const triggerParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
@@ -2785,6 +3692,15 @@ export function automationToTf(entity, ctx) {
2785
3692
  ? [input.name]
2786
3693
  : [])
2787
3694
  : [];
3695
+ const userParamNames = triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
3696
+ ? triggerConfig.inputs.flatMap((input) => isObject(input) && typeof input.name === "string" && input.type === "USER_ID" ? [input.name] : [])
3697
+ : [];
3698
+ const triggerParamFieldTypes = new Map(triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
3699
+ ? triggerConfig.inputs.flatMap((input) => isObject(input) && typeof input.name === "string" && typeof input.type === "string" &&
3700
+ !isOnDemandRecordType(input.type)
3701
+ ? [[input.name, { fieldType: input.type, multiple: input.multiple === true }]]
3702
+ : [])
3703
+ : []);
2788
3704
  const recordParamTargets = new Map(triggerKey === "onDemand" && isObject(triggerConfig) && Array.isArray(triggerConfig.inputs)
2789
3705
  ? triggerConfig.inputs.flatMap((input) => {
2790
3706
  if (!isObject(input) ||
@@ -2817,12 +3733,16 @@ export function automationToTf(entity, ctx) {
2817
3733
  trigger: { type: triggerType, label },
2818
3734
  triggerParamNames,
2819
3735
  recordParamNames,
3736
+ triggerParamFieldTypes,
2820
3737
  recordParamTargets,
3738
+ userParamNames,
2821
3739
  tasks: taskRefs,
2822
3740
  owner,
2823
3741
  dataBlocks,
2824
3742
  variableById,
3743
+ requiredSecrets: new Set(),
2825
3744
  recordItemForEachRefKeys,
3745
+ recordItemForEachSourceByRefKey,
2826
3746
  ...(recordFieldContext !== undefined ? { recordFieldContext } : {}),
2827
3747
  ...(ctx.fieldNamesByAppRefName !== undefined ? { fieldNamesByAppRefName: ctx.fieldNamesByAppRefName } : {}),
2828
3748
  ...(ctx.fieldAddressesByAppRefName !== undefined ? { fieldAddressesByAppRefName: ctx.fieldAddressesByAppRefName } : {}),
@@ -2935,26 +3855,24 @@ export function automationToTf(entity, ctx) {
2935
3855
  }
2936
3856
  if (wireType === "variable") {
2937
3857
  const variableType = variableTaskResourceType(inner, refKey);
2938
- const isCreate = variableType === "elementum_variable_task";
2939
3858
  const creates = Array.isArray(inner.create) ? inner.create : [];
2940
3859
  const updates = Array.isArray(inner.update) ? inner.update : [];
2941
- const item = (isCreate ? creates[0] : updates[0]);
2942
- if (!isObject(item))
2943
- throw new EntityTfError(`invalid setVariable item on "${refKey}"`);
2944
3860
  const variableAttrs = { parent: taskParent, name: displayName };
2945
- if (isCreate) {
2946
- if (typeof item.name !== "string" || typeof item.type !== "string")
2947
- throw new EntityTfError(`variable task "${refKey}" requires name and type`);
2948
- variableAttrs.variable_name = item.name;
2949
- variableAttrs.variable_type = item.type;
2950
- if (item.value !== undefined)
2951
- variableAttrs.value = valueToTf(item.value, refs);
3861
+ if (creates.length > 0) {
3862
+ variableAttrs.variables = creates.map((item) => {
3863
+ if (!isObject(item) || typeof item.name !== "string" || typeof item.type !== "string") {
3864
+ throw new EntityTfError(`variable task "${refKey}" requires name and type on every variable`);
3865
+ }
3866
+ return { name: item.name, type: item.type, ...(item.value !== undefined ? { value: valueToTf(item.value, refs) } : {}) };
3867
+ });
2952
3868
  }
2953
- else {
2954
- // elementum_update_variable_task's real attribute is
2955
- // variable_reference (see from-tf.ts's matching comment).
2956
- variableAttrs.variable_reference = valueToTf(item.variable, refs);
2957
- variableAttrs.value = valueToTf(item.value, refs);
3869
+ if (updates.length > 0) {
3870
+ // The provider's attribute is variable_reference; the authoring key stays "variable".
3871
+ variableAttrs.updates = updates.map((item) => {
3872
+ if (!isObject(item))
3873
+ throw new EntityTfError(`invalid setVariable item on "${refKey}"`);
3874
+ return { variable_reference: valueToTf(item.variable, refs), value: valueToTf(item.value, refs) };
3875
+ });
2958
3876
  }
2959
3877
  blocks.push({ kind: "resource", type: variableType, label: tfLabel, attrs: variableAttrs });
2960
3878
  const address = expr.resourceAttr(variableType, tfLabel);
@@ -3137,6 +4055,7 @@ export function automationToTf(entity, ctx) {
3137
4055
  ? { outputs: outputValues.map((output) => {
3138
4056
  if (typeof output.name !== "string")
3139
4057
  throw new EntityTfError("automation output has no name");
4058
+ assertPublishableOutputTask(output.name, output.value, payload.tasks ?? [], refs);
3140
4059
  return { name: output.name, value: workflowPublishOutputValueToTf(output.value, refs) };
3141
4060
  }) }
3142
4061
  : {}),
@@ -3144,5 +4063,36 @@ export function automationToTf(entity, ctx) {
3144
4063
  };
3145
4064
  blocks.push(publish);
3146
4065
  }
3147
- return { blocks: [...[...dataBlocks.values()].sort((a, b) => (a.type + "." + a.label).localeCompare(b.type + "." + b.label)), ...blocks], address: AUTOMATION_RESOURCE_TYPE + "." + label };
4066
+ const secretBlocks = [...refs.requiredSecrets].sort().map(requiredSecretVariableBlock);
4067
+ return { blocks: [...secretBlocks, ...[...dataBlocks.values()].sort((a, b) => (a.type + "." + a.label).localeCompare(b.type + "." + b.label)), ...blocks], address: AUTOMATION_RESOURCE_TYPE + "." + label };
4068
+ }
4069
+ function requiredSecretVariableBlock(name) {
4070
+ return {
4071
+ kind: "variable",
4072
+ label: name,
4073
+ attrs: {
4074
+ sensitive: true,
4075
+ description: `Write-only secret. Supply a non-empty value as TF_VAR_${name} before plan or apply.`,
4076
+ },
4077
+ variableValidation: {
4078
+ condition: `var.${name} != ""`,
4079
+ errorMessage: `TF_VAR_${name} must be a non-empty value. An empty string would overwrite the live write-only secret.`,
4080
+ },
4081
+ };
4082
+ }
4083
+ /** A serialized secret("KEY") vault-entry reference, optionally wrapped as { value: X }. */
4084
+ function isVaultSecretRaw(value) {
4085
+ if (!isObject(value))
4086
+ return false;
4087
+ if ("value" in value && Object.keys(value).length === 1)
4088
+ return isVaultSecretRaw(value.value);
4089
+ return isObject(value.secretReference) && typeof value.secretReference.secretId === "string";
4090
+ }
4091
+ function isRequiredSecretRaw(value) {
4092
+ if (!isObject(value))
4093
+ return false;
4094
+ // serializeValueOrRef wraps a plain value as { value: X } (unwrapped by valueToTf).
4095
+ if ("value" in value && Object.keys(value).length === 1)
4096
+ return isRequiredSecretRaw(value.value);
4097
+ return value.kind === "requiredSecret" && typeof value.variable === "string";
3148
4098
  }